<?php

namespace App\Http\Controllers;

use App\Models\RiwayatPemeriksaan;
use Illuminate\Http\Request;

class GrafikPertumbuhanController extends Controller
{
    public function index(Request $request)
    {
        // Search query for filtering baby names
        $namaSearch = $request->input('search_nama');
        $riwayatPemeriksaan = collect();

        // Fetch the filtered records based on name search if provided
        if ($namaSearch) {
            $riwayatPemeriksaan = RiwayatPemeriksaan::where('nama', 'like', '%' . $namaSearch . '%')
                ->orderBy('tanggal_pemeriksaan', 'asc')
                ->get();
        } elseif ($request->has('nama')) {
            $nama = $request->input('nama');
            $riwayatPemeriksaan = RiwayatPemeriksaan::where('nama', $nama)
                ->orderBy('tanggal_pemeriksaan', 'asc')
                ->get();
        }

        // Fetch all unique baby names from RiwayatPemeriksaan table for the dropdown
        $namaBalitas = RiwayatPemeriksaan::select('nama')->distinct()->get();

        // If it's an AJAX request, return the data as JSON
        if ($request->ajax()) {
            return response()->json($riwayatPemeriksaan);
        }

        return view('grafik_pertumbuhan', compact('riwayatPemeriksaan', 'namaBalitas', 'namaSearch'));
    }
}
