<?php

namespace App\Http\Controllers;

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

class MonitoringController extends Controller
{
    public function index(Request $request)
    {
        $patients = User::where('role', 'pasien')
            ->orderBy('name')
            ->get();

        $query = Monitoring::with(['patient', 'creator', 'gmfm.skor']);

        // FILTER PASIEN
        if ($request->filled('patient_id')) {
            $query->where('patient_id', $request->patient_id);
        }

        // SORTING
        $sort = $request->get('sort', 'tanggal');
        $direction = $request->get('direction', 'desc');

        if ($sort === 'patient') {
            $query->join('users as patients', 'monitorings.patient_id', '=', 'patients.id')
                ->orderBy('patients.name', $direction)
                ->select('monitorings.*');
        } elseif (in_array($sort, ['tanggal', 'skor'])) {
            $query->orderBy($sort, $direction);
        }

        $data = $query->get();

        // CHART
        $selectedPatient = $request->get('patient_chart_id');
        $chartData = $selectedPatient
            ? Monitoring::where('patient_id', $selectedPatient)->orderBy('tanggal')->get()
            : collect();

        $labels = $chartData->pluck('tanggal');
        $scores = $chartData->pluck('skor');

        $dimensi = GmfmDimensi::with('items')->get();

        // Prepare scores map per monitoring for edit modal: { monitoringId: { itemId: skor } }
        $skorMap = [];
        foreach ($data as $mon) {
            if ($mon->gmfm && $mon->gmfm->skor) {
                $skorMap[$mon->id] = $mon->gmfm->skor->pluck('skor', 'item_id')->toArray();
            }
        }

        return view('dashboard', compact(
            'data',
            'patients',
            'labels',
            'scores',
            'selectedPatient',
            'dimensi',
            'skorMap'
        ));
    }

    /**
     * UPDATE MONITORING (tanggal, catatan, + skor GMFM)
     * Akses: admin & terapis
     */
    public function update(Request $request, Monitoring $monitoring)
    {
        $user = Auth::user();
        if (!in_array($user->role, ['admin', 'terapis'])) {
            abort(403);
        }

        $request->validate([
            'tanggal' => 'required|date',
            'catatan' => 'nullable|string',
            'skor_item'   => 'nullable|array',
            'skor_item.*' => 'integer|min:1|max:7',
        ]);

        $monitoring->update($request->only('tanggal', 'catatan'));

        // Sinkronkan tanggal & catatan ke penilaian GMFM terkait
        if ($monitoring->gmfm) {
            $monitoring->gmfm->update([
                'tanggal_penilaian' => $request->tanggal,
                'catatan'           => $request->catatan,
            ]);

            // Update skor GMFM per item jika dikirim
            if ($request->filled('skor_item')) {
                $total = 0;
                $jumlahItem = count($request->skor_item);

                foreach ($request->skor_item as $itemId => $nilai) {
                    GmfmSkor::where('penilaian_id', $monitoring->gmfm_id)
                        ->where('item_id', $itemId)
                        ->update(['skor' => $nilai]);
                    $total += $nilai;
                }

                // Recalculate percentage
                $minSkor = $jumlahItem * 1;
                $maxSkor = $jumlahItem * 7;
                $persen = $maxSkor > $minSkor
                    ? (($total - $minSkor) / ($maxSkor - $minSkor)) * 100
                    : 0;

                $monitoring->update(['skor' => round($persen, 2)]);
            }
        }

        return back()->with('success', 'Data monitoring berhasil diupdate');
    }

    /**
     * HAPUS MONITORING
     * Akses: admin saja
     */
    public function destroy(Monitoring $monitoring)
    {
        if (Auth::user()->role !== 'admin') {
            abort(403);
        }

        // Hapus juga penilaian GMFM terkait
        if ($monitoring->gmfm) {
            $monitoring->gmfm->delete();
        }

        $monitoring->delete();

        return back()->with('success', 'Data monitoring berhasil dihapus');
    }
}
