<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class Dashboard extends BaseController
{
    public function index()
    {
        $session = session();
        if (!$session->get('isLoggedIn')) {
            return redirect()->to('/login');
        }

        $role = $session->get('role');
        $db = \Config\Database::connect();
        
        // Data dasar
        $data = [
            'title' => 'Dashboard',
            'role' => $role,
            'username' => $session->get('username'),
        ];

        if ($role === 'superadmin') {
            // Hitung Total OPD
            $data['total_opd'] = $db->table('opd')->countAllResults();
            
            // Hitung Total Bidang
            $data['total_bidang'] = $db->table('bidang')->countAllResults();
            
            // Hitung Laporan Masuk (Total record di tabel realisasi)
            $data['laporan_masuk'] = $db->table('realisasi')->countAllResults();
            
            // Hitung Status Laporan
            $data['status_selesai'] = $db->table('realisasi')->where('status', 'Disetujui')->countAllResults();
            $data['status_revisi'] = $db->table('realisasi')->where('status', 'Revisi')->countAllResults();
            $data['status_proses'] = $db->table('realisasi')->where('status', 'Diajukan')->countAllResults();
            // Draft tidak dihitung sebagai proses? Tergantung kebutuhan, anggap saja Diajukan = Proses
            
            // Persentase Progress (Contoh sederhana: Selesai / (Selesai + Proses + Revisi) * 100)
            $total_laporan = $data['laporan_masuk'];
            $data['progress_persen'] = $total_laporan > 0 ? round(($data['status_selesai'] / $total_laporan) * 100) : 0;

            // Aktivitas Terbaru (Ambil 5 laporan terakhir)
            $data['aktivitas_terbaru'] = $db->table('realisasi')
                ->select('realisasi.*, opd.nama_opd, bidang.nama_bidang, sub_kegiatan.nama_sub_kegiatan')
                ->join('sub_kegiatan', 'sub_kegiatan.id = realisasi.sub_kegiatan_id')
                ->join('kegiatan', 'kegiatan.id = sub_kegiatan.kegiatan_id')
                ->join('programs', 'programs.id = kegiatan.program_id')
                ->join('opd', 'opd.id = programs.opd_id')
                ->join('bidang', 'bidang.id = opd.bidang_id')
                ->orderBy('realisasi.updated_at', 'DESC')
                ->limit(5)
                ->get()->getResultArray();
            $data['loadCharts'] = true;

            return view('superadmin/dashboard', $data);
        } elseif ($role === 'admin_bidang') {
            return redirect()->to('/admin_bidang/dashboard');
        } else {
            return redirect()->to('/opd_kinerja/dashboard');
        }
    }
}
