<?php

declare(strict_types=1);

namespace SuperAdmin\Controllers;

/**
 * Super Admin Dashboard Controller
 *
 * Shows overview stats: total branches, total branch admins, total students,
 * total certificates, pending franchise applications, fee collection (all branches),
 * recent activity, recent applications, top-performing branches.
 */
class SuperAdminDashboardController extends SuperAdminBaseController
{
    public function index(): void
    {
        requireSuperAdmin();

        // ─── Stats ─────────────────────────────────────────────────────────
        $stats = [
            'total_branches'           => 0,
            'active_branches'          => 0,
            'pending_branches'         => 0,
            'total_branch_admins'      => 0,
            'total_students'           => 0,
            'total_certificates'       => 0,
            'total_marksheets'         => 0,
            'pending_applications'     => 0,
            'total_fee_collected'      => 0.00,
            'total_referral_earnings'  => 0.00,
            'total_exams'              => 0,
            'total_courses'            => 0,
        ];

        // Total & active branches
        try {
            $stmt = $this->db->query("SELECT COUNT(*) AS c FROM `branches`");
            $stats['total_branches'] = (int) ($stmt->fetch()['c'] ?? 0);

            $stmt = $this->db->query("SELECT COUNT(*) AS c FROM `branches` WHERE `status` = 'active'");
            $stats['active_branches'] = (int) ($stmt->fetch()['c'] ?? 0);

            $stmt = $this->db->query("SELECT COUNT(*) AS c FROM `branches` WHERE `status` = 'pending'");
            $stats['pending_branches'] = (int) ($stmt->fetch()['c'] ?? 0);
        } catch (\Throwable $e) { /* ignore */ }

        // Total branch admins
        try {
            $stmt = $this->db->query("SELECT COUNT(*) AS c FROM `users` WHERE `role` = 'branch_admin'");
            $stats['total_branch_admins'] = (int) ($stmt->fetch()['c'] ?? 0);
        } catch (\Throwable $e) { /* ignore */ }

        // Total students
        try {
            $stmt = $this->db->query("SELECT COUNT(*) AS c FROM `students`");
            $stats['total_students'] = (int) ($stmt->fetch()['c'] ?? 0);
        } catch (\Throwable $e) { /* ignore */ }

        // Total certificates + marksheets
        try {
            $stmt = $this->db->query("SELECT COUNT(*) AS c FROM `certificates` WHERE `status` IN ('generated','printed','delivered','issued')");
            $stats['total_certificates'] = (int) ($stmt->fetch()['c'] ?? 0);
        } catch (\Throwable $e) { /* ignore */ }

        // Pending franchise applications
        try {
            $stmt = $this->db->query("SELECT COUNT(*) AS c FROM `branch_applications` WHERE `status` = 'pending'");
            $stats['pending_applications'] = (int) ($stmt->fetch()['c'] ?? 0);
        } catch (\Throwable $e) { /* ignore */ }

        // Total fee collected (all branches — sum of fee_payments)
        try {
            $stmt = $this->db->query("SELECT COALESCE(SUM(`amount`), 0) AS t FROM `fee_payments`");
            $stats['total_fee_collected'] = (float) ($stmt->fetch()['t'] ?? 0);
        } catch (\Throwable $e) { /* ignore */ }

        // Total referral earnings
        try {
            $stmt = $this->db->query("SELECT COALESCE(SUM(`amount`), 0) AS t FROM `branch_referral_earnings` WHERE `status` = 'credited'");
            $stats['total_referral_earnings'] = (float) ($stmt->fetch()['t'] ?? 0);
        } catch (\Throwable $e) { /* ignore */ }

        // Total exams
        try {
            $stmt = $this->db->query("SELECT COUNT(*) AS c FROM `exams`");
            $stats['total_exams'] = (int) ($stmt->fetch()['c'] ?? 0);
        } catch (\Throwable $e) { /* ignore */ }

        // Total courses
        try {
            $stmt = $this->db->query("SELECT COUNT(*) AS c FROM `courses` WHERE `active` = 1");
            $stats['total_courses'] = (int) ($stmt->fetch()['c'] ?? 0);
        } catch (\Throwable $e) { /* ignore */ }

        // ─── Recent Branch Applications ────────────────────────────────────
        $recentApplications = [];
        try {
            $stmt = $this->db->query(
                "SELECT * FROM `branch_applications`
                 ORDER BY `created_at` DESC
                 LIMIT 5"
            );
            $recentApplications = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) { /* ignore */ }

        // ─── Top Performing Branches (by total_students desc) ──────────────
        $topBranches = [];
        try {
            $stmt = $this->db->query(
                "SELECT b.`id`, b.`name`, b.`branch_code`, b.`city`, b.`state`,
                        b.`total_students`, b.`total_certificates`, b.`total_revenue`,
                        b.`rank_position`,
                        u.`name` AS admin_name, u.`email` AS admin_email
                 FROM `branches` b
                 LEFT JOIN `users` u ON b.`admin_user_id` = u.`id`
                 WHERE b.`status` IN ('active','pending')
                 ORDER BY b.`total_students` DESC, b.`total_revenue` DESC
                 LIMIT 5"
            );
            $topBranches = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) { /* ignore */ }

        // ─── Recent Audit Log ──────────────────────────────────────────────
        $recentActivity = [];
        try {
            $stmt = $this->db->query(
                "SELECT a.*, u.`name` AS user_name
                 FROM `audit_log` a
                 LEFT JOIN `users` u ON a.`user_id` = u.`id`
                 ORDER BY a.`created_at` DESC
                 LIMIT 10"
            );
            $recentActivity = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) { /* ignore */ }

        // ─── Recent Global Announcements ───────────────────────────────────
        $recentAnnouncements = [];
        try {
            $stmt = $this->db->query(
                "SELECT * FROM `announcements`
                 WHERE `branch_id` IS NULL AND `is_active` = 1
                 ORDER BY `created_at` DESC
                 LIMIT 5"
            );
            $recentAnnouncements = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) { /* ignore */ }

        $this->superAdminView('dashboard', [
            'title'              => 'Super Admin Dashboard',
            'currentPage'        => 'dashboard',
            'stats'              => $stats,
            'recentApplications' => $recentApplications,
            'topBranches'        => $topBranches,
            'recentActivity'     => $recentActivity,
            'recentAnnouncements'=> $recentAnnouncements,
        ]);
    }
}
