<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PenilaianGmfm;
use App\Models\GmfmSkor;
use App\Models\Monitoring;
use Illuminate\Support\Facades\Auth;

class GmfmController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'patient_id' => 'required|exists:users,id',
            'tanggal'    => 'required|date',
            'skor'       => 'required|array',
            'skor.*'     => 'required|integer|min:1|max:7',
            'catatan'    => 'nullable|string',
        ]);

        // 1️⃣ Simpan header penilaian GMFM
        $penilaian = PenilaianGmfm::create([
            'pasien_id'         => $request->patient_id,
            'dinilai_oleh'      => Auth::id(),
            'tanggal_penilaian' => $request->tanggal,
            'catatan'           => $request->catatan,
        ]);

        // 2️⃣ Simpan skor per item + hitung total
        $total = 0;
        $jumlahItem = count($request->skor);

        foreach ($request->skor as $itemId => $nilai) {
            GmfmSkor::create([
                'penilaian_id' => $penilaian->id,
                'item_id'      => $itemId,
                'skor'         => $nilai,
            ]);
            $total += $nilai;
        }

        // 3️⃣ Hitung skor GMFM (%)
        // Skor 1-7: minimum = jumlahItem × 1, maximum = jumlahItem × 7
        // Persentase = (total - min) / (max - min) × 100
        $minSkor = $jumlahItem * 1;
        $maxSkor = $jumlahItem * 7;
        $persen  = $maxSkor > $minSkor ? (($total - $minSkor) / ($maxSkor - $minSkor)) * 100 : 0;

        // 4️⃣ Simpan ke MONITORING
        Monitoring::create([
            'patient_id'    => $request->patient_id,
            'created_by'    => Auth::id(),
            'tanggal'       => $request->tanggal,
            'catatan'       => $request->catatan,
            'skor'          => round($persen, 2),
            'gmfm_id'       => $penilaian->id,
        ]);

        return redirect()->route('dashboard')
            ->with('success', 'Monitoring GMFM berhasil disimpan');
    }
}
