<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Hasil;
use App\Models\User;
use App\Models\PilihPeriode;
use Barryvdh\DomPDF\Facade\Pdf as FacadePdf;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {
        $kmCounts = Hasil::select('km_class', DB::raw('count(*) as total'))
            ->groupBy('km_class')
            ->orderByRaw("FIELD(km_class, 'High', 'Medium', 'Low')")
            ->get();

        $rmCounts = Hasil::select('rm_class', DB::raw('count(*) as total'))
            ->groupBy('rm_class')
            ->orderByRaw("FIELD(rm_class, 'High', 'Medium', 'Low')")
            ->get();

        $checkPeriod = PilihPeriode::first();
        $idUser = auth()->user()->id;

        $historiPengisian = Hasil::where('id_user', $idUser)
            ->where('id_periode', $checkPeriod->id_periode)
            ->get();

        $results = Hasil::with('user')->with('periode')
            ->where('id_user', $idUser)
            ->get()
            ->map(function ($result) {
                $result->formatted_created_at = Carbon::parse($result->created_at)->format('d M Y');
                $result->periode->semester = $result->periode->semester == 1 ? 'Ganjil' : 'Genap';
                return $result;
            });

        // Ambil hasil terakhir dari user untuk gaya belajar
        $hasilGayaBelajar = Hasil::where('id_user', $idUser)
            ->where('id_periode', $checkPeriod->id_periode)
            ->latest()
            ->first();

        $learningStyleMap = [
            1 => 'Visual',
            2 => 'Auditory',
            3 => 'Read / Write',
            4 => 'Kinesthetic',
            5 => 'Multimodal'
        ];

        $learningStyle = $hasilGayaBelajar
            ? ($learningStyleMap[$hasilGayaBelajar->id_style] ?? 'Tidak diketahui')
            : 'Belum tersedia';

        // ===== LOGIKA UNTUK POPUP KUESIONER =====
        $data = DB::table('hasil')
            ->where('id_user', $idUser)
            ->where('id_periode', $checkPeriod->id_periode)
            ->latest()
            ->first();

        $styles = [
            'Visual' => $data->visual ?? 0,
            'Auditory' => $data->auditory ?? 0,
            'Read/Write' => $data->readwrite ?? 0,
            'Kinesthetic' => $data->kinesthetic ?? 0,
        ];

        $perluIsiKuesioner = empty(array_filter($styles)); // semua 0 → true

        return view('backend.dashboard', compact(
            'kmCounts',
            'rmCounts',
            'historiPengisian',
            'results',
            'learningStyle',
            'perluIsiKuesioner'
        ));
    }

    public function show($id)
    {
        $result = Hasil::with('user')->findOrFail($id);
        $result->formatted_updated_at = Carbon::parse($result->updated_at)->format('d M Y');
        return view('backend.user_pdf_result', compact('result'));
    }

    public function cetak_pdf($id)
    {
        // Kosong / belum diimplementasikan
    }
}
