@extends('app')

@section('content')
<section class="book_section layout_padding">
    <div class="container">
        <h4 style="font-size: 36px;">Timbangan <span>Pintar</span></h4>

        @if(session('success'))
            <div class="alert alert-success">
                {{ session('success') }}
            </div>
        @endif

        @if(session('error'))
            <div class="alert alert-danger">
                {{ session('error') }}
            </div>
        @endif

        @if($errors->any())
            <div class="alert alert-danger">
                <ul>
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <div class="row">
            <!-- Tinggi Badan -->
            <div class="col-lg-6 col-md-6 mb-4">
                <div class="card text-center shadow p-4">
                    <div class="card-body">
                        <h5 class="card-title">Tinggi Badan</h5>
                        <p class="card-text" style="font-size: 80px; font-weight: bold;">
                            <span id="tinggiOutput">{{ $tinggi ?? '-' }}</span>
                            <span style="font-size: 24px; color: #00c6a9;">cm</span>
                        </p>
                    </div>
                </div>
            </div>

            <!-- Berat Badan -->
            <div class="col-lg-6 col-md-6 mb-4">
                <div class="card text-center shadow p-4">
                    <div class="card-body">
                        <h5 class="card-title">Berat Badan</h5>
                        <p class="card-text" style="font-size: 80px; font-weight: bold;">
                            <span id="beratOutput">{{ $berat ?? '-' }}</span>
                            <span style="font-size: 24px; color: #00c6a9;">kg</span>
                        </p>
                    </div>
                </div>
            </div>
        </div>

        <form action="{{ route('timbangan.store') }}" method="POST" id="formTimbangan">
            @csrf
            <input type="hidden" id="beratInput" name="berat" value="{{ $berat }}">
            <input type="hidden" id="tinggiInput" name="tinggi" value="{{ $tinggi }}">

            <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...">
            </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($balitas as $balita)
                        <option value="{{ $balita->nama_anak }}"
                            data-nik="{{ $balita->nik }}"
                            data-tanggal-lahir="{{ $balita->tanggal_lahir }}">
                            {{ $balita->nama_anak }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="form-group">
                <label for="nik">NIK</label>
                <input type="text" id="nik" name="nik" class="form-control" readonly required>
            </div>

            <div class="form-group">
                <label for="umur">Umur (bulan)</label>
                <input type="number" id="umur" name="umur" class="form-control" required>
            </div>

            <div class="form-group">
                <label for="tanggal_pemeriksaan">Tanggal Pemeriksaan</label>
                <input type="date" id="tanggal_pemeriksaan" name="tanggal_pemeriksaan" class="form-control" value="{{ date('Y-m-d') }}" required>
            </div>

            <div class="form-group">
                <label for="hasil_analisis">Hasil Analisis</label>
                <select id="hasil_analisis" name="hasil_analisis" class="form-control" required>
                    <option value="">-- Pilih Hasil Analisis --</option>
                    <option value="Pertumbuhan Normal">Pertumbuhan Normal</option>
                    <option value="Berpotensi Stunting">Berpotensi Stunting</option>
                    <option value="Terindikasi Stunting">Terindikasi Stunting</option>
                    <option value="Hasil Analisis AI">Hasil Analisis AI</option>
                </select>
            </div>

            <div class="form-group">
                <label for="catatan">Catatan Tambahan (misalnya alergi, keluhan)</label>
                <textarea name="catatan" id="catatan" class="form-control"></textarea>
            </div>

            <button type="submit" class="btn btn-primary">Simpan</button>
            <button type="submit" class="btn btn-secondary" formaction="{{ route('analisis.ai') }}">Analisis AI</button>
        </form>

        <hr>
    </div>
</section>

<script>
document.getElementById('nama').addEventListener('change', function () {
    const selected = this.options[this.selectedIndex];
    const nik = selected.getAttribute('data-nik');
    const tanggalLahir = selected.getAttribute('data-tanggal-lahir');

    document.getElementById('nik').value = nik;

    const birthDate = new Date(tanggalLahir);
    const today = new Date();
    let months = (today.getFullYear() - birthDate.getFullYear()) * 12;
    months += today.getMonth() - birthDate.getMonth();
    if (today.getDate() < birthDate.getDate()) {
        months -= 1;
    }
    document.getElementById('umur').value = months;
});

document.getElementById('search_nama').addEventListener('input', function () {
    const keyword = this.value.toLowerCase();
    const options = document.querySelectorAll('#nama option');
    options.forEach(option => {
        option.style.display = option.text.toLowerCase().includes(keyword) ? 'block' : 'none';
    });
});

function updateTimbangan() {
    fetch('/timbangan-data')
        .then(response => response.json())
        .then(data => {
            const tinggi = data.tinggi ?? '-';
            const berat = data.berat ?? '-';
            document.getElementById('tinggiOutput').innerText = tinggi;
            document.getElementById('beratOutput').innerText = berat;

            document.getElementById('tinggiInput').value = tinggi;
            document.getElementById('beratInput').value = berat;
        })
        .catch(error => console.error('Gagal mengambil data timbangan:', error));
}
updateTimbangan();
setInterval(updateTimbangan, 3000);

document.getElementById('formTimbangan').addEventListener('submit', function (e) {
    const berat = document.getElementById('beratInput').value;
    const tinggi = document.getElementById('tinggiInput').value;
    const hasilAnalisis = document.getElementById('hasil_analisis').value;

    if (!berat || !tinggi || berat === '-' || tinggi === '-') {
        e.preventDefault();
        alert("Data berat dan tinggi belum tersedia.");
        return;
    }

    if (!hasilAnalisis) {
        e.preventDefault();
        alert("Silakan pilih hasil analisis terlebih dahulu.");
        return;
    }
});

function submitAnalisisAI() {
    const nama = document.getElementById('nama').value;
    const umur = document.getElementById('umur').value;
    const berat = document.getElementById('beratInput').value;
    const tinggi = document.getElementById('tinggiInput').value;
    const catatan = document.getElementById('catatan').value;

    fetch("{{ route('analisis.ai') }}", {
        method: "POST",
        headers: {
            "X-CSRF-TOKEN": "{{ csrf_token() }}",
            "Content-Type": "application/json"
        },
        body: JSON.stringify({ nama, umur, berat, tinggi, catatan })
    })
    .then(response => response.text())
    .then(() => {
        window.location.href = "{{ route('timbangan.index') }}";
    })
    .catch(error => alert('Gagal menganalisis dengan AI: ' + error));
}
</script>
@endsection
