<?php 

include 'auth_check.php';
include '../connection.php';

if (!isset($_SESSION['user_id'])) {
   header("Location: login.php");
   exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Barangay Management System</title>
    <!-- Bootstrap 4.6.2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
   <link rel="stylesheet" type="text/css" href="assets/css/main.css">
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/2.3.4/css/dataTables.dataTables.min.css">
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/2.3.4/css/dataTables.bootstrap4.css">
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/columncontrol/1.1.0/css/columnControl.dataTables.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
 <!-- ✅ Leaflet -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.5/css/lightbox.css"/>

</head>
<style>
    /* Shake animation for the bell */
.bell-alert.shake {
  animation: shake 0.5s infinite;
}

@keyframes shake {
  0% { transform: rotate(0deg); }
  25% { transform: rotate(-15deg); }
  50% { transform: rotate(15deg); }
  75% { transform: rotate(-15deg); }
  100% { transform: rotate(0deg); }
}

</style>
<body>
    <!-- Navigation Bar -->
<?php include 'includes/navbar.php'; ?>

    <!-- Overlay for mobile sidebar -->
    <div class="overlay" id="overlay"></div>

    <!-- Sidebar -->
   <?php include 'includes/sidebar.php'; ?>

    <!-- Main Content -->
    <main class="main-content" id="mainContent">
        <br>
        <br>
        <br>
        <!-- Page Header -->
        <div class="page-header">
            <h1 class="h2">Dashboard</h1>
            <p class="lead">Welcome to Barangay Management System </p>
        </div>
        <br>
       <!-- ✅ Loader (hidden by default) -->
<div class="loader" style="display:none;"></div>
<audio id="emergencyAlarm" src="../uploads/audio/emergency-alarm-with-reverb-29431.mp3" loop></audio>

<!-- ✅ Corrected div tag -->
<div id="page_content"></div>

    </main>

    <!-- Floating Sidebar Toggle Button -->
    <button class="sidebar-toggle" id="sidebarToggle">
        <i class="fas fa-bars"></i>
    </button>

    <!-- Bootstrap & jQuery --> 
   <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
   
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/2.3.4/js/dataTables.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/2.3.4/js/dataTables.bootstrap4.js"></script>
    <script src="https://cdn.datatables.net/columncontrol/1.1.0/js/dataTables.columnControl.js"></script>
    <script src="https://cdn.datatables.net/columncontrol/1.1.0/js/columnControl.dataTables.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.5/js/lightbox.min.js"></script>
    <script>
  setInterval(function() {
    load_emergency_count();
    transaction_counter();
}, 5000);

let isAlarming = false;
let audioUnlocked = false;

// Unlock audio on first click
document.addEventListener('click', function unlockAudio() {
    const alarm = document.getElementById('emergencyAlarm');
    alarm.play().then(() => {
        alarm.pause();
        alarm.currentTime = 0;
        audioUnlocked = true;
        console.log('Audio unlocked ✅');
        document.removeEventListener('click', unlockAudio);
    }).catch(err => console.log('Unlock failed:', err));
});

function load_emergency_count() {
    $.ajax({
        method: 'POST',
        url: 'query/emergency_query.php',
        data: { "loading_emergency_total": 1 },
        success: function(res) {
            $('#emergency_count').html(res);

            const emergencyCount = parseInt(res) || 0;
            const alarm = document.getElementById('emergencyAlarm');
            const bell = document.querySelector('.bell-alert'); // bell icon

            // 🚨 If there are emergencies
            if (emergencyCount > 0 && !isAlarming && audioUnlocked) {
                alarm.play().catch(err => console.log('Autoplay blocked:', err));
                bell?.classList.add('shake'); // start shaking bell
                isAlarming = true;
            }

            // ⏹ Stop the alarm and shake when cleared
            if (emergencyCount === 0 && isAlarming) {
                alarm.pause();
                alarm.currentTime = 0;
                bell?.classList.remove('shake'); // stop shaking
                isAlarming = false;
            }
        }
    });
}




        function transaction_counter(){
             $.ajax({
                method: 'post',
                url: 'query/transaction_query.php',
                data:{
                    "loading_transcations_total": 1
                },
                success: function(res){
                    $('#transactions_counter').html(res);
                }
            })
        }

// ✅ Handle sidebar/nav clicks
$(document).on("click", ".click_page", function () {
    let page = $(this).data("page");
    $('.loader').show(); // show immediately
    $('#page_content').html(''); // optional: clear old page content

    // Add a delay only for effect (optional)
    setTimeout(function () {
        load_pages(page);
    }, 1000);
});

// ✅ Load default page on startup
load_pages("dashboard.php");

function load_pages(page) {
    $('.loader').show(); // ensure loader visible during AJAX

    $.ajax({
        method: 'GET',
        url: 'pages/' + page,
        success: function (res) {
            $('.loader').hide();
            $('#page_content').html(res);
        },
        error: function () {
            $('.loader').hide();
            $('#page_content').html(`
                <div class="alert alert-warning" role="alert">
                     Page not found (404)!
                </div>
            `);
        }
    });
}



        $(document).ready(function() {
            const sidebar = $('#sidebar');
            const mainContent = $('#mainContent');
            const sidebarToggle = $('#sidebarToggle');
            const overlay = $('#overlay');
            
            // Toggle sidebar on button click
            sidebarToggle.click(function() {
                sidebar.toggleClass('show');
                overlay.toggleClass('active');
                
                // Change icon based on sidebar state
                if (sidebar.hasClass('show')) {
                    sidebarToggle.html('<i class="fas fa-times"></i>');
                    mainContent.addClass('sidebar-open');
                } else {
                    sidebarToggle.html('<i class="fas fa-bars"></i>');
                    mainContent.removeClass('sidebar-open');
                }
            });
            
            // Close sidebar when clicking on overlay
            overlay.click(function() {
                sidebar.removeClass('show');
                overlay.removeClass('active');
                sidebarToggle.html('<i class="fas fa-bars"></i>');
                mainContent.removeClass('sidebar-open');
            });
            
            // Handle active menu items
            $('.sidebar .nav-link').click(function() {
                $('.sidebar .nav-link').removeClass('active');
                $(this).addClass('active');
                
                // On mobile, close sidebar after clicking a menu item
                if ($(window).width() < 768) {
                    sidebar.removeClass('show');
                    overlay.removeClass('active');
                    sidebarToggle.html('<i class="fas fa-bars"></i>');
                    mainContent.removeClass('sidebar-open');
                }
            });
            
            // Handle window resize
            $(window).resize(function() {
                if ($(window).width() >= 768) {
                    // On larger screens, ensure sidebar is visible
                    sidebar.addClass('show');
                    overlay.removeClass('active');
                    mainContent.addClass('sidebar-open');
                    sidebarToggle.html('<i class="fas fa-bars"></i>');
                } else {
                    // On smaller screens, ensure sidebar is hidden by default
                    sidebar.removeClass('show');
                    sidebarToggle.html('<i class="fas fa-bars"></i>');
                    mainContent.removeClass('sidebar-open');
                }
            });
            
            // Initialize based on screen size
            if ($(window).width() >= 768) {
                sidebar.addClass('show');
                mainContent.addClass('sidebar-open');
            }
        });
    </script>
</body>
</html>