<?php

namespace App\Http\Controllers;

use App\Services\SupabaseService;
use Illuminate\Http\Request;

/**
 * Monitoring kelengkapan pengisian data instansi (dari Supabase instansi_data).
 * Kriteria "lengkap" = SEMUA kolom instansi untuk bulan itu terisi.
 */
class MonitoringController extends Controller
{
    public const BULAN_SINGKAT = [
        1 => 'Jan', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr', 5 => 'Mei', 6 => 'Jun',
        7 => 'Jul', 8 => 'Agu', 9 => 'Sep', 10 => 'Okt', 11 => 'Nov', 12 => 'Des',
    ];

    public function __construct(private SupabaseService $supabase)
    {
    }

    public function index(Request $request)
    {
        $tahun = (int) ($request->query('tahun') ?: date('Y'));

        $fieldsGrouped = $this->supabase->getAllFieldsGrouped();   // [ref_id => [field_key]]
        $filled = $this->supabase->getFilledCounts($tahun);        // [ref_id][bulan] => n terisi
        $refs = $this->supabase->getAllInstansiRef(activeOnly: true);

        $rows = [];
        $trendLengkap = array_fill(1, 12, 0); // jumlah instansi lengkap per bulan
        $totalLengkapSel = 0;

        foreach ($refs as $ref) {
            $id = $ref['id'];
            if (empty($fieldsGrouped[$id])) {
                continue; // belum onboard → tidak dipantau
            }
            $totalKolom = count($fieldsGrouped[$id]);

            $bulanStatus = [];
            $lengkapCount = 0;
            for ($b = 1; $b <= 12; $b++) {
                $terisi = $filled[$id][$b] ?? 0;
                if ($terisi >= $totalKolom) {
                    $status = 'lengkap';
                    $trendLengkap[$b]++;
                    $lengkapCount++;
                    $totalLengkapSel++;
                } elseif ($terisi > 0) {
                    $status = 'sebagian';
                } else {
                    $status = 'kosong';
                }
                $bulanStatus[$b] = ['status' => $status, 'terisi' => $terisi, 'total' => $totalKolom];
            }

            $rows[] = [
                'nama' => $ref['nama_instansi'],
                'slug' => $ref['slug'],
                'total_kolom' => $totalKolom,
                'bulan' => $bulanStatus,
                'lengkap_count' => $lengkapCount,
            ];
        }

        // Urut: paling sedikit lengkap di atas (yang perlu ditagih)
        usort($rows, fn ($a, $b) => $a['lengkap_count'] <=> $b['lengkap_count']);

        $jumlahInstansi = count($rows);
        $bulanIni = ((int) date('Y') === $tahun) ? (int) date('n') : 12;
        $lengkapBulanIni = 0;
        foreach ($rows as $r) {
            if ($r['bulan'][$bulanIni]['status'] === 'lengkap') {
                $lengkapBulanIni++;
            }
        }
        $persenTahun = $jumlahInstansi > 0
            ? round($totalLengkapSel / ($jumlahInstansi * 12) * 100)
            : 0;

        // Tren: % instansi lengkap per bulan
        $trend = [];
        for ($b = 1; $b <= 12; $b++) {
            $trend[$b] = $jumlahInstansi > 0 ? round($trendLengkap[$b] / $jumlahInstansi * 100) : 0;
        }

        return view('monitoring', [
            'tahun' => $tahun,
            'rows' => $rows,
            'bulanSingkat' => self::BULAN_SINGKAT,
            'jumlahInstansi' => $jumlahInstansi,
            'bulanIni' => $bulanIni,
            'lengkapBulanIni' => $lengkapBulanIni,
            'persenTahun' => $persenTahun,
            'trend' => $trend,
        ]);
    }
}
