<!DOCTYPE html>
<html lang="id">

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
  <title>Grafik Pertumbuhan - NutriPosy</title>
  <link rel="icon" type="image/png" href="images/nutriposy.png">
  <link rel="stylesheet" href="{{ asset('css/bootstrap.css') }}" />
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet">
  <link href="{{ asset('css/font-awesome.min.css') }}" rel="stylesheet" />
  <link href="{{ asset('css/style.css') }}" rel="stylesheet" />
  <link href="{{ asset('css/responsive.css') }}" rel="stylesheet" />
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>

<body>

  <div class="hero_area">
    <header class="header_section">
      <div class="header_bottom">
        <div class="container-fluid">
          <nav class="navbar navbar-expand-lg custom_nav-container">
            <a class="navbar-brand" href="#">
              <img src="images/nutriposy.png" alt="NutriPosy Logo">
            </a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
              aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
              <div class="d-flex mr-auto flex-column flex-lg-row align-items-center">
                <ul class="navbar-nav">
                  <li class="nav-item active">
                    <a class="nav-link" href="{{ route('dashboard') }}">Beranda</a>
                  </li>
                </ul>
              </div>
            </div>
          </nav>
        </div>
      </div>
    </header>

<section class="book_section layout_padding">
    <div class="container">
        <h4>Grafik <span>Pertumbuhan</span></h4>

        <!-- Search and Dropdown for Baby Name -->
        <form method="GET" action="{{ route('grafik.pertumbuhan') }}" class="mb-4" id="searchForm">
            <div class="form-group">
                <label for="search_nama">Cari Nama Balita</label>
                <input type="text" id="search_nama" class="form-control" placeholder="Ketik nama balita..." oninput="filterNames()">
            </div>

            <div class="form-group">
                <label for="nama">Pilih Nama Balita</label>
                <select id="nama" name="nama" class="form-control" required>
                    <option value="">-- Pilih Nama --</option>
                    @foreach($namaBalitas as $balita)
                        <option value="{{ $balita->nama }}" {{ $balita->nama == old('nama', $namaSearch) ? 'selected' : '' }}>
                            {{ $balita->nama }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-primary">Tampilkan Grafik</button>
            </div>
        </form>

        @if($riwayatPemeriksaan->count() > 0)
            <!-- Display Weight and Height Charts -->
            <div class="row">
                <div class="col-md-6">
                    <h5>Grafik Berat Badan</h5>
                    <canvas id="weightChart"></canvas>
                </div>
                <div class="col-md-6">
                    <h5>Grafik Tinggi Badan</h5>
                    <canvas id="heightChart"></canvas>
                </div>
            </div>
        @else
            <div class="alert alert-info">Silakan pilih balita untuk melihat grafik pertumbuhan.</div>
        @endif
    </div>
</section>

@if($riwayatPemeriksaan->count() > 0)
<script>
    // Function to filter the dropdown options based on search input
    function filterNames() {
        var input = document.getElementById('search_nama').value.toLowerCase();
        var select = document.getElementById('nama');
        var options = select.getElementsByTagName('option');

        // Loop through the options and hide those that don't match the search query
        for (var i = 1; i < options.length; i++) { // Start from 1 to skip the first empty option
            var option = options[i];
            if (option.text.toLowerCase().includes(input)) {
                option.style.display = "block"; // Show option if it matches
            } else {
                option.style.display = "none"; // Hide option if it doesn't match
            }
        }
    }

    // Format the date to DD/MM/YYYY
    function formatDate(dateString) {
        const date = new Date(dateString);
        const day = ('0' + date.getDate()).slice(-2);
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const year = date.getFullYear();
        return day + '/' + month + '/' + year;
    }

    // Initial Data for the chart (if available)
    var initialData = @json($riwayatPemeriksaan);
    var selectedName = '{{ old('nama', $namaSearch) }}'; // Selected name from the dropdown

    var labels = initialData.map(function (item) {
        return formatDate(item.tanggal_pemeriksaan); // Format the date for X axis
    });

    var beratData = initialData.map(function (item) {
        return item.berat; // Weight for Y axis
    });

    var tinggiData = initialData.map(function (item) {
        return item.tinggi; // Height for Y axis
    });

    // Create two separate charts: one for weight and one for height
    var weightCtx = document.getElementById('weightChart').getContext('2d');
    var heightCtx = document.getElementById('heightChart').getContext('2d');

    var weightChart = new Chart(weightCtx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Berat (kg)',
                data: beratData,
                borderColor: 'rgba(75, 192, 192, 1)',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                fill: false,
            },
            {
                label: 'Normal BB Laki-laki (kg)',
                data: [2.5, 3.4, 5.1, 6.4, 7.2, 7.8], // Berat Normal Laki-laki (BB/U)
                borderColor: 'rgba(255, 99, 132, 1)',
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                fill: false,
            },
            {
                label: 'Normal BB Perempuan (kg)',
                data: [2.4, 3.2, 4.6, 5.8, 6.7, 7.0], // Berat Normal Perempuan (BB/U)
                borderColor: 'rgba(153, 102, 255, 1)',
                backgroundColor: 'rgba(153, 102, 255, 0.2)',
                fill: false,
            }]
        },
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: 'Grafik Berat Badan ' + selectedName // Display the name dynamically in the title
                }
            },
            scales: {
                x: {
                    title: {
                        display: true,
                        text: 'Tanggal Pemeriksaan'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: 'Berat Badan (kg)'
                    }
                }
            }
        }
    });

    var heightChart = new Chart(heightCtx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Tinggi (cm)',
                data: tinggiData,
               borderColor: 'rgba(75, 192, 192, 1)',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                fill: false,
            },
            {
                label: 'Normal PB Laki-laki (cm)',
                data: [46.1, 57.3, 63.6, 67.3, 69.2], // Tinggi Normal Laki-laki (PB/U)
                borderColor: 'rgba(255, 99, 132, 1)',
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                fill: false,
            },
            {
                label: 'Normal PB Perempuan (cm)',
                data: [45.4, 55.6, 61.2, 65.0, 67.3], // Tinggi Normal Perempuan (PB/U)
              borderColor: 'rgba(153, 102, 255, 1)',
                backgroundColor: 'rgba(153, 102, 255, 0.2)',
                fill: false,
            }]
        },
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: 'Grafik Tinggi Badan ' + selectedName // Display the name dynamically in the title
                }
            },
            scales: {
                x: {
                    title: {
                        display: true,
                        text: 'Tanggal Pemeriksaan'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: 'Tinggi Badan (cm)'
                    }
                }
            }
        }
    });

    // AJAX for dynamic chart update based on selected name or search
    document.getElementById('nama').addEventListener('change', function (e) {
        var selectedName = e.target.value;

        // Send AJAX request to fetch the data for the selected name
        fetch('{{ route('grafik.pertumbuhan') }}?nama=' + selectedName, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            // Update the chart with new data
            var labels = data.map(function (item) {
                return formatDate(item.tanggal_pemeriksaan);
            });

            var beratData = data.map(function (item) {
                return item.berat;
            });

            var tinggiData = data.map(function (item) {
                return item.tinggi;
            });

            // Update weight chart data
            weightChart.data.labels = labels;
            weightChart.data.datasets[0].data = beratData;
            weightChart.update();

            // Update height chart data
            heightChart.data.labels = labels;
            heightChart.data.datasets[0].data = tinggiData;
            heightChart.update();
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
    });
</script>
@endif


  <!-- footer section -->
  <footer class="footer_section">
    <div class="container">
      <p>
        &copy; <span id="displayYear"></span> All Rights Reserved By
        <a href="#">NutriPosy</a>
      </p>
    </div>
  </footer>
</div>

<script src="{{ asset('js/jquery-3.4.1.min.js') }}"></script>
<script src="{{ asset('js/bootstrap.js') }}"></script>

</body>

</html>
