<?php 
// Debugging (Production-e eta muche diben)
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../db_connect.php'; 
include 'includes/header.php'; 
include 'includes/sidebar.php'; 

// ========================================================
// ⚙️ DYNAMIC DATA FETCHING (Existing + New Features)
// ========================================================

// --- 🌟 NEW: BLUEPRINT ESSENTIALS (Total Students, Monthly Income, Pending Tasks) ---
$total_students = 0;
try { $total_students = $pdo->query("SELECT COUNT(*) FROM students")->fetchColumn() ?: 0; } catch (Exception $e) {}

$monthly_income = 0;
try { 
    // Assuming you have a date column for payment verification
    $monthly_income = $pdo->query("
        SELECT SUM(c.fee) FROM admissions a 
        JOIN courses c ON a.course_id = c.id 
        WHERE a.payment_status = 'verified' 
        AND MONTH(a.applied_date) = MONTH(CURRENT_DATE()) 
        AND YEAR(a.applied_date) = YEAR(CURRENT_DATE())
    ")->fetchColumn() ?: 0; 
} catch (Exception $e) {}

$pending_requests = 0; // This acts as our primary "Pending Tasks"
try { $pending_requests = $pdo->query("SELECT COUNT(*) FROM admissions WHERE status = 'pending'")->fetchColumn() ?: 0; } catch (Exception $e) {}
$pending_tasks = $pending_requests; // Assigning to blueprint variable

// ---------------------------------------------------------------
// EXISTING QUERIES (Kept exactly as you had them)
// ---------------------------------------------------------------
$total_enrollments = 0; 
try { $total_enrollments = $pdo->query("SELECT COUNT(*) FROM admissions WHERE status = 'approved'")->fetchColumn() ?: 0; } catch (Exception $e) {}

$approved_amount = 0; $pending_amount = 0;
try {
    $fin_query = $pdo->query("
        SELECT 
            SUM(CASE WHEN a.payment_status = 'verified' THEN c.fee ELSE 0 END) as app_amt,
            SUM(CASE WHEN a.payment_status = 'pending' THEN c.fee ELSE 0 END) as pen_amt
        FROM admissions a 
        JOIN courses c ON a.course_id = c.id
    ")->fetch(PDO::FETCH_ASSOC);
    $approved_amount = $fin_query['app_amt'] ?? 0;
    $pending_amount = $fin_query['pen_amt'] ?? 0;
} catch (Exception $e) {}

$total_courses = 0; try { $total_courses = $pdo->query("SELECT COUNT(*) FROM courses")->fetchColumn() ?: 0; } catch(Exception $e) {}
$total_results = 0; try { $total_results = $pdo->query("SELECT COUNT(*) FROM results WHERE status = 'publish'")->fetchColumn() ?: 0; } catch(Exception $e) {}
$total_notices = 0; try { $total_notices = $pdo->query("SELECT COUNT(*) FROM notices")->fetchColumn() ?: 0; } catch(Exception $e) {}

$recent_students = 0; 
try { $recent_students = $pdo->query("SELECT COUNT(DISTINCT student_id) FROM exam_result WHERE submitted_at >= NOW() - INTERVAL 1 DAY")->fetchColumn() ?: 0; } catch(Exception $e) {}

$today_exams = 0;
try { $today_exams = $pdo->query("SELECT COUNT(*) FROM exams WHERE DATE(created_at) = CURDATE()")->fetchColumn() ?: 0; } catch(Exception $e) {}

$total_teachers = 0; 
try { $total_teachers = $pdo->query("SELECT COUNT(*) FROM teachers WHERE status = 'active'")->fetchColumn() ?: 0; } catch (Exception $e) {}

$today_live_classes = 0; 
try { $today_live_classes = $pdo->query("SELECT COUNT(*) FROM live_classes WHERE class_date = CURDATE()")->fetchColumn() ?: 0; } catch (Exception $e) {}

$trial_students = 0; $limit_reached = 0;
try { 
    $trial_students = $pdo->query("SELECT COUNT(*) FROM students WHERE is_trial = 1")->fetchColumn() ?: 0; 
    $limit_reached = $pdo->query("SELECT COUNT(*) FROM students WHERE is_trial = 1 AND trial_attended >= 3")->fetchColumn() ?: 0; 
} catch (Exception $e) {}

$course_chart_data = [];
try {
    $course_chart_data = $pdo->query("
        SELECT c.title, COUNT(a.id) as total_enrolls 
        FROM courses c 
        LEFT JOIN admissions a ON c.id = a.course_id AND a.status = 'approved'
        GROUP BY c.id 
        ORDER BY total_enrolls DESC 
        LIMIT 5
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

$recent_pending = [];
try {
    $recent_pending = $pdo->query("
        SELECT a.*, c.title as course_name 
        FROM admissions a 
        JOIN courses c ON a.course_id = c.id 
        WHERE a.status = 'pending' 
        ORDER BY a.applied_date DESC 
        LIMIT 5
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

$chart_labels = []; $chart_data = [];
foreach ($course_chart_data as $data) {
    $chart_labels[] = $data['title'];
    $chart_data[] = $data['total_enrolls'];
}

$current_date = date('d M Y, l');
?>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<style>
    :root {
        --primary: #064e3b;
        --primary-dark: #022c22;
        --accent: #d4af37;
        --bg-color: #f8fafc;
    }

    .main-content { background-color: var(--bg-color); min-height: 100vh; padding-bottom: 50px; }
    
    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } }

    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 16px; border-left: 5px solid var(--accent); box-shadow: 0 4px 20px rgba(0,0,0,0.03); margin-bottom: 30px; }
    .welcome-text { color: var(--primary-dark); font-weight: 800; font-size: 24px; }
    .date-badge { background: rgba(212, 175, 55, 0.15); color: var(--primary-dark); padding: 8px 18px; border-radius: 50px; font-size: 14px; font-weight: 700; border: 1px solid rgba(212, 175, 55, 0.3); }

    .stat-card { background: #fff; border-radius: 16px; border: 1px solid #f1f5f9; padding: 25px; box-shadow: 0 8px 25px rgba(0,0,0,0.04); position: relative; overflow: hidden; transition: 0.3s; display: flex; justify-content: space-between; align-items: center; height: 100%; }
    .stat-card:hover { transform: translateY(-5px); box-shadow: 0 15px 35px rgba(0,0,0,0.08); border-color: var(--accent); }
    
    .icon-box { width: 60px; height: 60px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 26px; }
    
    .stat-info h3 { font-size: 30px; font-weight: 800; margin: 0 0 5px; color: var(--primary-dark); }
    .stat-info p { margin: 0; font-size: 12px; color: #64748b; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }

    .content-box { background: #fff; border-radius: 16px; padding: 25px; box-shadow: 0 8px 25px rgba(0,0,0,0.04); border: 1px solid #f1f5f9; height: 100%; }
    .box-title { font-size: 16px; font-weight: 800; color: var(--primary-dark); margin-bottom: 20px; display: flex; align-items: center; }
    .box-title i { color: var(--accent); margin-right: 10px; font-size: 18px; }

    .table thead th { background-color: #f8fafc; color: #64748b; font-size: 11px; text-transform: uppercase; border-bottom: none; font-weight: 700; padding: 15px; }
    .table tbody tr { transition: 0.2s; }
    .table tbody tr:hover { background-color: rgba(212, 175, 55, 0.05); }
    .table td { padding: 15px; vertical-align: middle; font-size: 14px; }
    
    .badge-custom { padding: 6px 14px; border-radius: 50px; font-size: 11px; font-weight: 800; text-transform: uppercase; }

    .qa-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; text-align: center; transition: 0.3s; display: block; color: var(--primary-dark); text-decoration: none; }
    .qa-card:hover { background: var(--primary); color: #fff; border-color: var(--primary); transform: translateY(-3px); }
    .qa-icon { font-size: 24px; margin-bottom: 10px; color: var(--accent); }
    .qa-title { font-weight: 700; font-size: 15px; margin: 0; }

    .btn-action { width: 32px; height: 32px; display: inline-flex; align-items: center; justify-content: center; border-radius: 8px; transition: 0.3s; margin: 0 2px; text-decoration: none; }
    .btn-action:hover { transform: translateY(-2px); box-shadow: 0 4px 10px rgba(0,0,0,0.1); color: #fff !important; }
    .btn-approve { background: rgba(16,185,129,0.1); color: #10b981; border: 1px solid rgba(16,185,129,0.2); }
    .btn-approve:hover { background: #10b981; }
    
    /* Highlighted Box for Blueprint Essentials */
    .executive-card { border-left: 5px solid var(--primary); background: linear-gradient(145deg, #ffffff, #f8fafc); }
</style>

<div class="main-content p-3 p-md-4">

    <div class="dashboard-header d-flex flex-column flex-md-row justify-content-between align-items-md-center fade-up">
        <div class="d-flex align-items-center mb-3 mb-md-0">
            <button class="btn btn-light d-md-none me-3 border shadow-sm" id="sidebarToggle">
                <i class="fas fa-bars" style="color: var(--primary);"></i>
            </button>
            <div>
                <h4 class="mb-1 welcome-text">Welcome, Admin! 👋</h4>
                <p class="mb-0 text-muted small fw-medium">Overview of Academy Performance & Analytics.</p>
            </div>
        </div>
        <div class="d-none d-md-block">
            <span class="date-badge"><i class="far fa-calendar-alt me-2"></i> <?= $current_date; ?></span>
        </div>
    </div>

    <h6 class="fw-bold mb-3 text-muted text-uppercase fade-up" style="letter-spacing: 1px;"><i class="fas fa-bolt me-2"></i> Executive Summary</h6>
    <div class="row g-4 mb-5 fade-up" style="animation-delay: 0.05s;">
        <div class="col-xl-3 col-md-6">
            <div class="stat-card executive-card">
                <div class="stat-info">
                    <h3 style="color: var(--primary);"><?= number_format($total_students); ?></h3>
                    <p>Total Students</p>
                </div>
                <div class="icon-box" style="background: rgba(6, 78, 59, 0.1); color: var(--primary);"><i class="fas fa-users"></i></div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-card executive-card" style="border-left-color: #10b981;">
                <div class="stat-info">
                    <h3 style="color: #10b981;">$<?= number_format((float)$monthly_income, 2); ?></h3>
                    <p>Monthly Income</p>
                </div>
                <div class="icon-box" style="background: rgba(16, 185, 129, 0.1); color: #10b981;"><i class="fas fa-chart-line"></i></div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-card executive-card" style="border-left-color: #f59e0b;">
                <div class="stat-info">
                    <h3 style="color: #f59e0b;"><?= number_format($pending_tasks); ?></h3>
                    <p>Pending Tasks</p>
                </div>
                <div class="icon-box" style="background: rgba(245, 158, 11, 0.1); color: #f59e0b;"><i class="fas fa-clipboard-list"></i></div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-card executive-card" style="border-left-color: var(--accent);">
                <div class="stat-info">
                    <h3 style="color: var(--accent);"><?= sprintf("%02d", $today_live_classes); ?></h3>
                    <p>Today's Classes</p>
                </div>
                <div class="icon-box" style="background: rgba(212, 175, 55, 0.15); color: var(--accent);"><i class="fas fa-video"></i></div>
            </div>
        </div>
    </div>

    <h6 class="fw-bold mb-3 text-muted text-uppercase fade-up" style="letter-spacing: 1px;"><i class="fas fa-wallet me-2"></i> Financials & Enrollments</h6>
    <div class="row g-4 mb-4 fade-up" style="animation-delay: 0.1s;">
        <div class="col-xl-3 col-md-6">
            <div class="stat-card">
                <div class="stat-info">
                    <h3><?= number_format($total_enrollments); ?></h3>
                    <p>Total Enrollments</p>
                </div>
                <div class="icon-box" style="background: rgba(6, 78, 59, 0.1); color: var(--primary);"><i class="fas fa-user-graduate"></i></div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-card" style="border-left: 4px solid #ef4444;">
                <div class="stat-info">
                    <h3 style="color: #ef4444;"><?= number_format($pending_requests); ?></h3>
                    <p>Pending Requests</p>
                </div>
                <div class="icon-box" style="background: rgba(239, 68, 68, 0.1); color: #ef4444;"><i class="fas fa-user-clock"></i></div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-card">
                <div class="stat-info">
                    <h3 style="color: #10b981;">$<?= number_format((float)$approved_amount, 2); ?></h3>
                    <p>Approved Revenue</p>
                </div>
                <div class="icon-box" style="background: rgba(16, 185, 129, 0.1); color: #10b981;"><i class="fas fa-hand-holding-usd"></i></div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-card">
                <div class="stat-info">
                    <h3 style="color: #f59e0b;">$<?= number_format((float)$pending_amount, 2); ?></h3>
                    <p>Pending Revenue</p>
                </div>
                <div class="icon-box" style="background: rgba(245, 158, 11, 0.1); color: #f59e0b;"><i class="fas fa-file-invoice-dollar"></i></div>
            </div>
        </div>
    </div>

    <h6 class="fw-bold mb-3 mt-5 text-muted text-uppercase fade-up" style="letter-spacing: 1px;"><i class="fas fa-users-cog me-2"></i> Staff & Academic Limits</h6>
    <div class="row g-4 mb-4 fade-up" style="animation-delay: 0.15s;">
        <div class="col-xl-3 col-md-6">
            <div class="stat-card">
                <div class="stat-info">
                    <h3><?= number_format($total_teachers); ?></h3>
                    <p>Active Teachers</p>
                </div>
                <div class="icon-box" style="background: rgba(59, 130, 246, 0.1); color: #3b82f6;"><i class="fas fa-chalkboard-teacher"></i></div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-card">
                <div class="stat-info">
                    <h3><?= number_format($total_courses); ?></h3>
                    <p>Active Courses</p>
                </div>
                <div class="icon-box" style="background: rgba(212, 175, 55, 0.15); color: var(--accent);"><i class="fas fa-book-open"></i></div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-card">
                <div class="stat-info">
                    <h3><?= number_format($trial_students); ?></h3>
                    <p>Trial Students</p>
                </div>
                <div class="icon-box" style="background: rgba(139, 92, 246, 0.1); color: #8b5cf6;"><i class="fas fa-hourglass-half"></i></div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-card" style="border-left: 4px solid #ef4444;">
                <div class="stat-info">
                    <h3 style="color: #ef4444;"><?= number_format($limit_reached); ?></h3>
                    <p>Trial Limit Reached</p>
                </div>
                <div class="icon-box" style="background: rgba(239, 68, 68, 0.1); color: #ef4444;"><i class="fas fa-user-lock"></i></div>
            </div>
        </div>
    </div>

    <div class="row g-4 mb-5 fade-up" style="animation-delay: 0.3s;">
        <div class="col-lg-8">
            <div class="content-box">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="box-title mb-0"><i class="fas fa-chart-area"></i> Income & Student Growth (Last 6 Months)</h5>
                    <span class="badge bg-light text-primary border">Analytics</span>
                </div>
                <div style="position: relative; height: 280px; width: 100%;">
                    <canvas id="growthChart"></canvas>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="content-box">
                <h5 class="box-title"><i class="fas fa-chart-pie"></i> Top Popular Courses</h5>
                <div style="position: relative; height: 250px; width: 100%;">
                    <canvas id="courseChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 fade-up" style="animation-delay: 0.4s;">
        <div class="col-lg-8">
            <div class="content-box">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="box-title mb-0"><i class="fas fa-user-clock"></i> Action Required: Pending Admissions</h5>
                    <a href="view_admissions.php" class="btn btn-sm rounded-pill fw-bold" style="background: rgba(212, 175, 55, 0.15); color: var(--primary-dark);">View All</a>
                </div>
                
                <div class="table-responsive">
                    <table class="table align-middle">
                        <thead>
                            <tr>
                                <th>Student Name</th>
                                <th>Course</th>
                                <th>Payment</th>
                                <th class="text-end">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(!empty($recent_pending)): foreach($recent_pending as $rp): ?>
                            <tr>
                                <td class="fw-bold text-dark"><?= htmlspecialchars($rp['student_name']); ?></td>
                                <td class="text-muted fw-semibold small"><?= htmlspecialchars($rp['course_name']); ?></td>
                                <td>
                                    <?php if($rp['payment_status'] == 'verified'): ?>
                                        <span class="badge-custom bg-success bg-opacity-10 text-success border border-success border-opacity-25">Verified</span>
                                    <?php else: ?>
                                        <span class="badge-custom bg-warning bg-opacity-10 text-warning border border-warning border-opacity-25">Pending</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end">
                                    <a href="process_admission.php?id=<?= $rp['id'] ?>&action=approved" class="btn-action btn-approve" onclick="return confirm('Approve this student?')" title="Approve Student">
                                        <i class="fas fa-check"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; else: ?>
                            <tr>
                                <td colspan="4" class="text-center text-muted py-4">
                                    <i class="fas fa-check-circle fa-2x mb-2 text-success opacity-50"></i><br>
                                    No pending admissions at the moment!
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="content-box">
                <h5 class="box-title"><i class="fas fa-bolt"></i> Quick Actions</h5>
                <div class="row g-3 mt-2">
                    <div class="col-6">
                        <a href="add_course.php" class="qa-card">
                            <div class="qa-icon"><i class="fas fa-book-medical"></i></div>
                            <h5 class="qa-title">Add Course</h5>
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="add_exam.php" class="qa-card">
                            <div class="qa-icon"><i class="fas fa-file-signature"></i></div>
                            <h5 class="qa-title">Create Exam</h5>
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="add_notice.php" class="qa-card">
                            <div class="qa-icon"><i class="fas fa-bullhorn"></i></div>
                            <h5 class="qa-title">Add Notice</h5>
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="add_result.php" class="qa-card">
                            <div class="qa-icon"><i class="fas fa-poll"></i></div>
                            <h5 class="qa-title">Publish Result</h5>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<script>
    document.getElementById('sidebarToggle').addEventListener('click', function() { 
        document.querySelector('.sidebar').classList.toggle('active'); 
    });

    const primaryColor = '#064e3b';
    const accentColor = '#d4af37';
    const lightGreen = '#10b981';
    const blueColor = '#3b82f6';

    // 1. NEW: Income & Student Growth Line Chart (Replaced the static Bar Chart)
    const ctxGrowth = document.getElementById('growthChart').getContext('2d');
    
    // Dummy Data for demonstration (You will fetch this via PHP later)
    const months = ['Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar'];
    const incomeData = [1200, 1900, 2100, 2800, 3500, 4200];
    const studentGrowth = [20, 35, 50, 85, 120, 150];
    
    new Chart(ctxGrowth, {
        type: 'line',
        data: {
            labels: months,
            datasets: [
                {
                    label: 'Monthly Income ($)',
                    data: incomeData,
                    borderColor: lightGreen,
                    backgroundColor: 'rgba(16, 185, 129, 0.1)',
                    borderWidth: 3,
                    tension: 0.4,
                    fill: true,
                    yAxisID: 'y'
                },
                {
                    label: 'New Students',
                    data: studentGrowth,
                    borderColor: accentColor,
                    backgroundColor: 'transparent',
                    borderWidth: 3,
                    borderDash: [5, 5],
                    tension: 0.4,
                    yAxisID: 'y1'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: { mode: 'index', intersect: false },
            plugins: { 
                legend: { position: 'top', labels: { usePointStyle: true, boxWidth: 8, font: { family: 'Outfit', weight: 'bold' } } } 
            },
            scales: {
                y: { 
                    type: 'linear', display: true, position: 'left',
                    title: { display: true, text: 'Income ($)' },
                    grid: { color: '#f1f5f9' } 
                },
                y1: { 
                    type: 'linear', display: true, position: 'right',
                    title: { display: true, text: 'Students Count' },
                    grid: { drawOnChartArea: false } // only draw grid lines for one axis
                },
                x: { grid: { display: false } }
            }
        }
    });

    // 2. Course Popularity Doughnut Chart (Kept exactly as it was)
    const ctxCourse = document.getElementById('courseChart').getContext('2d');
    const courseLabels = <?= json_encode($chart_labels); ?>;
    const courseData = <?= json_encode($chart_data); ?>;

    new Chart(ctxCourse, {
        type: 'doughnut',
        data: {
            labels: courseLabels.length > 0 ? courseLabels : ['No Data Available'],
            datasets: [{
                data: courseData.length > 0 ? courseData : [1],
                backgroundColor: courseLabels.length > 0 ? [primaryColor, accentColor, lightGreen, '#022c22', '#fcd34d'] : ['#e2e8f0'],
                borderWidth: 2,
                borderColor: '#ffffff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            cutout: '70%',
            plugins: {
                legend: { position: 'bottom', labels: { boxWidth: 12, font: { family: 'Outfit' } } }
            }
        }
    });
</script>

<?php include 'includes/footer.php'; ?>