<?php

declare(strict_types=1);

namespace BranchAdmin\Controllers;

/**
 * Branch Admin Dashboard Controller
 *
 * Shows branch-specific stats:
 *   - Total students, active students
 *   - Total certificates generated, marksheets generated
 *   - Pending approvals (results, applications)
 *   - Examinations conducted
 *   - Fee collections (this month + total)
 *   - Referral earnings
 *   - Wallet balance
 *   - Recent announcements (global + branch-specific)
 *   - Branch ranking
 */
class BranchDashboardController extends BranchBaseController
{
    public function index(): void
    {
        requireBranchAdmin();

        $branchId   = $this->getBranchId();
        $branchCode = $this->getBranchCode();

        // ─── Branch Info ───────────────────────────────────────────────────
        $branch = [];
        try {
            $stmt = $this->db->prepare("SELECT * FROM `branches` WHERE `id` = :bid LIMIT 1");
            $stmt->execute([':bid' => $branchId]);
            $branch = $stmt->fetch() ?: [];
        } catch (\Throwable $e) {}

        // ─── Stats ─────────────────────────────────────────────────────────
        $stats = [
            'total_students'         => 0,
            'active_students'        => 0,
            'certificates_generated' => 0,
            'marksheets_generated'   => 0,
            'pending_approvals'      => 0,
            'exams_conducted'        => 0,
            'fee_collected_month'    => 0.00,
            'fee_collected_total'    => 0.00,
            'referral_earnings'      => 0.00,
            'wallet_balance'         => (float) ($branch['wallet_balance'] ?? 0),
            'rank_position'          => (int) ($branch['rank_position'] ?? 0),
            'total_revenue'          => (float) ($branch['total_revenue'] ?? 0),
        ];

        // Total & active students
        try {
            $stmt = $this->db->prepare("SELECT COUNT(*) AS c FROM `students` WHERE `branch_id` = :bid");
            $stmt->execute([':bid' => $branchId]);
            $stats['total_students'] = (int) ($stmt->fetch()['c'] ?? 0);

            $stmt = $this->db->prepare("SELECT COUNT(*) AS c FROM `students` WHERE `branch_id` = :bid AND `status` = 'active'");
            $stmt->execute([':bid' => $branchId]);
            $stats['active_students'] = (int) ($stmt->fetch()['c'] ?? 0);
        } catch (\Throwable $e) {}

        // Certificates generated
        try {
            $stmt = $this->db->prepare("SELECT COUNT(*) AS c FROM `certificates` WHERE `branch_id` = :bid AND `status` IN ('generated','printed','delivered','issued')");
            $stmt->execute([':bid' => $branchId]);
            $stats['certificates_generated'] = (int) ($stmt->fetch()['c'] ?? 0);
        } catch (\Throwable $e) {}

        // Pending result approvals (results with status='pending_approval')
        try {
            $stmt = $this->db->prepare("SELECT COUNT(*) AS c FROM `branch_results` WHERE `branch_id` = :bid AND `status` = 'pending_approval'");
            $stmt->execute([':bid' => $branchId]);
            $stats['pending_approvals'] = (int) ($stmt->fetch()['c'] ?? 0);
        } catch (\Throwable $e) {}

        // Exams conducted
        try {
            $stmt = $this->db->prepare("SELECT COUNT(*) AS c FROM `exams` WHERE `branch_id` = :bid");
            $stmt->execute([':bid' => $branchId]);
            $stats['exams_conducted'] = (int) ($stmt->fetch()['c'] ?? 0);
        } catch (\Throwable $e) {}

        // Fee collected this month
        try {
            $stmt = $this->db->prepare(
                "SELECT COALESCE(SUM(`amount`), 0) AS t FROM `fee_payments`
                 WHERE `branch_id` = :bid AND MONTH(`payment_date`) = MONTH(CURRENT_DATE())
                 AND YEAR(`payment_date`) = YEAR(CURRENT_DATE())"
            );
            $stmt->execute([':bid' => $branchId]);
            $stats['fee_collected_month'] = (float) ($stmt->fetch()['t'] ?? 0);
        } catch (\Throwable $e) {}

        // Fee collected total
        try {
            $stmt = $this->db->prepare("SELECT COALESCE(SUM(`amount`), 0) AS t FROM `fee_payments` WHERE `branch_id` = :bid");
            $stmt->execute([':bid' => $branchId]);
            $stats['fee_collected_total'] = (float) ($stmt->fetch()['t'] ?? 0);
        } catch (\Throwable $e) {}

        // Referral earnings
        try {
            $stmt = $this->db->prepare("SELECT COALESCE(SUM(`amount`), 0) AS t FROM `branch_referral_earnings` WHERE `branch_id` = :bid AND `status` = 'credited'");
            $stmt->execute([':bid' => $branchId]);
            $stats['referral_earnings'] = (float) ($stmt->fetch()['t'] ?? 0);
        } catch (\Throwable $e) {}

        // ─── Recent Announcements (global + branch-specific) ───────────────
        $recentAnnouncements = [];
        try {
            $stmt = $this->db->prepare(
                "SELECT * FROM `announcements`
                 WHERE `is_active` = 1 AND (`branch_id` IS NULL OR `branch_id` = :bid)
                 ORDER BY `created_at` DESC
                 LIMIT 5"
            );
            $stmt->execute([':bid' => $branchId]);
            $recentAnnouncements = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}

        // ─── Recent Students ───────────────────────────────────────────────
        $recentStudents = [];
        try {
            $stmt = $this->db->prepare(
                "SELECT s.*, u.`name`, u.`email`, u.`phone`, c.`name` AS course_name
                 FROM `students` s
                 LEFT JOIN `users` u ON s.`user_id` = u.`id`
                 LEFT JOIN `courses` c ON s.`course_id` = c.`id`
                 WHERE s.`branch_id` = :bid
                 ORDER BY s.`created_at` DESC
                 LIMIT 5"
            );
            $stmt->execute([':bid' => $branchId]);
            $recentStudents = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}

        // ─── Recent Fee Payments ───────────────────────────────────────────
        $recentFees = [];
        try {
            $stmt = $this->db->prepare(
                "SELECT fp.*, s.`user_id`, u.`name` AS student_name, u.`email` AS student_email
                 FROM `fee_payments` fp
                 LEFT JOIN `students` s ON fp.`student_id` = s.`id`
                 LEFT JOIN `users` u ON s.`user_id` = u.`id`
                 WHERE fp.`branch_id` = :bid
                 ORDER BY fp.`created_at` DESC
                 LIMIT 5"
            );
            $stmt->execute([':bid' => $branchId]);
            $recentFees = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}

        // ─── Branch Ranking (top 5 + my rank) ──────────────────────────────
        $topBranches = [];
        $myRank = null;
        try {
            $stmt = $this->db->query(
                "SELECT `id`, `name`, `branch_code`, `total_students`, `total_certificates`, `total_revenue`, `rank_position`
                 FROM `branches`
                 WHERE `status` = 'active'
                 ORDER BY `rank_position` ASC, `total_students` DESC, `total_revenue` DESC
                 LIMIT 5"
            );
            $topBranches = $stmt->fetchAll() ?: [];

            // My rank
            $rankPos = (int) ($branch['rank_position'] ?? 0);
            if ($rankPos > 0) {
                $myRank = $rankPos;
            } else {
                // Calculate rank on the fly
                $stmt = $this->db->prepare(
                    "SELECT COUNT(*) + 1 AS r FROM `branches`
                     WHERE `status` = 'active'
                     AND (`total_students` > :ts OR
                          (`total_students` = :ts2 AND `total_revenue` > :tr))"
                );
                $stmt->execute([
                    ':ts'  => (int) ($branch['total_students'] ?? 0),
                    ':ts2' => (int) ($branch['total_students'] ?? 0),
                    ':tr'  => (float) ($branch['total_revenue'] ?? 0),
                ]);
                $myRank = (int) ($stmt->fetch()['r'] ?? 0);
            }
        } catch (\Throwable $e) {}

        $this->branchAdminView('dashboard', [
            'title'               => 'Branch Dashboard',
            'currentPage'         => 'dashboard',
            'branch'              => $branch,
            'stats'               => $stats,
            'recentAnnouncements' => $recentAnnouncements,
            'recentStudents'      => $recentStudents,
            'recentFees'          => $recentFees,
            'topBranches'         => $topBranches,
            'myRank'              => $myRank,
        ]);
    }
}
