<?php
/**
 * Village Statistics
 * Dashboard with charts and statistics
 */

session_start();
require_once '../db_connect.php';

$allowed_roles = ['village_chairman', 'land_officer', 'surveyor', 'district_officer', 'land_council'];
if(!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header('Location: ../login');
    exit;
}

$user_role = $_SESSION['role'];
$village_id = $_SESSION['village_id'] ?? null;

$where = ($user_role !== 'district_officer' && $village_id) ? "village_id = $village_id" : "1=1";

// Get statistics
$stats = [];

// Total lands
$result = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM lands WHERE $where");
$stats['total_lands'] = mysqli_fetch_assoc($result)['cnt'];

// By status
$status_stats = [];
$result = mysqli_query($conn, "SELECT status, COUNT(*) as cnt FROM lands WHERE $where GROUP BY status");
while($row = mysqli_fetch_assoc($result)) {
    $status_stats[$row['status']] = $row['cnt'];
}

// Total area
$result = mysqli_query($conn, "SELECT SUM(total_area) as total FROM lands WHERE $where AND area_unit = 'acres'");
$stats['total_area'] = mysqli_fetch_assoc($result)['total'] ?? 0;

// Landowners
$result = mysqli_query($conn, "SELECT COUNT(DISTINCT user_id) as cnt FROM lands WHERE $where");
$stats['landowners'] = mysqli_fetch_assoc($result)['cnt'];

// Disputes
$dispute_where = ($user_role !== 'district_officer' && $village_id) ? "village_id = $village_id" : "1=1";
$result = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM land_disputes WHERE $dispute_where AND status NOT IN ('resolved', 'dismissed')");
$stats['active_disputes'] = mysqli_fetch_assoc($result)['cnt'];

$result = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM land_disputes WHERE $dispute_where AND status IN ('resolved', 'dismissed')");
$stats['resolved_disputes'] = mysqli_fetch_assoc($result)['cnt'];

// Monthly registrations (last 6 months)
$monthly_data = [];
for($i = 5; $i >= 0; $i--) {
    $month = date('Y-m', strtotime("-$i months"));
    $result = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM lands WHERE $where AND DATE_FORMAT(created_at, '%Y-%m') = '$month'");
    $monthly_data[$month] = mysqli_fetch_assoc($result)['cnt'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Statistics - Land Secure CBC</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .admin-main { margin-left: 280px; padding: 24px; min-height: 100vh; background: #f0f2f5; }
        @media (max-width: 1024px) { .admin-main { margin-left: 0; padding-top: 90px; } }

        .page-header { margin-bottom: 24px; }
        .page-header h1 { font-size: 24px; font-weight: 700; color: #1a1d21; display: flex; align-items: center; gap: 12px; }
        .page-header h1 i { color: #8b5cf6; }

        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 24px; }

        .stat-card { background: white; border-radius: 16px; padding: 24px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }
        .stat-card .icon { width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 20px; color: white; margin-bottom: 16px; }
        .stat-card .icon.purple { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .stat-card .icon.green { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); }
        .stat-card .icon.orange { background: linear-gradient(135deg, #f5af19 0%, #f12711 100%); }
        .stat-card .icon.blue { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
        .stat-card .value { font-size: 32px; font-weight: 700; color: #1a1d21; }
        .stat-card .label { font-size: 14px; color: #64748b; }

        .charts-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 24px; }
        .chart-card { background: white; border-radius: 16px; padding: 24px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }
        .chart-card h3 { font-size: 16px; font-weight: 600; color: #1a1d21; margin: 0 0 20px; display: flex; align-items: center; gap: 10px; }
        .chart-card h3 i { color: #11998e; }
        .chart-container { position: relative; height: 300px; }

        @media (max-width: 768px) { .charts-grid { grid-template-columns: 1fr; } }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="admin-main">
        <div class="page-header">
            <h1><i class="fas fa-chart-pie"></i> Village Statistics</h1>
            <p style="color: #64748b; margin: 8px 0 0;">Takwimu za Kijiji / Overview of land data</p>
        </div>

        <div class="stats-grid">
            <div class="stat-card">
                <div class="icon purple"><i class="fas fa-map"></i></div>
                <div class="value"><?php echo number_format($stats['total_lands']); ?></div>
                <div class="label">Total Lands / Ardhi Zote</div>
            </div>
            <div class="stat-card">
                <div class="icon green"><i class="fas fa-ruler-combined"></i></div>
                <div class="value"><?php echo number_format($stats['total_area'], 2); ?></div>
                <div class="label">Total Acres / Ekari</div>
            </div>
            <div class="stat-card">
                <div class="icon blue"><i class="fas fa-users"></i></div>
                <div class="value"><?php echo number_format($stats['landowners']); ?></div>
                <div class="label">Landowners / Wamiliki</div>
            </div>
            <div class="stat-card">
                <div class="icon orange"><i class="fas fa-gavel"></i></div>
                <div class="value"><?php echo number_format($stats['active_disputes']); ?></div>
                <div class="label">Active Disputes / Migogoro</div>
            </div>
        </div>

        <div class="charts-grid">
            <div class="chart-card">
                <h3><i class="fas fa-chart-pie"></i> Lands by Status</h3>
                <div class="chart-container">
                    <canvas id="statusChart"></canvas>
                </div>
            </div>
            <div class="chart-card">
                <h3><i class="fas fa-chart-line"></i> Monthly Registrations</h3>
                <div class="chart-container">
                    <canvas id="monthlyChart"></canvas>
                </div>
            </div>
            <div class="chart-card">
                <h3><i class="fas fa-chart-bar"></i> Disputes Overview</h3>
                <div class="chart-container">
                    <canvas id="disputesChart"></canvas>
                </div>
            </div>
        </div>
    </main>

    <script src="../assets/vendor/jquery/jquery.min.js"></script>
    <script>
        // Status Chart
        new Chart(document.getElementById('statusChart'), {
            type: 'doughnut',
            data: {
                labels: [<?php echo implode(',', array_map(function($k) { return "'" . ucfirst(str_replace('_', ' ', $k)) . "'"; }, array_keys($status_stats))); ?>],
                datasets: [{
                    data: [<?php echo implode(',', array_values($status_stats)); ?>],
                    backgroundColor: ['#22c55e', '#f59e0b', '#3b82f6', '#8b5cf6', '#ef4444', '#6b7280']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { position: 'bottom' } }
            }
        });

        // Monthly Chart
        new Chart(document.getElementById('monthlyChart'), {
            type: 'line',
            data: {
                labels: [<?php echo implode(',', array_map(function($m) { return "'" . date('M Y', strtotime($m . '-01')) . "'"; }, array_keys($monthly_data))); ?>],
                datasets: [{
                    label: 'Registrations',
                    data: [<?php echo implode(',', array_values($monthly_data)); ?>],
                    borderColor: '#11998e',
                    backgroundColor: 'rgba(17, 153, 142, 0.1)',
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: { y: { beginAtZero: true } }
            }
        });

        // Disputes Chart
        new Chart(document.getElementById('disputesChart'), {
            type: 'bar',
            data: {
                labels: ['Active', 'Resolved'],
                datasets: [{
                    data: [<?php echo $stats['active_disputes']; ?>, <?php echo $stats['resolved_disputes']; ?>],
                    backgroundColor: ['#f59e0b', '#22c55e']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: { y: { beginAtZero: true } }
            }
        });
    </script>
</body>
</html>
