<?php

declare(strict_types=1);

namespace Admin\Controllers;

/**
 * Admin Dashboard Controller
 *
 * Renders the admin dashboard with summary statistics.
 * Shows different dashboards for super_admin vs regular admin.
 */
class DashboardController extends AdminController
{
    /**
     * Display the admin dashboard.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function index(array $params = []): void
    {
        requireAdmin();

        // Redirect branch admin to their own dashboard
        if (isBranchAdmin()) {
            redirect(BASE_PATH . '/branch/dashboard');
        }

        // Student count
        $stmt = $this->db->query('SELECT COUNT(*) AS total FROM `students`');
        $studentCount = (int) ($stmt->fetch()['total'] ?? 0);

        // Active courses count
        $stmt = $this->db->query('SELECT COUNT(*) AS total FROM `courses` WHERE `active` = 1');
        $courseCount = (int) ($stmt->fetch()['total'] ?? 0);

        // Exams count
        $stmt = $this->db->query('SELECT COUNT(*) AS total FROM `exams`');
        $examCount = (int) ($stmt->fetch()['total'] ?? 0);

        // Branches count
        $stmt = $this->db->query('SELECT COUNT(*) AS total FROM `branches` WHERE `active` = 1');
        $branchCount = (int) ($stmt->fetch()['total'] ?? 0);

        // Pending testimonials
        $stmt = $this->db->query('SELECT COUNT(*) AS total FROM `testimonials` WHERE `is_approved` = 0');
        $pendingTestimonials = (int) ($stmt->fetch()['total'] ?? 0);

        // Unread contacts count
        $stmt = $this->db->query('SELECT COUNT(*) AS total FROM `contacts` WHERE `is_read` = 0');
        $unreadContacts = (int) ($stmt->fetch()['total'] ?? 0);

        // Recent contacts (last 5)
        $stmt = $this->db->query(
            'SELECT * FROM `contacts` ORDER BY `created_at` DESC LIMIT 5'
        );
        $recentContacts = $stmt->fetchAll() ?: [];

        // Recent exam results (last 5)
        $stmt = $this->db->query(
            'SELECT er.*, e.title AS exam_title, u.name AS student_name
             FROM `exam_results` er
             LEFT JOIN `exams` e ON er.exam_id = e.id
             LEFT JOIN `students` s ON er.student_id = s.id
             LEFT JOIN `users` u ON s.user_id = u.id
             ORDER BY er.created_at DESC LIMIT 5'
        );
        $recentResults = $stmt->fetchAll() ?: [];

        // Published exams count
        $stmt = $this->db->query('SELECT COUNT(*) AS total FROM `exams` WHERE `is_published` = 1');
        $publishedExams = (int) ($stmt->fetch()['total'] ?? 0);

        // Practice test statistics
        $practiceStats = [
            'total_attempts'   => 0,
            'unique_students'  => 0,
            'unique_guests'    => 0,
            'avg_percentage'   => 0,
            'recent_attempts'  => [],
            'pass_count'       => 0,
            'fail_count'       => 0,
            'attempts_today'   => 0,
        ];
        try {
            $attemptModel = new \App\Models\PracticeAttempt($this->db);
            $practiceStats = $attemptModel->getAdminStats();
        } catch (\Throwable $e) {
            error_log('Dashboard: Practice stats error: ' . $e->getMessage());
        }

        // Practice sets count
        $practiceSetsCount = 0;
        try {
            $stmt = $this->db->query('SELECT COUNT(*) AS total FROM `practice_sets`');
            $practiceSetsCount = (int) ($stmt->fetch()['total'] ?? 0);
        } catch (\Throwable $e) {
            // Table might not exist yet
        }

        // Unread demo class requests
        $unreadDemoClass = 0;
        try {
            $stmt = $this->db->query('SELECT COUNT(*) AS total FROM `demo_class_requests` WHERE `status` = "pending"');
            $unreadDemoClass = (int) ($stmt->fetch()['total'] ?? 0);
        } catch (\Throwable $e) {
            // Table might not exist yet
        }

        // If super admin, show ERP dashboard
        if (isSuperAdmin()) {
            $this->showSuperAdminDashboard($studentCount, $branchCount, $pendingTestimonials, $unreadContacts);
            return;
        }

        // Regular admin dashboard
        $this->adminView('dashboard', [
            'title'              => 'Dashboard',
            'currentPage'        => 'dashboard',
            'studentCount'       => $studentCount,
            'courseCount'        => $courseCount,
            'examCount'          => $examCount,
            'branchCount'        => $branchCount,
            'pendingTestimonials' => $pendingTestimonials,
            'unreadContacts'     => $unreadContacts,
            'recentContacts'     => $recentContacts,
            'recentResults'      => $recentResults,
            'publishedExams'     => $publishedExams,
            'practiceStats'      => $practiceStats,
            'practiceSetsCount'  => $practiceSetsCount,
            'unreadDemoClass'    => $unreadDemoClass,
        ]);
    }

    /**
     * Show super admin ERP dashboard with branch management data.
     */
    private function showSuperAdminDashboard(int $studentCount, int $branchCount, int $pendingTestimonials, int $unreadContacts): void
    {
        // Total branches (all, not just active)
        $stmt = $this->db->query('SELECT COUNT(*) AS total FROM `branches`');
        $totalBranches = (int) ($stmt->fetch()['total'] ?? 0);

        // Active branches
        $stmt = $this->db->query('SELECT COUNT(*) AS total FROM `branches` WHERE `active` = 1');
        $activeBranches = (int) ($stmt->fetch()['total'] ?? 0);

        // Total wallet balance across all branches
        $totalWalletBalance = 0;
        try {
            $stmt = $this->db->query('SELECT COALESCE(SUM(`wallet_balance`), 0) AS total FROM `branches`');
            $totalWalletBalance = (float) ($stmt->fetch()['total'] ?? 0);
        } catch (\Throwable $e) {}

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

        // 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) {}

        // Recent wallet transactions
        $recentTransactions = [];
        try {
            $stmt = $this->db->query(
                'SELECT wt.*, b.name AS branch_name FROM `branch_wallet_transactions` wt
                 LEFT JOIN `branches` b ON wt.branch_id = b.id
                 ORDER BY wt.created_at DESC LIMIT 5'
            );
            $recentTransactions = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}

        // Branch overview
        $branchOverview = [];
        try {
            $stmt = $this->db->query('SELECT `id`, `name`, `city`, `wallet_balance`, `active`, `is_verified` FROM `branches` ORDER BY `name` ASC');
            $branchOverview = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}

        $this->adminView('dashboard_superadmin', [
            'title'               => 'Super Admin Dashboard',
            'currentPage'         => 'dashboard',
            'totalBranches'       => $totalBranches,
            'activeBranches'      => $activeBranches,
            'totalStudents'       => $studentCount,
            'totalWalletBalance'  => $totalWalletBalance,
            'pendingApplications' => $pendingApplications,
            'pendingTestimonials' => $pendingTestimonials,
            'unreadContacts'      => $unreadContacts,
            'recentApplications'  => $recentApplications,
            'recentTransactions'  => $recentTransactions,
            'branchOverview'      => $branchOverview,
        ]);
    }
}
