<?php
require_once __DIR__ . '/../../includes/dashboard-config.php';

// For role-specific pages, add:
checkRoleAccess(ROLE_STUDENT); // or ROLE_COUNSELOR or ROLE_ADMIN
require_once '../../includes/config.php';
require_once '../../includes/auth.php';
require_once '../../includes/functions.php';

if (!isLoggedIn() || !hasRole('admin')) {
    header('Location: ../login.php');
    exit();
}

// Default report period (last 30 days)
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

// Get report data
$applications_by_status = $pdo->query("
    SELECT application_status, COUNT(*) as count 
    FROM applications 
    WHERE created_at BETWEEN '$start_date' AND '$end_date 23:59:59'
    GROUP BY application_status
")->fetchAll(PDO::FETCH_ASSOC);

$students_by_country = $pdo->query("
    SELECT c.name, COUNT(*) as count
    FROM students s
    JOIN applications a ON s.id = a.student_id
    JOIN universities u ON a.university_id = u.id
    JOIN countries c ON u.country_id = c.id
    WHERE a.created_at BETWEEN '$start_date' AND '$end_date 23:59:59'
    GROUP BY c.name
    ORDER BY count DESC
")->fetchAll(PDO::FETCH_ASSOC);

$revenue_data = $pdo->query("
    SELECT DATE(payment_date) as date, SUM(amount) as total
    FROM payments
    WHERE status = 'completed'
    AND payment_date BETWEEN '$start_date' AND '$end_date 23:59:59'
    GROUP BY DATE(payment_date)
    ORDER BY date
")->fetchAll(PDO::FETCH_ASSOC);

include '../../includes/header.php';
?>

<div class="container py-5">
    <h2 class="mb-4">System Reports</h2>
    
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0">Report Filters</h5>
        </div>
        <div class="card-body">
            <form method="get" class="row">
                <div class="col-md-5">
                    <div class="form-group">
                        <label for="start_date">Start Date</label>
                        <input type="date" class="form-control" id="start_date" name="start_date" 
                               value="<?= htmlspecialchars($start_date) ?>">
                    </div>
                </div>
                <div class="col-md-5">
                    <div class="form-group">
                        <label for="end_date">End Date</label>
                        <input type="date" class="form-control" id="end_date" name="end_date" 
                               value="<?= htmlspecialchars($end_date) ?>">
                    </div>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary btn-block">Generate</button>
                </div>
            </form>
        </div>
    </div>
    
    <div class="row">
        <div class="col-lg-6">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Applications by Status</h5>
                </div>
                <div class="card-body">
                    <canvas id="applicationsChart" height="300"></canvas>
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Revenue Trend</h5>
                </div>
                <div class="card-body">
                    <canvas id="revenueChart" height="300"></canvas>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <div class="col-lg-6">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Students by Destination Country</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Country</th>
                                    <th>Students</th>
                                    <th>Percentage</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $total = array_sum(array_column($students_by_country, 'count'));
                                foreach ($students_by_country as $row): 
                                    $percentage = $total > 0 ? round(($row['count'] / $total) * 100, 1) : 0;
                                ?>
                                    <tr>
                                        <td><?= htmlspecialchars($row['name']) ?></td>
                                        <td><?= $row['count'] ?></td>
                                        <td>
                                            <div class="progress" style="height: 20px;">
                                                <div class="progress-bar" role="progressbar" 
                                                     style="width: <?= $percentage ?>%" 
                                                     aria-valuenow="<?= $percentage ?>" 
                                                     aria-valuemin="0" 
                                                     aria-valuemax="100">
                                                    <?= $percentage ?>%
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Export Reports</h5>
                </div>
                <div class="card-body">
                    <div class="list-group">
                        <a href="export.php?type=applications&start_date=<?= $start_date ?>&end_date=<?= $end_date ?>" 
                           class="list-group-item list-group-item-action">
                            <i class="fas fa-file-export mr-2"></i> Export Applications Data (CSV)
                        </a>
                        <a href="export.php?type=payments&start_date=<?= $start_date ?>&end_date=<?= $end_date ?>" 
                           class="list-group-item list-group-item-action">
                            <i class="fas fa-file-invoice-dollar mr-2"></i> Export Payments Data (CSV)
                        </a>
                        <a href="generate-pdf.php?type=summary&start_date=<?= $start_date ?>&end_date=<?= $end_date ?>" 
                           class="list-group-item list-group-item-action">
                            <i class="fas fa-file-pdf mr-2"></i> Generate Summary Report (PDF)
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Applications by Status Chart
const appsCtx = document.getElementById('applicationsChart').getContext('2d');
const appsChart = new Chart(appsCtx, {
    type: 'doughnut',
    data: {
        labels: <?= json_encode(array_column($applications_by_status, 'application_status')) ?>,
        datasets: [{
            data: <?= json_encode(array_column($applications_by_status, 'count')) ?>,
            backgroundColor: [
                '#36a2eb', '#ff6384', '#4bc0c0', '#ff9f40', '#9966ff', '#ffcd56'
            ]
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: {
                position: 'right'
            }
        }
    }
});

// Revenue Trend Chart
const revCtx = document.getElementById('revenueChart').getContext('2d');
const revChart = new Chart(revCtx, {
    type: 'line',
    data: {
        labels: <?= json_encode(array_column($revenue_data, 'date')) ?>,
        datasets: [{
            label: 'Daily Revenue (USD)',
            data: <?= json_encode(array_column($revenue_data, 'total')) ?>,
            borderColor: '#4bc0c0',
            backgroundColor: 'rgba(75, 192, 192, 0.1)',
            fill: true,
            tension: 0.1
        }]
    },
    options: {
        responsive: true,
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});
</script>

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