<?php

namespace App\Http\Controllers;

use App\Models\DaftarProposal;
use App\Models\DaftarProposalMonev;
use App\Models\Jenis;
use App\Models\JenisMonev;
use App\Models\MonevInternal;
use App\Models\Pengumuman;
use App\Models\Periode;
use App\Models\Proposal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DashboardController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $title   = 'Dashboard PMW';
        $pengumuman = Pengumuman::query()->where('status', '1')->first();

        $tahun = Periode::orderBy('nama', 'ASC')->get();
        $jenis = Jenis::where('status_hapus', '0')->whereNotNull('nama')->orderBy('nama', 'ASC')->get();
        $proposal = DaftarProposal::all();
        $jenis_monev = JenisMonev::where('status_hapus', '0')->get();
        $monev = DaftarProposalMonev::where('status_hapus', '0')->get();
        $fakultas = DB::connection('siakadu')->table('sms')->whereNull('id_induk_sms')->whereNull('kode_prodi')->get();

        $data = [
            'title'   => $title,
            'pengumuman'  => $pengumuman,
            'tahun' => $tahun,
            'jenis' => $jenis,
            'proposal' => $proposal,
            'tahap' => $jenis_monev,
            'monev' => $monev,
            'fakultas' => $fakultas,
        ];

        return view('backend.index', $data);
    }

    public function getChartData(Request $request)
    {
        try {
            $jenis_id = $request->get('reqJenisPmw');
            $tahap = $request->get('reqStatus');
            $tahun = $request->get('tahun');

            // Debug: log received parameters
            Log::info('Chart data request parameters:', [
                'jenis_id' => $jenis_id,
                'tahap' => $tahap,
                'tahun' => $tahun
            ]);

            // 1️⃣ Ambil semua fakultas (sekali saja)
            $fakultas = DB::connection('siakadu')->table('sms')
                ->select('id_sms', 'nm_lemb')
                ->whereNull('id_induk_sms')
                ->whereNull('kode_prodi')
                ->where('nm_lemb', '!=', 'FPS')
                ->orderBy('nm_lemb', 'ASC')
                ->get()
                ->map(function ($item) {
                    if (strtolower($item->nm_lemb) === 'vokasi') {
                        $item->nm_lemb = 'VOKASI';
                    }
                    if (strtolower($item->nm_lemb) === 'kedokteran') {
                        $item->nm_lemb = 'FK';
                    }
                    if (strtolower($item->nm_lemb) === 'fpsi') {
                        $item->nm_lemb = 'FPsi';
                    }
                    if (strtolower($item->nm_lemb) === 'psdku') {
                        $item->nm_lemb = "PSDKU\nMagetan";
                    }
                    return $item;
                })
                ->sortBy(function ($item) {
                    $urutanKhusus = [
                        'VOKASI' => 1,
                        "PSDKU\nMagetan" => 2,
                        'FK' => 3,
                        'FKP' => 4,
                    ];

                    $rank = $urutanKhusus[$item->nm_lemb] ?? 0;

                    return sprintf('%02d_%s', $rank, $item->nm_lemb);
                })
                ->values();

            // 2️⃣ Query proposal per fakultas (1 query saja)
            $proposalQuery = DaftarProposal::select('fakultas_ketua', DB::raw('COUNT(*) as total'))
                ->where('status_hapus', '0')
                ->when($jenis_id, fn($q) => $q->where('jenis_id', $jenis_id))
                ->when($tahun, fn($q) => $q->where('periode', $tahun))
                ->when($tahap === 'proposal', fn($q) => $q) // Only show proposal data when tahap is 'proposal'
                ->when($tahap && $tahap !== 'proposal', fn($q) => $q->whereRaw('1 = 0')) // Hide proposal data for other tahap
                ->groupBy('fakultas_ketua')
                ->get()
                ->pluck('total', 'fakultas_ketua');

            // 3️⃣ Query Monev 1 (1 query)
            $monev1Query = DaftarProposalMonev::select('fakultas_ketua', DB::raw('COUNT(*) as total'))
                ->where('jenis_monev_desc', 'Monev Internal I')
                ->where('status_hapus', '0')
                ->when($jenis_id, fn($q) => $q->where('jenis_id', $jenis_id))
                ->when($tahun, fn($q) => $q->where('periode', $tahun))
                ->when($tahap === 'monev1', fn($q) => $q) // Only show monev1 data when tahap is 'monev1'
                ->when($tahap && $tahap !== 'monev1', fn($q) => $q->whereRaw('1 = 0')) // Hide monev1 data for other tahap
                ->groupBy('fakultas_ketua')
                ->get()
                ->pluck('total', 'fakultas_ketua');

            // 4️⃣ Query Monev 2 (1 query)
            $monev2Query = DaftarProposalMonev::select('fakultas_ketua', DB::raw('COUNT(*) as total'))
                ->where('jenis_monev_desc', 'Monev Internal II')
                ->where('status_hapus', '0')
                ->when($jenis_id, fn($q) => $q->where('jenis_id', $jenis_id))
                ->when($tahun, fn($q) => $q->where('periode', $tahun))
                ->when($tahap === 'monev2', fn($q) => $q) // Only show monev2 data when tahap is 'monev2'
                ->when($tahap && $tahap !== 'monev2', fn($q) => $q->whereRaw('1 = 0')) // Hide monev2 data for other tahap
                ->groupBy('fakultas_ketua')
                ->get()
                ->pluck('total', 'fakultas_ketua');

            // 5️⃣ Gabungkan data
            $chartData = $fakultas->map(function ($f) use ($proposalQuery, $monev1Query, $monev2Query) {
                $namaFak = $f->nm_lemb;
                return [
                    'fakultas' => $namaFak,
                    'proposal' => $proposalQuery[$namaFak] ?? 0,
                    'monev1'   => $monev1Query[$namaFak] ?? 0,
                    'monev2'   => $monev2Query[$namaFak] ?? 0,
                ];
            });

            return response()->json($chartData);

        } catch (\Throwable $e) {
            Log::error([
                'error' => true,
                'message' => $e->getMessage(),
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
            return response()->json(['error' => 'Terjadi kesalahan saat mengambil data chart.'], 500);
        }
    }
}
