<?php
session_start();
if (!isset($_SESSION['admin_id']) && $_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit();
}
include '../../include/config.php';

// Get monthly revenue data
$monthly_revenue = [];
for($i = 11; $i >= 0; $i--) {
    $month = date('M Y', strtotime("-$i months"));
    $revenue = $conn->query("SELECT SUM(amount) as total FROM payments WHERE status = 'successful' AND MONTH(created_at) = MONTH(DATE_SUB(NOW(), INTERVAL $i MONTH))")->fetch_assoc()['total'] ?? 0;
    $monthly_revenue[] = ['month' => $month, 'revenue' => $revenue];
}

// Get totals by payment type
$by_type = $conn->query("
    SELECT payment_type, SUM(amount) as total, COUNT(*) as count 
    FROM payments 
    WHERE status = 'successful' 
    GROUP BY payment_type
");

// Get totals by month
$total_revenue = $conn->query("SELECT SUM(amount) as total FROM payments WHERE status = 'successful'")->fetch_assoc()['total'] ?? 0;
$this_year = $conn->query("SELECT SUM(amount) as total FROM payments WHERE status = 'successful' AND YEAR(created_at) = YEAR(NOW())")->fetch_assoc()['total'] ?? 0;
$last_year = $conn->query("SELECT SUM(amount) as total FROM payments WHERE status = 'successful' AND YEAR(created_at) = YEAR(NOW()) - 1")->fetch_assoc()['total'] ?? 0;

$page_title = 'HPS Reports';
include '../../include/header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HPS Financial Reports</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="container mt-4">
    <div class="d-flex justify-content-between mb-4">
        <h2><i class="fas fa-chart-bar me-2"></i> Financial Reports</h2>
        <a href="dashboard.php" class="btn btn-secondary">← Back</a>
    </div>

    <!-- Summary Stats -->
    <div class="row g-3 mb-4">
        <div class="col-md-4">
            <div class="card shadow-sm text-center p-3">
                <h5>Total Revenue</h5>
                <h2 class="text-success">₦<?= number_format($total_revenue, 2) ?></h2>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card shadow-sm text-center p-3">
                <h5>This Year</h5>
                <h2 class="text-primary">₦<?= number_format($this_year, 2) ?></h2>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card shadow-sm text-center p-3">
                <h5>Last Year</h5>
                <h2><?= number_format($last_year, 2) ?></h2>
                <small class="text-<?= $this_year > $last_year ? 'success' : 'danger' ?>">
                    <?= $this_year > $last_year ? '↑' : '↓' ?> <?= number_format($this_year - $last_year, 2) ?>
                </small>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-8">
            <div class="card shadow">
                <div class="card-header bg-white">
                    <h5>Monthly Revenue (12 Months)</h5>
                </div>
                <div class="card-body">
                    <canvas id="revenueChart" height="300"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card shadow">
                <div class="card-header bg-white">
                    <h5>Revenue by Type</h5>
                </div>
                <div class="card-body">
                    <canvas id="typeChart" height="250"></canvas>
                    <div class="mt-3">
                        <?php while($t = $by_type->fetch_assoc()): ?>
                            <div class="d-flex justify-content-between mb-1">
                                <span><?= ucfirst(str_replace('_', ' ', $t['payment_type'])) ?>:</span>
                                <span class="fw-bold">₦<?= number_format($t['total'], 2) ?></span>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="mt-4">
        <button class="btn btn-primary" onclick="window.print()"><i class="fas fa-print"></i> Print Report</button>
    </div>
</div>

<script>
<?php
$labels = [];
$data = [];
foreach($monthly_revenue as $m) {
    $labels[] = $m['month'];
    $data[] = $m['revenue'];
}
?>
new Chart(document.getElementById('revenueChart'), {
    type: 'line',
    data: {
        labels: <?= json_encode($labels) ?>,
        datasets: [{
            label: 'Revenue (₦)',
            data: <?= json_encode($data) ?>,
            borderColor: '#d4a017',
            backgroundColor: 'rgba(212,160,23,0.1)',
            fill: true,
            tension: 0.3
        }]
    }
});

<?php
$type_labels = [];
$type_data = [];
$type_reset = $conn->query("SELECT payment_type, SUM(amount) as total FROM payments WHERE status = 'successful' GROUP BY payment_type");
while($t = $type_reset->fetch_assoc()) {
    $type_labels[] = ucfirst(str_replace('_', ' ', $t['payment_type']));
    $type_data[] = $t['total'];
}
?>
new Chart(document.getElementById('typeChart'), {
    type: 'doughnut',
    data: {
        labels: <?= json_encode($type_labels) ?>,
        datasets: [{
            data: <?= json_encode($type_data) ?>,
            backgroundColor: ['#d4a017', '#28a745', '#17a2b8', '#dc3545', '#6c757d']
        }]
    }
});
</script>
<?php include '../../include/footer.php'; ?>