<?php
require_once 'config/config.php';
require_once 'config/database.php';
require_once 'models/Student.php';

requireLogin();

$database = new Database();
$db = $database->getConnection();
$student = new Student($db);

// Get statistics
$stats = $student->getStats();

// Get students by status
$stmt_active = $db->prepare("SELECT COUNT(*) as count FROM students WHERE status = 'Active'");
$stmt_active->execute();
$active_count = $stmt_active->fetch(PDO::FETCH_ASSOC)['count'];

$stmt_inactive = $db->prepare("SELECT COUNT(*) as count FROM students WHERE status = 'Inactive'");
$stmt_inactive->execute();
$inactive_count = $stmt_inactive->fetch(PDO::FETCH_ASSOC)['count'];

$stmt_graduated = $db->prepare("SELECT COUNT(*) as count FROM students WHERE status = 'Graduated'");
$stmt_graduated->execute();
$graduated_count = $stmt_graduated->fetch(PDO::FETCH_ASSOC)['count'];

// Get monthly registrations
$stmt_monthly = $db->prepare("
    SELECT 
        DATE_FORMAT(joining_date, '%Y-%m') as month,
        COUNT(*) as count
    FROM students 
    WHERE joining_date >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
    GROUP BY DATE_FORMAT(joining_date, '%Y-%m')
    ORDER BY month ASC
");
$stmt_monthly->execute();
$monthly_data = $stmt_monthly->fetchAll(PDO::FETCH_ASSOC);

// Get fee collection summary
$stmt_fees = $db->prepare("
    SELECT 
        SUM(total_fee) as total_fees,
        SUM(fees_deposit) as collected_fees,
        SUM(pending_fee) as pending_fees,
        AVG(total_fee) as avg_fee
    FROM students
");
$stmt_fees->execute();
$fee_summary = $stmt_fees->fetch(PDO::FETCH_ASSOC);

// Get recent students
$stmt_recent = $db->prepare("
    SELECT student_name, student_id, joining_date, status
    FROM students 
    ORDER BY created_at DESC 
    LIMIT 10
");
$stmt_recent->execute();
$recent_students = $stmt_recent->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reports - <?php echo APP_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            border-radius: 8px;
            margin: 2px 0;
            transition: all 0.3s ease;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            color: white;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
        }
        .main-content {
            background-color: #f8f9fa;
            min-height: 100vh;
        }
        .report-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            border: none;
            transition: transform 0.3s ease;
        }
        .report-card:hover {
            transform: translateY(-5px);
        }
        .chart-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            padding: 20px;
            margin-bottom: 20px;
        }
        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: white;
        }
        .recent-students {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0">
                <div class="sidebar">
                    <div class="p-3">
                        <h4 class="text-center mb-4">
                            <i class="fas fa-graduation-cap me-2"></i>
                            <?php echo APP_NAME; ?>
                        </h4>
                        <nav class="nav flex-column">
                            <a class="nav-link" href="index.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                            <a class="nav-link" href="add_student.php">
                                <i class="fas fa-user-plus me-2"></i>Add Student
                            </a>
                            <a class="nav-link active" href="reports.php">
                                <i class="fas fa-chart-bar me-2"></i>Reports
                            </a>
                            <a class="nav-link" href="settings.php">
                                <i class="fas fa-cog me-2"></i>Settings
                            </a>
                            <hr class="my-3">
                            <a class="nav-link" href="logout.php">
                                <i class="fas fa-sign-out-alt me-2"></i>Logout
                            </a>
                        </nav>
                    </div>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 px-0">
                <div class="main-content">
                    <!-- Top Navigation -->
                    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
                        <div class="container-fluid">
                            <span class="navbar-brand mb-0 h1">Reports & Analytics</span>
                            <div class="d-flex align-items-center">
                                <span class="me-3">Welcome, <?php echo $_SESSION['admin_name']; ?></span>
                                <div class="dropdown">
                                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                        <i class="fas fa-user-circle"></i>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a class="dropdown-item" href="profile.php"><i class="fas fa-user me-2"></i>Profile</a></li>
                                        <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                                        <li><hr class="dropdown-divider"></li>
                                        <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </nav>

                    <div class="p-4">
                        <!-- Summary Cards -->
                        <div class="row mb-4">
                            <div class="col-md-3 mb-3">
                                <div class="card report-card">
                                    <div class="card-body d-flex align-items-center">
                                        <div class="stat-icon bg-primary me-3">
                                            <i class="fas fa-users"></i>
                                        </div>
                                        <div>
                                            <h6 class="card-title mb-0">Total Students</h6>
                                            <h4 class="mb-0"><?php echo $stats['total_students']; ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="card report-card">
                                    <div class="card-body d-flex align-items-center">
                                        <div class="stat-icon bg-success me-3">
                                            <i class="fas fa-user-check"></i>
                                        </div>
                                        <div>
                                            <h6 class="card-title mb-0">Active Students</h6>
                                            <h4 class="mb-0"><?php echo $stats['active_students']; ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="card report-card">
                                    <div class="card-body d-flex align-items-center">
                                        <div class="stat-icon bg-info me-3">
                                            <i class="fas fa-rupee-sign"></i>
                                        </div>
                                        <div>
                                            <h6 class="card-title mb-0">Total Revenue</h6>
                                            <h4 class="mb-0"><?php echo formatCurrency($fee_summary['collected_fees']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="card report-card">
                                    <div class="card-body d-flex align-items-center">
                                        <div class="stat-icon bg-warning me-3">
                                            <i class="fas fa-exclamation-triangle"></i>
                                        </div>
                                        <div>
                                            <h6 class="card-title mb-0">Pending Revenue</h6>
                                            <h4 class="mb-0"><?php echo formatCurrency($fee_summary['pending_fees']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <!-- Student Status Chart -->
                            <div class="col-md-6 mb-4">
                                <div class="chart-container">
                                    <h5 class="mb-3">
                                        <i class="fas fa-chart-pie me-2"></i>Student Status Distribution
                                    </h5>
                                    <canvas id="statusChart" width="400" height="300"></canvas>
                                </div>
                            </div>

                            <!-- Monthly Registrations Chart -->
                            <div class="col-md-6 mb-4">
                                <div class="chart-container">
                                    <h5 class="mb-3">
                                        <i class="fas fa-chart-line me-2"></i>Monthly Registrations (Last 12 Months)
                                    </h5>
                                    <canvas id="monthlyChart" width="400" height="300"></canvas>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <!-- Fee Collection Summary -->
                            <div class="col-md-8 mb-4">
                                <div class="chart-container">
                                    <h5 class="mb-3">
                                        <i class="fas fa-chart-bar me-2"></i>Fee Collection Summary
                                    </h5>
                                    <div class="row">
                                        <div class="col-md-4 text-center">
                                            <h6 class="text-muted">Total Fees</h6>
                                            <h4 class="text-primary"><?php echo formatCurrency($fee_summary['total_fees']); ?></h4>
                                        </div>
                                        <div class="col-md-4 text-center">
                                            <h6 class="text-muted">Collected</h6>
                                            <h4 class="text-success"><?php echo formatCurrency($fee_summary['collected_fees']); ?></h4>
                                        </div>
                                        <div class="col-md-4 text-center">
                                            <h6 class="text-muted">Pending</h6>
                                            <h4 class="text-warning"><?php echo formatCurrency($fee_summary['pending_fees']); ?></h4>
                                        </div>
                                    </div>
                                    <div class="mt-3">
                                        <?php 
                                        $collection_rate = $fee_summary['total_fees'] > 0 ? ($fee_summary['collected_fees'] / $fee_summary['total_fees']) * 100 : 0;
                                        ?>
                                        <div class="progress" style="height: 25px;">
                                            <div class="progress-bar bg-success" role="progressbar" style="width: <?php echo $collection_rate; ?>%">
                                                <?php echo number_format($collection_rate, 1); ?>% Collected
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Recent Students -->
                            <div class="col-md-4 mb-4">
                                <div class="recent-students">
                                    <div class="p-3 border-bottom">
                                        <h5 class="mb-0">
                                            <i class="fas fa-clock me-2"></i>Recent Students
                                        </h5>
                                    </div>
                                    <div class="p-0">
                                        <?php foreach ($recent_students as $recent): ?>
                                        <div class="d-flex align-items-center p-3 border-bottom">
                                            <div class="flex-shrink-0">
                                                <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                    <i class="fas fa-user"></i>
                                                </div>
                                            </div>
                                            <div class="flex-grow-1 ms-3">
                                                <h6 class="mb-1"><?php echo $recent['student_name']; ?></h6>
                                                <small class="text-muted"><?php echo $recent['student_id']; ?></small>
                                                <br>
                                                <small class="text-muted"><?php echo formatDate($recent['joining_date']); ?></small>
                                            </div>
                                            <div>
                                                <span class="badge bg-<?php echo $recent['status'] == 'Active' ? 'success' : ($recent['status'] == 'Inactive' ? 'danger' : 'info'); ?>">
                                                    <?php echo $recent['status']; ?>
                                                </span>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Student Status Chart
        const statusCtx = document.getElementById('statusChart').getContext('2d');
        new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: ['Active', 'Inactive', 'Graduated'],
                datasets: [{
                    data: [<?php echo $active_count; ?>, <?php echo $inactive_count; ?>, <?php echo $graduated_count; ?>],
                    backgroundColor: ['#28a745', '#dc3545', '#17a2b8'],
                    borderWidth: 2,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                aspectRatio: 1.5,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });

        // Monthly Registrations Chart
        const monthlyCtx = document.getElementById('monthlyChart').getContext('2d');
        const monthlyData = <?php echo json_encode($monthly_data); ?>;
        const months = monthlyData.map(item => item.month);
        const counts = monthlyData.map(item => item.count);

        new Chart(monthlyCtx, {
            type: 'line',
            data: {
                labels: months,
                datasets: [{
                    label: 'New Registrations',
                    data: counts,
                    borderColor: '#667eea',
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                aspectRatio: 2,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    </script>
</body>
</html>
