<?php

namespace App\Http\Controllers;

use App\Models\Monitoring;
use App\Models\GmfmSkor;
use App\Models\GmfmDimensi;
use Illuminate\Support\Facades\Auth;
use Barryvdh\DomPDF\Facade\Pdf;

class PasienController extends Controller
{
    public function index()
    {
        $data = Monitoring::with(['creator', 'gmfm.skor.item.dimensi'])
            ->where('patient_id', Auth::id())
            ->latest()
            ->get();

        $total = $data->count();
        $rataSkor = $data->avg('skor');

        // Data chart: tanggal vs skor (%)
        $chartData = Monitoring::where('patient_id', Auth::id())
            ->orderBy('tanggal')
            ->get();

        $chartLabels = $chartData->pluck('tanggal')->toArray();
        $chartScores = $chartData->pluck('skor')->toArray();

        // Data chart per dimensi: rata-rata skor per dimensi dari penilaian terakhir
        $dimensiData = $this->getDimensiChartData(Auth::id());

        return view('pasien', compact(
            'data', 'total', 'rataSkor',
            'chartLabels', 'chartScores',
            'dimensiData'
        ));
    }

    /**
     * Download PDF laporan perkembangan
     */
    public function downloadPdf()
    {
        $user = Auth::user();

        $data = Monitoring::with(['creator', 'gmfm.skor.item.dimensi'])
            ->where('patient_id', $user->id)
            ->orderBy('tanggal', 'asc')
            ->get();

        $total = $data->count();
        $rataSkor = $data->avg('skor');

        $chartLabels = $data->pluck('tanggal')->toArray();
        $chartScores = $data->pluck('skor')->toArray();

        $dimensiData = $this->getDimensiChartData($user->id);

        // Generate chart image as base64 for PDF
        $chartImage = null;
        if (count($chartLabels) > 1) {
            $chartConfig = [
                'type' => 'line',
                'data' => [
                    'labels' => array_map(fn($d) => \Carbon\Carbon::parse($d)->format('d/m/Y'), $chartLabels),
                    'datasets' => [[
                        'label' => 'Skor GMFM (%)',
                        'data' => $chartScores,
                        'borderColor' => '#0F4C81',
                        'backgroundColor' => 'rgba(15,76,129,0.1)',
                        'fill' => true,
                        'tension' => 0.3,
                        'pointBackgroundColor' => '#0F4C81',
                        'pointRadius' => 5,
                        'pointBorderColor' => '#fff',
                        'pointBorderWidth' => 2,
                    ]],
                ],
                'options' => [
                    'scales' => [
                        'y' => ['min' => 0, 'max' => 100, 'title' => ['display' => true, 'text' => 'Skor (%)']],
                        'x' => ['title' => ['display' => true, 'text' => 'Tanggal Penilaian']],
                    ],
                    'plugins' => ['legend' => ['display' => false]],
                ],
            ];
            $chartUrl = 'https://quickchart.io/chart?w=700&h=300&bkg=white&c=' . urlencode(json_encode($chartConfig));

            try {
                $imageData = file_get_contents($chartUrl);
                if ($imageData) {
                    $chartImage = 'data:image/png;base64,' . base64_encode($imageData);
                }
            } catch (\Exception $e) {
                $chartImage = null;
            }
        }

        $pdf = Pdf::loadView('pasien-pdf', compact(
            'user', 'data', 'total', 'rataSkor',
            'chartLabels', 'chartScores', 'dimensiData', 'chartImage'
        ));

        $pdf->setPaper('a4', 'portrait');
        $pdf->setOption('margin-top', 15);
        $pdf->setOption('margin-bottom', 15);
        $pdf->setOption('margin-left', 20);
        $pdf->setOption('margin-right', 20);

        return $pdf->download("laporan_perkembangan_{$user->name}.pdf");
    }

    /**
     * Hitung rata-rata skor per dimensi dari semua penilaian pasien
     */
    private function getDimensiChartData($patientId)
    {
        $dimensiList = GmfmDimensi::all();

        // Ambil semua penilaian GMFM pasien ini
        $monitorings = Monitoring::where('patient_id', $patientId)
            ->whereNotNull('gmfm_id')
            ->with('gmfm.skor.item.dimensi')
            ->orderBy('tanggal')
            ->get();

        $result = [
            'dimensi_labels' => [],
            'dimensi_avg' => [],
            'per_penilaian' => [], // data per tanggal per dimensi
        ];

        foreach ($dimensiList as $d) {
            $result['dimensi_labels'][] = "Dimensi {$d->kode}";
        }

        // Per penilaian: hitung rata-rata skor per dimensi
        foreach ($monitorings as $mon) {
            if (!$mon->gmfm) continue;

            $entry = [
                'tanggal' => $mon->tanggal,
                'dimensi_scores' => [],
            ];

            foreach ($dimensiList as $d) {
                $skorDimensi = $mon->gmfm->skor->filter(function ($s) use ($d) {
                    return $s->item && $s->item->dimensi_id == $d->id;
                });

                $avg = $skorDimensi->count() > 0 ? $skorDimensi->avg('skor') : 0;
                $entry['dimensi_scores'][] = round($avg, 2);
            }

            $result['per_penilaian'][] = $entry;
        }

        // Rata-rata keseluruhan per dimensi
        foreach ($dimensiList as $i => $d) {
            $allScores = collect($result['per_penilaian'])->pluck("dimensi_scores.{$i}");
            $result['dimensi_avg'][] = $allScores->count() > 0 ? round($allScores->avg(), 2) : 0;
        }

        return $result;
    }
}
