<?php
session_start();
// Use the root pmed functions and DB connection
include_once 'functions.php';
if (!isset($_SESSION['username']) || ($_SESSION['user_type'] !== 'admin' && $_SESSION['user_type'] !== 'user')) {
    header("Location: ../login.php");
    exit();
}

$divisionId = $_SESSION['division_id'] ?? $_POST['division_id'] ?? $_GET['division_id'] ?? 1;
$_SESSION['division_id'] = $divisionId;
$divisionName = getDivisionName($divisionId);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PMED - User Panel</title>
    <link rel="stylesheet" href="../css/admin_dashboard.css">
    <link rel="stylesheet" href="../css/user_modal.css">
    <link rel="stylesheet" href="../css/preview.css">
    <!-- Load Chart.js first -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
    <!-- Load Brython after Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/brython@3.9.5/brython.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/brython@3.9.5/brython_stdlib.js"></script>
    <script src="script.js"></script>
</head>
<body onload="initializeDashboard();">
    <div class="navbar">
        <div class="navbar-center">
            <img src="../icons/ppdco_logo_icon.webp" alt="PPDCO Logo" class="navbar-logo">
            <img src="../icons/seal_laguna.webp" alt="Laguna Seal" class="navbar-logo">
            <img src="../icons/High-Resolution_Logo_PH.webp" alt="Laguna Seal" class="navbar-logo" loading="lazy" decoding="async">
            <div class="navbar-text">
                <a>Republic of the Philippines - PROVINCIAL GOVERNMENT OF LAGUNA</a>
                <p>PROVINCIAL PLANNING AND DEVELOPMENT COORDINATOR'S OFFICE</p>
            </div>
        </div>
        <div class="navbar-right">
            <nav>
                <ul>
                    <li>
                        <a href="admin_dashboard.php" class="nav-link" data-section="divisions">
                            <img src="../icons/navigator/divisions.svg" alt="Divisions" class="nav-icon">
                            <span class="nav-text">DOCUMENTS</span>
                        </a>
                    </li>
                    <li>
                        <a href="admin_bulletin.php" class="nav-link" data-section="manageDivisions">
                            <img src="../icons/navigator/manage-divisions.svg" alt="Manage" class="nav-icon">
                            <span class="nav-text">BULLETIN</span>
                        </a>
                    </li>
                    <li>
                        <a href="#" class="nav-link" data-section="composeMessage" onclick="openComposeModal(); return false;" style="cursor:pointer;">
                            <img src="../icons/action/compose.svg" alt="Manage" class="nav-icon">
                            <span class="nav-text">COMPOSE</span>
                        </a>
                    </li>
                    <li>
                        <a href="logout.php" class="nav-link">
                            <img src="../icons/navigator/logout.svg" alt="Logout" class="nav-icon">
                            <span class="nav-text">LOG OUT</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    </div>
    <div id="addFileModal" class="modal">
            <div class="modal-content">
                <span class="close-btn" onclick="closeModal('addFileModal')">&times;</span>
                <h2 id="modalTitle">Add Document</h2>
                <form id="addFileForm" method="post" action="../functions.php" enctype="multipart/form-data">
                    <input type="hidden" id="documentId" name="documentId">
                    <div class="input-field">
                        <input type="text" id="fileName" name="fileName" class="input-text" required>
                        <label class="label" for="fileName">File Name</label>
                    </div>
                    <div class="input-field">
                        <input type="text" id="refNo" name="refNo" class="input-text" required>
                        <label class="label" for="refNo">Reference Number (EX: PGL_PPDCO_FILE123)</label>
                    </div>
                    <div class="input-field">
                        <input type="text" id="fileAuthor" name="fileAuthor" class="input-text" required>
                        <label class="label" for="fileAuthor">Author</label>
                    </div>
                    <div class="input-field">
                        <textarea id="fileDescription" name="fileDescription" class="input-text" rows="4" required></textarea>
                        <label class="label" for="fileDescription">Description</label>
                    </div>
                    <div class="dropdown-select">
                        <select id="fileStatus" name="fileStatus" class="input-text" required>
                            <option value="Available">Available</option>
                            <option value="Draft">Draft</option>
                            <option value="Updated">Updated</option>
                            <option value="For update">For Update</option>
                            <option value="For disposal">For Disposal</option>
                            <option value="For review">For Review</option>
                            <option value="For approval">For Approval</option>
                            <option value="Approved">Approved</option>
                        </select>
                    </div>
                    <div id="existingFileSection" style="display:none; margin-bottom: 10px;"></div>
                    <div id="uploadedFileSection" class="input-field" style="display: none;">
                        <p id="uploadedFileName"></p>
                        <button type="button" onclick="removeUploadedFile()">Remove File</button>
                    </div>
                    <label class="custum-file-upload" id="fileUploadSection" for="fileInput" style="cursor:pointer;">
                        <div class="icon">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="" viewBox="0 0 24 24">
                                <path fill="" d="M10 1C9.73478 1 9.48043 1.10536 9.29289 1.29289L3.29289 7.29289C3.10536 7.48043 3 7.73478 3 8V20C3 21.6569 4.34315 23 6 23H7C7.55228 23 8 22.5523 8 22C8 21.4477 7.55228 21 7 21H6C5.44772 21 5 20.5523 5 20V9H10C10.5523 9 11 8.55228 11 8V3H18C18.5523 3 19 3.44772 19 4V9C19 9.55228 19.4477 10 20 10C20.5523 10 21 9.55228 21 9V4C21 2.34315 19.6569 1 18 1H10ZM9 7H6.41421L9 4.41421V7ZM14 15.5C14 14.1193 15.1193 13 16.5 13C17.8807 13 19 14.1193 19 15.5V16V17H20C21.1046 17 22 17.8954 22 19C22 20.1046 21.1046 21 20 21H13C11.8954 21 11 20.1046 11 19C11 17.8954 11.8954 17 13 17H14V16V15.5ZM16.5 11C14.142 11 12.2076 12.8136 12.0156 15.122C10.2825 15.5606 9 17.1305 9 19C9 21.2091 10.7909 23 13 23H20C22.2091 23 24 21.2091 24 19C24 17.1305 22.7175 15.5606 20.9844 15.122C20.7924 12.8136 18.858 11 16.5 11Z" clip-rule="evenodd" fill-rule="evenodd"></path>
                            </svg>
                        </div>
                        <div class="text">
                            <span>Click to upload file</span>
                        </div>
                        <input type="file" id="fileInput" name="fileInput" accept="*/*" onchange="handleFileUpload(this)" style="display:none;">
                    </label>
                    <button class="save-button" type="submit" name="add_document">
                        Save Document
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="dashboard-container">
        <div class="section-header">
        <button id="sidebarToggle" class="sidebar-toggle">
            <img src="../icons/navigator/piechart.svg" alt="Toggle Sidebar">
        </button>
        <p>PPDCO - PROJECT MONITORING AND EVALUATION DIVISION - USER PANEL</p>
        </div>
        <div class="section-content">
            <div class="sidebar" id="sidebar">
                <div class="statistics-section">
                    <div class="file-summary">
                        <?php include "piechart.php" ?>
                    </div>
                </div>
            <div class="container">
                <div class="filter-group">
                    <div class="filter">
                    <a class="current-division" id="currentDivisionName" data-division-id="<?= htmlspecialchars($divisionId) ?>">
                        <?= htmlspecialchars($divisionName) ?>
                    </a>
                    </div>
                    <div class="action-buttons">
                        <div class="search-bar">
                            <form method="GET" class="search-form">
                                <span class="search">
                                    <img src="../icons/action/search.svg" alt="Search">
                                </span>
                                <input type="text" id="searchQuery" name="search_query" placeholder="Search documents..." value="<?= isset($_GET['search_query']) ? htmlspecialchars($_GET['search_query']) : '' ?>">
                                <input type="hidden" name="division_id" value="<?= $divisionId ?>">
                            </form>
                        </div>
                        <button class="add-button" onclick="openAddModal()">
                            <img src='../icons/action/add.svg' alt='Add'>
                            Add File
                        </button>
                    </div>
                    <div class="filter_sort">
                        <input type="hidden" id="sortOrder" value="asc">
                        <input type="hidden" id="fileType" value="">
                        <div class="dropdown">
                            <button class="filter-button" id="sortButton">
                                <img src="../icons/action/sort.svg" alt="Sort" class="add-icon" id="sortIcon">Sequence
                            </button>
                            <div class="dropdown-content" data-dropdown="sort">
                                <a href="#" data-action="sort" data-value="asc">Filename: A-Z</a>
                                <a href="#" data-action="sort" data-value="desc">Filename: Z-A</a>
                                <a href="#" data-action="sort" data-value="date_asc">Date Uploaded: Ascending</a>
                                <a href="#" data-action="sort" data-value="date_desc">Date Uploaded: Descending</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="filter-button">
                                <img src="../icons/action/file-solid.svg" alt="Filter" class="add-icon">File Type
                            </button>
                            <div class="dropdown-content" data-dropdown="file_type">
                                <a href="#" data-action="file_type" data-value="doc,docx">Word Documents (doc, docx)</a>
                                <a href="#" data-action="file_type" data-value="xls,xlsx">Excel Files (xls, xlsx)</a>
                                <a href="#" data-action="file_type" data-value="ppt,pptx">PowerPoint Files (ppt, pptx)</a>
                                <a href="#" data-action="file_type" data-value="pdf">PDF Files (pdf)</a>
                                <a href="#" data-action="file_type" data-value="jpg,jpeg,png,gif,bmp,ico,webp,tiff">Images (jpg, jpeg, png, gif, bmp, etc.)</a>
                                <a href="#" data-action="file_type" data-value="mp4,avi,mkv,mov,wmv">Videos (mp4, avi, mkv, etc.)</a>
                                <a href="#" data-action="file_type" data-value="mp3,wav,flac,aac">Audio (mp3, wav, flac, etc.)</a>
                                <a href="#" data-action="file_type" data-value="html,php,js,css,sql,py">Code Files (html, php, js, etc.)</a>
                                <a href="#" data-action="file_type" data-value="zip,rar,7z">Compressed Files (zip, rar, 7z, etc.)</a>
                                <a href="#" data-action="file_type" data-value="other">Other Files</a>
                            </div>
                        </div>
                        <button class="filter-button" onclick="clearFilters()">
                            <img src="../icons/action/refresh.svg" alt="Clear" class="add-icon">Clear Filters
                        </button>
                    </div>
                     <div class="table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th>Reference No.</th>
                                    <th>File Name</th>
                                    <th>Author</th>
                                    <th>File Type</th>
                                    <th>Uploaded On</th>
                                    <th>Last Updated</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="documentsTableBody">
                            <?php
                                // Use the pmed documents table from pmed_db via the pmed DB connection ($conn2)
                                $rowsPerPage = 25;
                                $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                                $offset = ($page - 1) * $rowsPerPage;

                                $dbConn = $conn2; // pmed_db connection

                                $search_query = "SELECT * FROM pmed_documents WHERE 1=1";
                                if (isset($_GET['search_query']) && !empty($_GET['search_query'])) {
                                    $search_term = $dbConn->real_escape_string($_GET['search_query']);
                                    $search_query .= " AND (pmed_file_name LIKE '%$search_term%' 
                                                    OR pmed_author LIKE '%$search_term%' 
                                                    OR pmed_file_type LIKE '%$search_term%'
                                                    OR pmed_upload_date LIKE '%$search_term%'
                                                    OR pmed_ref_no LIKE '%$search_term%')";
                                    // keep logging on main connection
                                    logAction($conn, $_SESSION['user_id'] ?? 0, $_SESSION['username'] ?? '', "Searched documents: '$search_term'");
                                }

                                $search_query .= " ORDER BY pmed_upload_date DESC LIMIT $rowsPerPage OFFSET $offset";
                                $result = $dbConn->query($search_query);

                                $totalRowsQuery = "SELECT COUNT(*) as total FROM pmed_documents WHERE 1=1";
                                if (isset($_GET['search_query']) && !empty($_GET['search_query'])) {
                                    $totalRowsQuery .= " AND (pmed_file_name LIKE '%$search_term%' 
                                                    OR pmed_author LIKE '%$search_term%' 
                                                    OR pmed_file_type LIKE '%$search_term%'
                                                    OR pmed_upload_date LIKE '%$search_term%'
                                                    OR pmed_ref_no LIKE '%$search_term%')";
                                }
                                $totalRowsResult = $dbConn->query($totalRowsQuery);
                                $totalRows = $totalRowsResult->fetch_assoc()['total'];
                                $totalPages = ceil($totalRows / $rowsPerPage);

                                if ($result && $result->num_rows > 0) {
                                    while ($row = $result->fetch_assoc()) {
                                        echo "<tr>
                                        <td>{$row['pmed_ref_no']}</td>
                                        <td>{$row['pmed_file_name']}</td>
                                        <td>{$row['pmed_author']}</td>
                                        <td>{$row['pmed_file_type']}</td>
                                        <td>{$row['pmed_upload_date']}</td>
                                        <td>{$row['pmed_last_updated']}</td>
                                        <td>{$row['pmed_status']}</td>
                                        <td>
                                            <div class='action'>
                                                <div class='tooltip'>
                                                    <img src='../icons/action/view.svg' alt='Preview' class='icon-button'
                                                        onclick='openFileModal(\"" . addslashes($row['pmed_file_name']) . "\", \"" . addslashes($row['pmed_author']) . "\", \"" . addslashes($row['pmed_file_type']) . "\", \"" . addslashes($row['pmed_upload_date']) . "\", \"" . addslashes($row['pmed_last_updated']) . "\", \"" . addslashes($row['pmed_file_path']) . "\", \"" . $row['pmed_document_id'] . "\", \"" . addslashes($row['pmed_description']) . "\", \"" . $row['pmed_file_size'] . "\", \"" . addslashes($row['pmed_resolution']) . "\", \"" . $divisionId . "\", \"" . $row['pmed_ref_no'] . "\")'>
                                                    <span class='tooltip-text'>Preview</span>
                                                </div>
                                                <div class='tooltip'>
                                                    <img src='../icons/action/download.svg' alt='Download' class='icon-button'
                                                        onclick='window.location.href=\"../download.php?id={$row['pmed_document_id']}\"'>
                                                    <span class='tooltip-text'>Download</span>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>";
                                    }
                                } else {
                                    echo "<tr><td colspan='8'>No documents found</td></tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                            <a href="?division_id=<?= $divisionId ?>&page=1" class="pagination-button"><<</a>
                            <a href="?division_id=<?= $divisionId ?>&page=<?= $page - 1 ?>" class="pagination-button">Previous</a>
                        <?php endif; ?>

                        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                            <a href="?division_id=<?= $divisionId ?>&page=<?= $i ?>" class="pagination-button <?= $i == $page ? 'active' : '' ?>"><?= $i ?></a>
                        <?php endfor; ?>

                        <?php if ($page < $totalPages): ?>
                            <a href="?division_id=<?= $divisionId ?>&page=<?= $page + 1 ?>" class="pagination-button">Next</a>
                            <a href="?division_id=<?= $divisionId ?>&page=<?= $totalPages ?>" class="pagination-button">>></a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <div id="fileModal" class="modal-preview">
            <span class="close" onclick="closeFileModal()">&times;</span>
            <div class="modal-content-preview">
                <div id="previewArea" class="preview-area"></div>
                <div class="details-area">
                    <div>
                        <h3 id="fileTitle">File Title</h3>
                        <p><strong>Reference No.:</strong> <span id="ref_no"></span></p>
                        <p><strong>Author:</strong> <span id="preview_fileAuthor"></span></p>
                        <p><strong>File Type:</strong> <span id="file_type"></span></p>
                        <p><strong>Uploaded On:</strong> <span id="uploadDate"></span></p>
                        <p><strong>Last Updated:</strong> <span id="lastUpdated"></span></p>
                        <p><strong>File Size:</strong> <span id="fileSize"></span></p>
                        <p><strong>Resolution:</strong> <span id="fileResolution"></span></p>
                        <p><strong>Description:</strong> <span id="preview_fileDescription"></span></p>
                    </div>
                    <div>
                       <button id="modalDownloadBtn">Download</button>
                    </div>
                </div>
            </div>
        </div>

        <script src="preview.js"></script>

        <div id="composeMessageModal" class="modal">
            <div class="modal-content">
                <span class="close-btn" onclick="closeModal('composeMessageModal')">&times;</span>
                <h2>Compose Message</h2>
                <form id="composeMessageForm" method="post" action="../send_message.php" enctype="multipart/form-data">
                    <input type="hidden" id="composeMessageId" name="userId" value="<?= $_SESSION['user_id'] ?>">
                    <div class="input-message-field">
                        <textarea id="mainmessage" name="message" class="input-message-text" required></textarea>
                        <label class="label" for="mainmessage">Message</label>
                    </div>
                    <button type="submit" name="send_message">Send</button>
                </form>
            </div>
        </div>
    </div>
    <script>
        // Open Add File modal
        function openAddModal() {
            document.getElementById('addFileForm').reset();
            document.getElementById('addFileModal').style.display = 'block';
        }

        function closeAddModal() {
            document.getElementById('addFileModal').style.display = 'none';
        }

        // Optional: intercept submission to show simple feedback
        document.getElementById('addFileForm') && document.getElementById('addFileForm').addEventListener('submit', function(e) {
            // Let the default POST happen to ../functions.php which handles the upload.
            // You can add client-side validation here if needed.
            // Show a basic uploading message
            // (no AJAX here to keep server-side handling unchanged)
        });
        
        // Handle file input UI for the add file modal
        function handleFileUpload(input) {
            if (input && input.files && input.files[0]) {
                const fileName = input.files[0].name;
                const uploadedNameEl = document.getElementById('uploadedFileName');
                const uploadedSection = document.getElementById('uploadedFileSection');
                const fileUploadSection = document.getElementById('fileUploadSection');
                if (uploadedNameEl) uploadedNameEl.innerText = fileName;
                if (uploadedSection) uploadedSection.style.display = 'block';
                if (fileUploadSection) fileUploadSection.style.display = 'none';
            }
        }

        function removeUploadedFile() {
            const uploadedNameEl = document.getElementById('uploadedFileName');
            const uploadedSection = document.getElementById('uploadedFileSection');
            const fileUploadSection = document.getElementById('fileUploadSection');
            const fileInput = document.getElementById('fileInput');
            if (uploadedNameEl) uploadedNameEl.innerText = '';
            if (uploadedSection) uploadedSection.style.display = 'none';
            if (fileUploadSection) fileUploadSection.style.display = 'block';
            if (fileInput) fileInput.value = '';
        }
        function initializeDashboard() {
            brython();
            create_pie_chart();
        }

        // Sidebar toggle functionality
        document.getElementById('sidebarToggle').addEventListener('click', toggleFileStatistics);

        // Real-time search functionality
        document.getElementById("searchQuery").addEventListener("input", function () {
            const query = this.value;
            const divisionId = <?= $divisionId ?>;

            fetch(`fetch_documents.php?division_id=${divisionId}&search_query=${encodeURIComponent(query)}`)
                .then(response => response.text())
                .then(data => {
                    document.getElementById("documentsTableBody").innerHTML = data;
                })
                .catch(error => console.error('Error fetching search results:', error));
        });

        // Close sidebar automatically on small screens when clicking outside
        document.addEventListener('click', function(event) {
            const sidebar = document.getElementById('sidebar');
            const sidebarToggle = document.getElementById('sidebarToggle');
            
            if (window.innerWidth <= 768 && 
                !sidebar.contains(event.target) && 
                !sidebarToggle.contains(event.target)) {
                sidebar.classList.add('collapsed');
                document.querySelector('.main-layout').classList.add('sidebar-collapsed');
            }
        });

        // Function to update the current division name
        function updateCurrentDivisionName() {
            const divisionDropdown = document.getElementById("divisionDropdown");
            const currentDivisionName = divisionDropdown.options[divisionDropdown.selectedIndex].text;
            document.getElementById("currentDivisionName").innerText = currentDivisionName;
        }

        // Function to update file statistics
        function updateFileStatistics() {
            const divisionId = document.getElementById("divisionDropdown").value;
            fetch(`piechart.php?division_id=${divisionId}`)
                .then(response => response.text())
                .then(data => {
                    document.querySelector('.file-summary').innerHTML = data;
                    brython(); // Reinitialize Brython
                    create_pie_chart(); // Recreate the pie chart with new data
                });
        }

        // Call the functions on page load and when the division changes
        document.addEventListener('DOMContentLoaded', () => {
            updateCurrentDivisionName();
            updateFileStatistics();
        });
        document.getElementById("divisionDropdown").addEventListener('change', () => {
            updateCurrentDivisionName();
            updateFileStatistics();
        });

        function openComposeModal() {
            document.getElementById('composeMessageForm').reset();
            document.getElementById('composeMessageModal').style.display = 'block';
            <?php if (isset($_SESSION['user_id'])): ?>
                document.getElementById('composeMessageId').value = <?= $_SESSION['user_id'] ?>;
                <?php $_SESSION['sender_id'] = $_SESSION['user_id']; // Ensure sender_id is set ?>
            <?php endif; ?>
        }
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        function sendMessage(event) {
            event.preventDefault();
            const form = document.getElementById('composeMessageForm');
            const formData = new FormData(form);

            fetch('../send_message.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Message sent successfully');
                    closeModal('composeMessageModal');
                } else {
                    alert('Failed to send message: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while sending the message.');
            });
        }

        document.getElementById('composeMessageForm').addEventListener('submit', sendMessage);

        function performSearch(query) {
            const divisionId = <?= $divisionId ?>;
            const sortOrder = document.getElementById("sortOrder").value || 'asc';
            const fileType = document.getElementById("fileType").value || '';

            const xhr = new XMLHttpRequest();
            xhr.open("GET", `fetch_documents.php?division_id=${divisionId}&search_query=${encodeURIComponent(query)}&sort=${sortOrder}&file_type=${fileType}`, true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById("documentsTableBody").innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        }

        function applyFilters() {
            const divisionId = <?= $divisionId ?>;
            const sortOrder = document.getElementById("sortOrder").value || 'asc';
            const fileType = document.getElementById("fileType").value || '';

            const xhr = new XMLHttpRequest();
            xhr.open("GET", `fetch_documents.php?division_id=${divisionId}&sort=${sortOrder}&file_type=${fileType}`, true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById("documentsTableBody").innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        }

        function setSortOrder(order) {
            document.getElementById("sortOrder").value = order;
            applyFilters();
        }

        function setFileType(type) {
            document.getElementById("fileType").value = type;
            applyFilters();
        }

        function clearFilters() {
            document.getElementById("sortOrder").value = "asc";
            document.getElementById("fileType").value = "";
            applyFilters();
        }

        document.getElementById("searchQuery").addEventListener("keyup", function () {
            performSearch(this.value);
        });
    </script>

    <style>
    /* Make JS-controlled dropdowns visible when .open is set */
    .dropdown.open .dropdown-content { display: block !important; }
    </style>

    <script>
    // Ensure dropdowns open on click (more reliable than :hover, works on touch)
    (function(){
        function closeAllDropdowns() {
            document.querySelectorAll('.dropdown.open').forEach(d => d.classList.remove('open'));
        }

        function setupDropdowns() {
            document.querySelectorAll('.dropdown').forEach(d => {
                const btn = d.querySelector('button, .dropbtn');
                if (!btn) return;
                btn.addEventListener('click', function(ev){
                    ev.stopPropagation();
                    // toggle only this dropdown, close others
                    const isOpen = d.classList.contains('open');
                    closeAllDropdowns();
                    if (!isOpen) d.classList.add('open');
                });
            });

            // close when clicking outside
            document.addEventListener('click', function(){ closeAllDropdowns(); });
            // close on ESC
            document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closeAllDropdowns(); });
        }

        // init on DOM ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', setupDropdowns);
        } else {
            setupDropdowns();
        }
    })();
    </script>

    <script>
    // Delegated handler for dropdown option clicks (users page)
    document.addEventListener('click', function (ev) {
        var target = ev.target;
        while (target && target !== document) {
            if (target.matches && target.matches('a[data-action]')) break;
            target = target.parentNode;
        }
        if (!target || target === document) return;
        ev.preventDefault();
        ev.stopPropagation();
        var action = target.getAttribute('data-action');
        var value = target.getAttribute('data-value');
        if (action === 'sort' && typeof setSortOrder === 'function') {
            setSortOrder(value);
        } else if (action === 'file_type' && typeof setFileType === 'function') {
            setFileType(value);
        }
        document.querySelectorAll('.dropdown.open').forEach(d => d.classList.remove('open'));
    }, true);
    </script>

<!-- <div id="fut" class="container-fluid">
    <div class="row">
        <div class="col-md-5 f1">
          <img src="../icons/serbisyong_tama.png">
        </div>
        <div class="col-md-3 f3">
          <h5>Follow us on</h5>
          <ul>
                <a taget="_blank" title="Provincial Government of Laguna in Facebook" href="https://www.facebook.com/govramil">
                  <img src="../icons/facebook.png" alt="Facebook" height="35px">
                </a>
                <a taget="_blank" title="Provincial Government of Laguna in twitter" href="https://www.twitter.com/govramil">
                  <img src="../icons/twitter.png" alt="Twitter" height="35px">
                </a>
                <a taget="_blank" title="Provincial Government of Laguna in Instagram" href="https://www.instagram.com/govramil">
                  <img src="../icons/instagram.png" alt="Instagram" height="35px">
                </a>
                <a taget="_blank" title="Provincial Government of Laguna in Youtube" href="https://www.youtube.com/govramil">
                  <img src="../icons/youtube.png" alt="Youtube" height="35px">
                </a>
              </ul>
        </div>
    </div>
  </div>
    -->
    <footer>
        <p>&copy; <?php echo date("Y"); ?> PPDCO. All rights reserved.</p>
    </footer>
    <style>
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }

        .pagination-button {
            margin: 0 5px;
            padding: 5px 10px;
            text-decoration: none;
            color: #b10000;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .pagination-button.active {
            background-color: #b10000;
            color: white;
            border-color: #b10000;
        }

        .pagination-button:hover {
            background-color: #cb0000ff;
            color: white;
        }
    </style>
</body>
</html>