<?php
// File: index.php
// The public-facing information portal for the Barangay Profiling System.
require_once "db.php";

// Fetch 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'];

// Fetch total number of households (which represent puroks with residents)
$total_puroks_result = $conn->query("SELECT COUNT(DISTINCT purok) as total FROM households JOIN residents ON households.id = residents.household_id WHERE residents.is_archived = 0");
$total_puroks = $total_puroks_result->fetch_assoc()['total'];

// Fetch data for Purok Distribution 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));


// Fetch data for Gender Distribution Chart
$gender_data = [];
$gender_sql = "SELECT gender, COUNT(*) as count FROM residents WHERE is_archived = 0 GROUP BY gender";
$gender_result = $conn->query($gender_sql);
while($row = $gender_result->fetch_assoc()) {
    $gender_data[$row['gender']] = $row['count'];
}
$gender_labels = json_encode(array_keys($gender_data));
$gender_values = json_encode(array_values($gender_data));


// Fetch data for 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));


?>
<!DOCTYPE html>
<html lang="en">
    <link rel="icon" href="logo.jpg" type="image/jpg">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Barangay San Fabian Information Portal</title>
    <!-- **CACHE BUSTING FIX**: Added a unique timestamp to the CSS link -->
    <link rel="stylesheet" href="css/style.css?v=<?php echo time(); ?>">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="public-page">
    <header class="public-header">
        <div class="container">
            <h1><i class="fas fa-landmark"></i> Barangay San Fabian Information Portal</h1>
            <a href="login.php" class="btn btn-primary">
                <i class="fas fa-sign-in-alt"></i> Admin Login
            </a>
        </div>
    </header>

    <main class="public-main">
        <div class="container">
            <div class="public-content-grid">
                <!-- Left Column: Slideshow -->
                <div class="card slideshow-container">
                    <!-- Purok Chart Slide -->
                    <div class="slide fade">
                        <h2 class="card-title">Population by Purok</h2>
                        <div class="chart-container">
                            <canvas id="purokChart"></canvas>
                        </div>
                    </div>
                     <!-- Gender Chart Slide -->
                    <div class="slide fade">
                        <h2 class="card-title">Gender Distribution</h2>
                        <div class="chart-container">
                            <canvas id="genderChart"></canvas>
                        </div>
                    </div>
                    <!-- Voter Chart Slide -->
                    <div class="slide fade">
                        <h2 class="card-title">Voter Distribution</h2>
                        <div class="chart-container">
                            <canvas id="voterChart"></canvas>
                        </div>
                    </div>
                     <!-- Navigation Dots -->
                    <div class="slideshow-dots">
                        <span class="dot" onclick="currentSlide(1)"></span>
                        <span class="dot" onclick="currentSlide(2)"></span>
                        <span class="dot" onclick="currentSlide(3)"></span>
                    </div>
                </div>

                <!-- Right Column: Stats & Recent -->
                <div class="info-column">
                    <div class="stat-card">
                         <div class="stat-card-icon" style="background-color: #17a2b8;"><i class="fas fa-users"></i></div>
                        <div class="stat-card-info">
                            <p>Total Active Residents</p>
                            <h3><?php echo $total_residents; ?></h3>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-card-icon" style="background-color: #28a745;"><i class="fas fa-map-marker-alt"></i></div>
                        <div class="stat-card-info">
                            <p>Number of Puroks</p>
                            <h3><?php echo $total_puroks; ?></h3>
                        </div>
                    </div>
                    <div class="card">
                        <h2 class="card-title">Recently Registered Residents</h2>
                        <div class="table-responsive">
                            <table>
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Purok</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    // Corrected query to use r.id for ordering
                                    $recent_sql = "
                                        SELECT r.first_name, r.last_name, h.purok 
                                        FROM residents r
                                        JOIN households h ON r.household_id = h.id
                                        WHERE r.is_archived = 0
                                        ORDER BY r.id DESC 
                                        LIMIT 5
                                    ";
                                    $recent_result = $conn->query($recent_sql);
                                    if ($recent_result->num_rows > 0) {
                                        while($row = $recent_result->fetch_assoc()) {
                                            echo "<tr>";
                                            echo "<td>" . htmlspecialchars($row['first_name'] . " " . $row['last_name']) . "</td>";
                                            echo "<td>" . htmlspecialchars($row['purok']) . "</td>";
                                            echo "</tr>";
                                        }
                                    } else {
                                        echo "<tr><td colspan='2'>No recent registrations found.</td></tr>";
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
    
    <footer class="public-footer">
         <?php echo date("Y"); ?> Barangay San Fabian Profiling System. All rights reserved.
        <div class="developer-credit">Developed by: Jayson Chalanag Jr. | Jennifer Dumilon | Michelle Ann Geraban</div>
    </footer>

    <script>
    // Slideshow Logic
    let slideIndex = 1;
    let slideInterval = setInterval(() => plusSlides(1), 5000); // Change slide every 5 seconds

    showSlides(slideIndex);

    function plusSlides(n) {
        clearInterval(slideInterval);
        slideInterval = setInterval(() => plusSlides(1), 5000);
        showSlides(slideIndex += n);
    }

    function currentSlide(n) {
        clearInterval(slideInterval);
        slideInterval = setInterval(() => plusSlides(1), 5000);
        showSlides(slideIndex = n);
    }

    function showSlides(n) {
        let i;
        let slides = document.getElementsByClassName("slide");
        let dots = document.getElementsByClassName("dot");
        if (n > slides.length) {slideIndex = 1}
        if (n < 1) {slideIndex = slides.length}
        for (i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }
        for (i = 0; i < dots.length; i++) {
            dots[i].className = dots[i].className.replace(" active", "");
        }
        slides[slideIndex-1].style.display = "block";
        dots[slideIndex-1].className += " active";
    }


    // Chart.js - Purok Chart
    const purokCtx = document.getElementById('purokChart').getContext('2d');
    new Chart(purokCtx, {
        type: 'pie',
        data: {
            labels: <?php echo $purok_labels; ?>,
            datasets: [{
                label: 'Population',
                data: <?php echo $purok_values; ?>,
                backgroundColor: ['#007bff', '#28a745', '#dc3545', '#ffc107', '#6f42c1', '#fd7e14', '#20c997'],
            }]
        },
        options: { responsive: true, maintainAspectRatio: false }
    });

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

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

