<link rel="icon" href="logo.jpg" type="image/jpg">
<?php
// File: dashboard.php
// The main dashboard for administrators after logging in.
require_once "db.php";
check_login();

$page_title = "Dashboard";

// --- DATA FETCHING FOR STAT CARDS ---
// Total Active Residents
$total_residents_result = $conn->query("SELECT COUNT(*) as total FROM residents WHERE is_archived = 0");
$total_residents = $total_residents_result->fetch_assoc()['total'];

// Total Households
$total_households_result = $conn->query("SELECT COUNT(*) as total FROM households");
$total_households = $total_households_result->fetch_assoc()['total'];

// Male Population
$male_count_result = $conn->query("SELECT COUNT(*) as total FROM residents WHERE gender = 'Male' AND is_archived = 0");
$male_count = $male_count_result->fetch_assoc()['total'];

// Female Population
$female_count_result = $conn->query("SELECT COUNT(*) as total FROM residents WHERE gender = 'Female' AND is_archived = 0");
$female_count = $female_count_result->fetch_assoc()['total'];


// --- DATA FETCHING FOR CHARTS ---
// Population by Purok Chart
$purok_data = [];
$purok_sql = "
    SELECT h.purok, COUNT(r.id) as resident_count 
    FROM residents r
    JOIN households h ON r.household_id = h.id
    WHERE r.is_archived = 0
    GROUP BY h.purok
";
$purok_result = $conn->query($purok_sql);
while ($row = $purok_result->fetch_assoc()) {
    $purok_data[$row['purok']] = $row['resident_count'];
}
$purok_labels = json_encode(array_keys($purok_data));
$purok_values = json_encode(array_values($purok_data));

// Gender Distribution Chart
$gender_data = ['Male' => $male_count, 'Female' => $female_count];
$gender_labels = json_encode(array_keys($gender_data));
$gender_values = json_encode(array_values($gender_data));

// Voter Distribution Chart
$voter_data = ['Registered' => 0, 'Not Registered' => 0];
$voter_sql = "SELECT is_voter, COUNT(*) as count FROM residents WHERE is_archived = 0 GROUP BY is_voter";
$voter_result = $conn->query($voter_sql);
while($row = $voter_result->fetch_assoc()) {
    if ($row['is_voter']) {
        $voter_data['Registered'] = $row['count'];
    } else {
        $voter_data['Not Registered'] = $row['count'];
    }
}
$voter_labels = json_encode(array_keys($voter_data));
$voter_values = json_encode(array_values($voter_data));

include 'header.php';
?>

<div class="main-content">
    <div class="page-header">
        <h1>Dashboard</h1>
        <p>Welcome, <?php echo htmlspecialchars($_SESSION['name']); ?>! Here's a summary of the barangay.</p>
    </div>

    <!-- Statistic Cards -->
    <div class="stat-cards-grid">
        <div class="stat-card">
            <div class="stat-card-icon" style="background-color: #007bff;"><i class="fas fa-users"></i></div>
            <div class="stat-card-info">
                <p>Total Residents</p>
                <h3><?php echo $total_residents; ?></h3>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-icon" style="background-color: #17a2b8;"><i class="fas fa-home"></i></div>
            <div class="stat-card-info">
                <p>Total Households</p>
                <h3><?php echo $total_households; ?></h3>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-icon" style="background-color: #28a745;"><i class="fas fa-male"></i></div>
            <div class="stat-card-info">
                <p>Male Population</p>
                <h3><?php echo $male_count; ?></h3>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-icon" style="background-color: #dc3545;"><i class="fas fa-female"></i></div>
            <div class="stat-card-info">
                <p>Female Population</p>
                <h3><?php echo $female_count; ?></h3>
            </div>
        </div>
    </div>

    <!-- Charts -->
    <div class="dashboard-charts-grid">
        <div class="chart-card full-width">
            <h2 class="card-title">Population by Purok</h2>
            <div class="chart-container">
                <canvas id="purokBarChart"></canvas>
            </div>
        </div>
        <div class="chart-card">
            <h2 class="card-title">Gender Distribution</h2>
            <div class="chart-container">
                <canvas id="genderPieChart"></canvas>
            </div>
        </div>
        <div class="chart-card">
            <h2 class="card-title">Voter Distribution</h2>
            <div class="chart-container">
                <canvas id="voterPieChart"></canvas>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    // Purok Bar Chart
    const purokCtx = document.getElementById('purokBarChart').getContext('2d');
    new Chart(purokCtx, {
        type: 'bar',
        data: {
            labels: <?php echo $purok_labels; ?>,
            datasets: [{
                label: 'Number of Residents',
                data: <?php echo $purok_values; ?>,
                backgroundColor: 'rgba(0, 123, 255, 0.5)',
                borderColor: 'rgba(0, 123, 255, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: { beginAtZero: true }
            }
        }
    });

    // Gender Doughnut Chart
    const genderCtx = document.getElementById('genderPieChart').getContext('2d');
    new Chart(genderCtx, {
        type: 'doughnut',
        data: {
            labels: <?php echo $gender_labels; ?>,
            datasets: [{
                data: <?php echo $gender_values; ?>,
                backgroundColor: ['#007bff', '#dc3545'],
            }]
        },
        options: { responsive: true, maintainAspectRatio: false }
    });

    // Voter Doughnut Chart
    const voterCtx = document.getElementById('voterPieChart').getContext('2d');
    new Chart(voterCtx, {
        type: 'doughnut',
        data: {
            labels: <?php echo $voter_labels; ?>,
            datasets: [{
                data: <?php echo $voter_values; ?>,
                backgroundColor: ['#28a745', '#6c757d'],
            }]
        },
        options: { responsive: true, maintainAspectRatio: false }
    });
});
</script>

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

