<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\CatatanKesehatan;
use Illuminate\Http\Request;

class CatatanKesehatanController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $santri = $user->santri;

        if (!$santri) {
            return response()->json([
                'success' => false,
                'message' => 'Data santri tidak ditemukan',
                'data' => [],
            ], 404);
        }

        $catatan = CatatanKesehatan::with(['santri', 'kelas'])
            ->where('santri_id', $santri->id)
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'santri_id' => $item->santri_id,
                    'santri_nama' => $item->santri->nama ?? '-',
                    'kelas_id' => $item->kelas_id,
                    'kelas_nama' => $item->kelas->nama_kelas ?? '-',
                    'keluhan' => $item->keluhan,
                    'diagnosis' => $item->diagnosis,
                    'saran' => $item->saran,
                    'created_at' => $item->created_at,
                    'updated_at' => $item->updated_at,
                ];
            });

        return response()->json([
            'success' => true,
            'message' => 'Data catatan kesehatan berhasil diambil',
            'data' => $catatan,
        ]);
    }

    public function notifikasi(Request $request)
    {
        $user = $request->user();
        $santri = $user->santri;

        if (!$santri) {
            return response()->json([
                'success' => false,
                'message' => 'Santri tidak ditemukan',
                'data' => [],
            ]);
        }

        $notifikasi = CatatanKesehatan::with(['santri', 'kelas'])
            ->where('santri_id', $santri->id)
            ->whereNotNull('keluhan')
            ->get();

        return response()->json([
            'success' => true,
            'message' => 'Notifikasi kesehatan ditemukan',
            'data' => $notifikasi,
        ]);
    }
}
