<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
include 'functions.php';

// Check if user is logged in and is an admin
if (!isset($_SESSION['username']) || $_SESSION['user_type'] !== 'admin') {
    header("Location: index.php");
    exit();
}


// Ensure $divisionId is defined (used in links and JS). Prefer request, then session, default to 1.
$divisionId = isset($_GET['division_id'])
    ? (int)$_GET['division_id']
    : (isset($_SESSION['division_id']) ? (int)$_SESSION['division_id'] : 1);


// Get username from session
$username = $_SESSION['username'];

// Ensure sender_id session is set for admin (used by send_message.php)
if (isset($_SESSION['user_id'])) {
    $_SESSION['sender_id'] = $_SESSION['user_id'];
}

$current_page = basename($_SERVER['PHP_SELF']);

// Pagination logic
$rowsPerPage = 25;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $rowsPerPage;

// Define field names for the pmed_documents table
$documentIdField = 'pmed_document_id';
$refNoField = 'pmed_ref_no';
$fileNameField = 'pmed_file_name';
$authorField = 'pmed_author';
$fileTypeField = 'pmed_file_type';
$uploadDateField = 'pmed_upload_date';
$lastUpdatedField = 'pmed_last_updated';
$statusField = 'pmed_status';
$filePathField = 'pmed_file_path';
$descriptionField = 'pmed_description';
$fileSizeField = 'pmed_file_size';
$resolutionField = 'pmed_resolution';

// Prefer the pmed DB connection ($conn2) for document queries; fall back to main $conn
$db = isset($conn2) ? $conn2 : $conn;

// Ensure $search_query is initialized properly
$search_query = "SELECT * FROM pmed_documents WHERE 1=1";

// Apply search filters if provided
if (isset($_GET['search_query']) && !empty($_GET['search_query'])) {
    $search_term = $db->real_escape_string($_GET['search_query']);
    $search_query .= " AND ($fileNameField LIKE '%$search_term%' 
                    OR $authorField LIKE '%$search_term%' 
                    OR $fileTypeField LIKE '%$search_term%'
                    OR $uploadDateField LIKE '%$search_term%'
                    OR $refNoField LIKE '%$search_term%')";
    // keep audit logging on the main connection
    logAction(isset($conn) ? $conn : $db, $_SESSION['user_id'] ?? 0, $username, "Searched documents: '$search_term'");
}

// Add LIMIT and OFFSET to the query
$search_query .= " ORDER BY $uploadDateField DESC LIMIT $rowsPerPage OFFSET $offset";

// Execute the query on the selected DB connection ($db)
$result = $db->query($search_query);
if (!$result) {
    die("Error executing query: " . $db->error);
}

// Fetch total number of rows for pagination
$totalRowsQuery = "SELECT COUNT(*) as total FROM pmed_documents WHERE 1=1";
if (isset($_GET['search_query']) && !empty($_GET['search_query'])) {
    $search_term_for_count = $db->real_escape_string($_GET['search_query']);
    // match the same fields used by the main search query
    $totalRowsQuery .= " AND ($fileNameField LIKE '%$search_term_for_count%' 
            OR $authorField LIKE '%$search_term_for_count%' 
            OR $fileTypeField LIKE '%$search_term_for_count%'
            OR $uploadDateField LIKE '%$search_term_for_count%'
            OR $refNoField LIKE '%$search_term_for_count%')";
}
$totalRowsResult = $db->query($totalRowsQuery);
if (!$totalRowsResult) {
    die("Error executing total rows query: " . $db->error);
}
$totalRows = $totalRowsResult->fetch_assoc()['total'];
$totalPages = ceil($totalRows / $rowsPerPage);

// Get filter/search params for pagination links
$search_query_param = isset($_GET['search_query']) ? '&search_query=' . urlencode($_GET['search_query']) : '';
$sort_param = isset($_GET['sort']) ? '&sort=' . urlencode($_GET['sort']) : '';
$file_type_param = isset($_GET['file_type']) ? '&file_type=' . urlencode($_GET['file_type']) : '';

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PMED - Admin Panel</title>
    <link rel="icon" href="../../../../Users/PPCDO/Downloads/favicon_io/favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="../../../../Users/PPCDO/Downloads/css/admin_dashboard.css">
    <link rel="stylesheet" href="../../../../Users/PPCDO/Downloads/css/preview.css">
    <link rel="stylesheet" href="../../../../Users/PPCDO/Downloads/css/user_modal.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <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="../../../../Users/PPCDO/Downloads/preview.js"></script>
    <style type="text/css">
<!--
.style1 {color: #FFFFFF}
-->
    </style>
</head>
<body>
    <script>
    // Ensure sidebar is initially toggled open (visible)
    document.addEventListener('DOMContentLoaded', function() {
        const sidebar = document.getElementById('sidebar');
        if (sidebar) sidebar.classList.remove('hidden');
        const sectionContent = document.querySelector('.section-content');
        if (sectionContent) sectionContent.classList.remove('expanded');
    });
    </script>
    
    <style>
    /* Make JS-controlled dropdowns visible when .open is set */
    .dropdown.open .dropdown-content { display: block !important; }
    /* Ensure dropdown overlays are clickable above surrounding content */
    .dropdown { position: relative; }
    .dropdown .dropdown-content {
        position: absolute;
        z-index: 9999; /* raise above modals/containers */
        top: calc(100% + 6px);
        left: 0;
    }
    </style>
    
    <script>
    // Dropdown click/tap helper (works on touch devices and prevents hover-only issues)
    (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();
                    const isOpen = d.classList.contains('open');
                    closeAllDropdowns();
                    if (!isOpen) d.classList.add('open');
                });
            });

            document.addEventListener('click', function(){ closeAllDropdowns(); });
            document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closeAllDropdowns(); });
        }

        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', setupDropdowns);
        } else {
            setupDropdowns();
        }
    })();
    </script>
    <script>
    // Ensure clicks on dropdown menu items don't navigate to '#' and don't immediately close before handlers run
    document.addEventListener('click', function(ev) {
        var el = ev.target;
        // climb to anchor inside dropdown-content
        while (el && el !== document) {
            if (el.matches && el.matches('.dropdown .dropdown-content a')) break;
            el = el.parentNode;
        }
        if (!el || el === document) return;
        ev.preventDefault();
        ev.stopPropagation();
        // Allow inline onclick handlers to run manually when present
        var handler = el.getAttribute('onclick');
        if (handler) {
            try { new Function(handler).call(el); } catch (e) { /* no-op */ }
        }
        // Close menus after selection
        document.querySelectorAll('.dropdown.open').forEach(function(d){ d.classList.remove('open'); });
    }, true);
    </script>
    <script>
    // Delegated handler for dropdown option clicks using data-action/data-value
    document.addEventListener('click', function (ev) {
        var target = ev.target;
        // climb up to anchor if inner element clicked
        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);
        }
        // close dropdowns after selection
        document.querySelectorAll('.dropdown.open').forEach(d => d.classList.remove('open'));
    }, true);
    </script>
    <div class="navbar">
        <div class="navbar-center">
            <img src="../../../../Users/PPCDO/Downloads/icons/ppdco_logo_icon.webp" alt="PPDCO Logo" class="navbar-logo">
            <img src="../../../../Users/PPCDO/Downloads/icons/seal_laguna.webp" alt="Laguna Seal" class="navbar-logo">
            <img src="../../../../Users/PPCDO/Downloads/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="../../../../Users/PPCDO/Downloads/admin_dashboard.php" class="nav-link" data-section="divisions">
                            <img src="../../../../Users/PPCDO/Downloads/icons/navigator/divisions.svg" alt="Divisions" class="nav-icon">
                            <span class="nav-text">DOCUMENTS</span>
                        </a>
                    </li>
                    <li>
                        <a href="../../../../Users/PPCDO/Downloads/admin_bulletin.php" class="nav-link" data-section="manageDivisions">
                            <img src="../../../../Users/PPCDO/Downloads/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="../../../../Users/PPCDO/Downloads/icons/action/compose.svg" alt="Manage" class="nav-icon">
                            <span class="nav-text">COMPOSE</span>
                        </a>
                    </li>
                    <li>
                        <a href="../../../../Users/PPCDO/Downloads/logout.php" class="nav-link">
                            <img src="../../../../Users/PPCDO/Downloads/icons/navigator/logout.svg" alt="Logout" class="nav-icon">
                            <span class="nav-text">LOG OUT</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    </div>

    <div class="dashboard-container">
        <div class="section-header">
            <button id="sidebarToggle" class="sidebar-toggle">
                <img src="../../../../Users/PPCDO/Downloads/icons/navigator/piechart.svg" alt="Toggle Sidebar">
            </button>
            <p>PPDCO - PROJECT MONITORING AND EVALUATION DIVISION - ADMIN PANEL</p>
        </div>
        <div class="section-content">
            <div class="sidebar" id="sidebar">
                <div class="statistics-section">
                    <?php include "piechart.php" ?>
                </div>
            <div class="container">
                <div class="filter-group">
                    <div class="action-buttons">
                        <div class="search-bar">
                            <form method="GET" class="search-form" onSubmit="return false;">
                                <span class="search">
                                    <img src="../../../../Users/PPCDO/Downloads/icons/action/search.svg" alt="Search">
                                </span>
                                <input type="text" id="searchQuery" name="search_query" placeholder="Search documents..." onKeyUp="performSearch(this.value)">
                            </form>
                        </div>

                        <button class="add-button" onClick="openModal()">
                            <img src='../../../../Users/PPCDO/Downloads/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 type="button" class="filter-button" id="sortButton">
                                <img src="../../../../Users/PPCDO/Downloads/icons/action/sort.svg" alt="Sort" class="add-icon" id="sortIcon">Sequence
                            </button>
                            <div class="dropdown-content">
                                <a href="#" onClick="setSortOrder('asc')">Filename: A-Z</a>
                                <a href="#" onClick="setSortOrder('desc')">Filename: Z-A</a>
                                <a href="#" onClick="setSortOrder('date_asc')">Date Uploaded: Ascending</a>
                                <a href="#" onClick="setSortOrder('date_desc')">Date Uploaded: Descending</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button type="button" class="filter-button">
                                <img src="../../../../Users/PPCDO/Downloads/icons/action/file-solid.svg" alt="Filter" class="add-icon">File Type
                            </button>
                            <div class="dropdown-content">
                                <a href="#" onClick="setFileType('doc,docx')">Word Documents (doc, docx)</a>
                                <a href="#" onClick="setFileType('xls,xlsx')">Excel Files (xls, xlsx)</a>
                                <a href="#" onClick="setFileType('ppt,pptx')">PowerPoint Files (ppt, pptx)</a>
                                <a href="#" onClick="setFileType('pdf')">PDF Files (pdf)</a>
                                <a href="#" onClick="setFileType('jpg,jpeg,png,gif,bmp,ico,webp,tiff,tif,psd,raw,heif,svg,svgz,ai,eps,ps,cdr,wmf,emf')">Images (jpg, jpeg, png, gif, bmp, etc.)</a>
                                <a href="#" onClick="setFileType('mp4,m4p,m4v,mpg,mp2,mpeg,mpe,mpv,svi,3gp,3g2,mxf,roq,nsv,flv,f4v,f4p,f4a,f4b,mod,webm,mkv,vob,ogv,mov,avi,qt,wmv,yuv,rm,asf,amv')">Videos (mp4, avi, mkv, etc.)</a>
                                <a href="#" onClick="setFileType('mp3,aac,wav,aiff,pcm,flac,alac,wma,ogg,oga,dsd,m4a,m4b,m4p,m4r,3ga,mid,midi,xmf,rtttl,rtx,ota,imy,spx,opus')">Audio (mp3, wav, flac, etc.)</a>
                                <a href="#" onClick="setFileType('h,H,html,php,js,css,sql,py,csv,cxx,CXX,CPP,c')">Code Files (html, php, js, etc.)</a>
                                <a href="#" onClick="setFileType('zip,rar,7z,tar,gz,bz2,xz,z,Z,taz,tgz,tbz,tbz2,txz,tlz,zipx,sit,sitx,ace,arj,cab,deb')">Compressed Files (zip, rar, 7z, etc.)</a>
                                <a href="#" onClick="setFileType('other')">Other Files</a>
                            </div>
                        </div>
                        <button class="filter-button" onClick="clearFilters()">
                            <img src="../../../../Users/PPCDO/Downloads/icons/action/refresh.svg" alt="Clear" class="add-icon">Clear Filters
                        </button>
                    </div>
                    <div class="table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th>Ref No</th>
                                    <th>File Name</th>
                                    <th>Author</th>
                                    <th>Type</th>
                                    <th>Date</th>
                                    <th>Updated</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="documentsTableBody">
                            <?php
                                // Define field names for the current division
                                $documentIdField = 'pmed_document_id';
                                $refNoField = 'pmed_ref_no';
                                $fileNameField = 'pmed_file_name';
                                $authorField = 'pmed_author';
                                $fileTypeField = 'pmed_file_type';
                                $uploadDateField = 'pmed_upload_date';
                                $lastUpdatedField = 'pmed_last_updated';
                                $statusField = 'pmed_status';
                                $filePathField = 'pmed_file_path';
                                $descriptionField = 'pmed_description';
                                $fileSizeField = 'pmed_file_size';
                                $resolutionField = 'pmed_resolution';

                                if ($table && $divisionConn) {
                                    $search_query = "SELECT * FROM $table WHERE 1=1";
                                    if (isset($_GET['search_query']) && !empty($_GET['search_query'])) {
                                        $search_term = $divisionConn->real_escape_string($_GET['search_query']);
                                        $search_query .= " AND ($fileNameField LIKE '%$search_term%' 
                                                        OR $authorField LIKE '%$search_term%' 
                                                        OR $fileTypeField LIKE '%$search_term%'
                                                        OR $uploadDateField LIKE '%$search_term%'
                                                        OR $refNoField LIKE '%$search_term%')";
                                        // Use the main connection for audit logging
                                        require_once '../db_connect/main_db_connection.php';
                                        logAction($conn, $_SESSION['user_id'], $username, "Searched documents: '$search_term'");
                                    }

                                    $search_query .= " LIMIT $rowsPerPage OFFSET $offset";
                                    $result = $divisionConn->query($search_query);

                                    $totalRowsQuery = "SELECT COUNT(*) as total FROM $table WHERE 1=1";
                                    if (isset($_GET['search_query']) && !empty($_GET['search_query'])) {
                                        $search_term_for_count = $divisionConn->real_escape_string($_GET['search_query']);
                                        $totalRowsQuery .= " AND ($fileNameField LIKE '%$search_term_for_count%' 
                                                        OR $authorField LIKE '%$search_term_for_count%' 
                                                        OR $fileTypeField LIKE '%$search_term_for_count%'
                                                        OR $uploadDateField LIKE '%$search_term_for_count%'
                                                        OR $refNoField LIKE '%$search_term_for_count%')";
                                    }
                                    $totalRowsResult = $divisionConn->query($totalRowsQuery);
                                    $totalRows = $totalRowsResult->fetch_assoc()['total'];
                                    $totalPages = ceil($totalRows / $rowsPerPage);

                                    if ($result->num_rows > 0) {
                                        while ($row = $result->fetch_assoc()) {
                                            $fileType = $row[$fileTypeField];
                                            $iconPath = "/icons/$fileType.png";
                                            if (!file_exists($iconPath)) {
                                                $iconPath = "icons/others.png";
                                            }
                                            echo "<tr>
                                                <td>{$row[$refNoField]}</td>
                                                <td>{$row[$fileNameField]}</td>
                                                <td>{$row[$authorField]}</td>
                                                <td>{$row[$fileTypeField]}</td>
                                                <td>{$row[$uploadDateField]}</td>
                                                <td>{$row[$lastUpdatedField]}</td>
                                                <td>{$row[$statusField]}</td>
                                                <td>
                                                    <div class='action'>
                                                        <div class='tooltip'>
                                                            <img src='icons/action/view.svg' alt='Preview' class='icon-button' onclick=\"openFileModal('" . addslashes($row[$fileNameField]) . "', '" . addslashes($row[$authorField]) . "', '" . addslashes($row[$fileTypeField]) . "', '" . addslashes($row[$uploadDateField]) . "', '" . addslashes($row[$lastUpdatedField]) . "', '" . addslashes($row[$filePathField]) . "', '{$row[$documentIdField]}', '" . addslashes($row[$descriptionField]) . "', '{$row[$fileSizeField]}', '" . addslashes($row[$resolutionField]) . "', '{$row[$refNoField]}', '{$divisionId}')\">
                                                            <span class='tooltip-text'>Preview</span>
                                                        </div>
                                                        <div class='tooltip'>
                                                            <img src='icons/action/edit.svg' alt='Edit' class='icon-button' onclick=\"openEditModal('{$row[$documentIdField]}', '" . htmlspecialchars($row[$fileNameField], ENT_QUOTES) . "', '" . htmlspecialchars($row[$authorField], ENT_QUOTES) . "', '" . htmlspecialchars($row[$descriptionField], ENT_QUOTES) . "', '{$row[$fileSizeField]}', '{$row[$resolutionField]}', '{$row[$filePathField]}', '{$row[$statusField]}', '{$row[$refNoField]}', '{$divisionId}')\">
                                                            <span class='tooltip-text'>Edit File</span>
                                                        </div>
                                                        <div class='tooltip'>
                                                            <img src='icons/action/paper_plane.svg' alt='email' class='icon-button' onclick=\"openEmailModalFromTable('{$row[$documentIdField]}', '" . addslashes($row[$fileNameField]) . "', '{$divisionId}')\">
                                                            <span class='tooltip-text'>Send Via Email</span>
                                                        </div>
                                                        <div class='tooltip'>
                                                            <img src='icons/action/download.svg' alt='Download' class='icon-button' onclick=\"window.location.href='download.php?id={$row[$documentIdField]}&division_id={$divisionId}'\">
                                                            <span class='tooltip-text'>Download</span>
                                                        </div>
                                                        <div class='tooltip'>
                                                            <img src='icons/action/delete.svg' alt='Delete' class='icon-button' onclick=\"confirmDelete('{$row[$documentIdField]}', '{$divisionId}')\">
                                                            <span class='tooltip-text'>Delete</span>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>";
                                        }
                                    } else {
                                        echo "<tr><td colspan='8'>No documents found</td></tr>";
                                    }
                                } else {
                                    echo "<tr><td colspan='8'>No documents found</td></tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination Controls -->
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                            <a href="../../../../Users/PPCDO/Downloads/?page=1<?= $search_query_param . $sort_param . $file_type_param ?>" class="pagination-button"><<</a>
                            <a href="../../../../Users/PPCDO/Downloads/?page=<?= $page - 1 ?><?= $search_query_param . $sort_param . $file_type_param ?>" class="pagination-button">Previous</a>
                        <?php endif; ?>

                        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                            <a href="../../../../Users/PPCDO/Downloads/?page=<?= $i ?><?= $search_query_param . $sort_param . $file_type_param ?>" class="pagination-button <?= $i == $page ? 'active' : '' ?>"><?= $i ?></a>
                        <?php endfor; ?>

                        <?php if ($page < $totalPages): ?>
                            <a href="../../../../Users/PPCDO/Downloads/?page=<?= $page + 1 ?><?= $search_query_param . $sort_param . $file_type_param ?>" class="pagination-button">Next</a>
                            <a href="../../../../Users/PPCDO/Downloads/?page=<?= $totalPages ?><?= $search_query_param . $sort_param . $file_type_param ?>" class="pagination-button">>></a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
                        </div>

        <!-- File Preview Modal -->
        <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="fileRefNo"></span></p>
                        <p><strong>Author:</strong> <span id="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="fileDescription"></span></p>
                    </div>
                    <div>
                        <button id="modalDownloadBtn">Download</button>
                        <button id="modalEmailBtn">
                            <img src="../../../../Users/PPCDO/Downloads/icons/action/paper_plane.svg" alt="Send via Email" style="height:20px;vertical-align:middle;">
                            Send via Email
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Email Modal -->
        <div id="emailModal" class="modal" style="display:none;">
            <div class="modal-content email-modal-content">
                <span class="close-btn" onClick="closeEmailModal()">&times;</span>
                <h2>Send File via Email</h2>
                <form id="emailForm">
                    <div class="coolinput">
                        <label for="recipientEmail" class="text">Recipient Email:</label>
                        <input type="email" id="recipientEmail" name="recipient" class="input" required placeholder="Write here...">
                    </div>
                    <div class="coolinput">
                        <label for="emailSubject" class="text">Subject:</label>
                        <input type="text" id="emailSubject" name="subject" class="input" required placeholder="Write here..." value="Document from PPDCO">
                    </div>
                    <div class="coolinput">
                        <label for="emailMessage" class="text">Message:</label>
                        <textarea id="emailMessage" name="message" class="input" rows="4" placeholder="Write here... (optional)"></textarea>
                    </div>
                    <div class="coolinput">
                        <label for="attachedFileName" class="text">Attached File:</label>
                        <input type="text" id="attachedFileName" class="input" readonly style="background:#f5f5f5; color:#333;">
                    </div>
                    <button type="submit" class="save-button">Send Email</button>
                </form>
            </div>
        </div>

        <!-- Document Modal -->
        <div id="documentModal" class="modal">
            <div class="modal-content">
                <span class="close-btn" onClick="closeModal()">&times;</span>
                <h2 id="modalTitle">Add/Edit Document</h2>
                <form id="documentForm" method="post" 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">
                        <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)">
                    </label>
                    <button class="save-button" type="submit" name="add_document">
                        Save Document
                    </button>
                </form>
            </div>
        </div>
    </div>

    <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="../../../../Users/PPCDO/Downloads/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>

    <!-- Upload Progress Modal -->
    <div id="uploadModal" style="display:none; position:fixed; bottom:20px; right:20px; background:#222; color:#fff; padding:20px; border-radius:10px; z-index:9999; min-width:300px; box-shadow:0 2px 10px #0008;">
        <div id="uploadStatus">Uploading...</div>
        <div style="background:#444; border-radius:5px; margin-top:10px;">
            <div id="uploadProgressBar" style="height:10px; width:0%; background:#4caf50; border-radius:5px; transition:width 0.2s;"></div>
        </div>
        <div id="uploadFileName" style="margin-top:10px; font-size:0.95em;"></div>
        <button id="uploadCancelBtn" style="margin-top:10px; display:none; background:#dc3545; color:#fff; border:none; border-radius:5px; padding:5px 10px; cursor:pointer;">Cancel</button>
    </div>

    <script>
        // Function to load documents table on page load (uses fetch_documents.php)
        function loadDocumentsTable(page = 1) {
            const sortOrder = document.getElementById("sortOrder").value || 'asc';
            const fileType = document.getElementById("fileType").value || '';
            const searchQuery = document.getElementById('searchQuery').value || '';
            const params = new URLSearchParams({ division_id: divisionId, sort: sortOrder, file_type: fileType, search_query: searchQuery, page: page });
            const xhr = new XMLHttpRequest();
            xhr.open("GET", `fetch_documents.php?${params.toString()}`, true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById("documentsTableBody").innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        }

        // Function to close the file preview modal
        function closeFileModal() {
            document.getElementById('fileModal').style.display = "none";
        }

        // Function to toggle the file statistics section
        function toggleFileStatistics() {
            const sidebar = document.getElementById('sidebar');
            const sectionContent = document.querySelector('.section-content');
            sidebar.classList.toggle('hidden');
            sectionContent.classList.toggle('expanded');
            // Notify any embedded scripts (Brython) that the sidebar visibility changed
            const event = new CustomEvent('sidebarToggled', { detail: { visible: !sidebar.classList.contains('hidden') } });
            window.dispatchEvent(event);
        }

        // Add event listener to the "Add File" button
        document.addEventListener('DOMContentLoaded', function() {
            // Load documents table on page load
            // expose divisionId from server-side if available
            var divisionId = <?= isset($divisionId) ? (int)$divisionId : 1 ?>;
            // make divisionId global for other functions
            window.divisionId = divisionId;
            loadDocumentsTable();

            const addButton = document.querySelector('.add-button');
            if (addButton) {
                addButton.addEventListener('click', openModal);
            }

            // Add event listener to the sidebar toggle button
            document.getElementById('sidebarToggle').addEventListener('click', toggleFileStatistics);

            // Add event listener to the clear all button
            const clearAllButton = document.querySelector('.clear-all-btn');
            if (clearAllButton) {
                clearAllButton.addEventListener('click', openClearAllModal);
            }

            // Initialize Brython (pie chart will initialize itself)
            brython();
        });

        function confirmDelete(documentId) {
            if (confirm('Are you sure you want to delete this file?')) {
                window.location.href = 'admin_dashboard.php?delete_id=' + documentId;
            }
        }

        // Open the clear all modal
        function openClearAllModal() {
            document.getElementById("clearAllModal").style.display = "block";
        }

        // Close the clear all modal
        function closeClearAllModal() {
            document.getElementById("clearAllModal").style.display = "none";
        }

        // Function to open the "Add File" modal
        function openModal() {
            document.getElementById("modalTitle").innerText = "Add Document";
            document.getElementById("documentForm").reset();
            document.getElementById("documentId").value = "";
            document.getElementById("documentModal").style.display = "block";
        }

        // Function to close modals. Accepts optional modalId. If no id provided,
        // it will try to close the add/edit document modal and common compose modal.
        function closeModal(modalId) {
            try {
                if (!modalId) {
                    // Close commonly used modals when no id is provided
                    const docModal = document.getElementById('documentModal');
                    if (docModal) docModal.style.display = 'none';
                    const addFileModal = document.getElementById('addFileModal');
                    if (addFileModal) addFileModal.style.display = 'none';
                    const composeModal = document.getElementById('composeMessageModal');
                    if (composeModal) composeModal.style.display = 'none';
                    return;
                }

                const el = document.getElementById(modalId);
                if (el) el.style.display = 'none';
            } catch (err) {
                // Fail silently but keep a debug log when available
                if (window.console && console.error) console.error('closeModal error:', err);
            }
        }

        // Function to properly decode special characters
        function decodeSpecialChars(str) {
            return str.replace(/\\'/g, "'")
                     .replace(/\\"/g, '"')
                     .replace(/\\\\/g, '\\');
        }

        // Function to open the edit modal with proper character handling
        function openEditModal(documentId, fileName, fileAuthor, description, fileSize, resolution, filePath, status, refNo) {
            // Decode special characters
            fileName = decodeSpecialChars(fileName);
            fileAuthor = decodeSpecialChars(fileAuthor);
            description = decodeSpecialChars(description);

            document.getElementById("modalTitle").innerText = "Edit Document";
            document.getElementById("documentForm").reset();
            document.getElementById("documentId").value = documentId;
            document.getElementById("fileName").value = fileName;
            document.getElementById("fileAuthor").value = fileAuthor;
            document.getElementById("fileDescription").value = description;
            document.getElementById("fileStatus").value = status;
            document.getElementById("refNo").value = refNo;

            // Show existing file details
            const existingFileSection = document.getElementById("existingFileSection");
            const fileUploadSection = document.getElementById("fileUploadSection");
            if (filePath) {
                existingFileSection.style.display = "block";
                existingFileSection.innerHTML = `<a href="${filePath}" target="_blank">${fileName}</a>`;
                fileUploadSection.style.display = "none";
            } else {
                existingFileSection.style.display = "none";
                fileUploadSection.style.display = "block";
            }

            document.getElementById("documentModal").style.display = "block";
        }

        function handleFileUpload(input) {
            if (input.files && input.files[0]) {
                const fileName = input.files[0].name;
                document.getElementById("uploadedFileName").innerText = fileName;
                document.getElementById("uploadedFileSection").style.display = "block";
                document.getElementById("fileUploadSection").style.display = "none";
            }
        }

        function removeUploadedFile() {
            document.getElementById("uploadedFileName").innerText = "";
            document.getElementById("uploadedFileSection").style.display = "none";
            document.getElementById("fileUploadSection").style.display = "block";
            document.getElementById("fileInput").value = "";
        }

        // AJAX file upload with progress bar modal
        (function() {
            const form = document.getElementById('documentForm');
            if (!form) return;

            let xhr = null;

            form.onsubmit = function(e) {
                e.preventDefault();

                const fileInput = form.fileInput;
                if (!fileInput || !fileInput.files.length) {
                    form.submit();
                    return;
                }

                const formData = new FormData(form);

                // Show modal
                const modal = document.getElementById('uploadModal');
                const status = document.getElementById('uploadStatus');
                const bar = document.getElementById('uploadProgressBar');
                const fileName = document.getElementById('uploadFileName');
                const cancelBtn = document.getElementById('uploadCancelBtn');
                modal.style.display = 'block';
                status.innerText = 'Uploading...';
                bar.style.width = '0%';
                fileName.innerText = fileInput.files[0].name;
                cancelBtn.style.display = 'inline-block';

                xhr = new XMLHttpRequest();
                xhr.open('POST', form.action || window.location.href, true);

                xhr.upload.onprogress = function(e) {
                    if (e.lengthComputable) {
                        const percent = Math.round((e.loaded / e.total) * 100);
                        bar.style.width = percent + '%';
                        status.innerText = 'Uploading... ' + percent + '%';
                    }
                };

                xhr.onload = function() {
                    if (xhr.status == 200) {
                        status.innerText = 'Upload complete!';
                        bar.style.width = '100%';
                        cancelBtn.style.display = 'none';
                        setTimeout(() => {
                            modal.style.display = 'none';
                            window.location.reload();
                        }, 1000);
                    } else {
                        status.innerText = 'Upload failed!';
                        cancelBtn.style.display = 'none';
                    }
                };

                xhr.onerror = function() {
                    status.innerText = 'Upload error!';
                    cancelBtn.style.display = 'none';
                };

                cancelBtn.onclick = function() {
                    if (xhr) xhr.abort();
                    status.innerText = 'Upload cancelled!';
                    bar.style.width = '0%';
                    cancelBtn.style.display = 'none';
                    setTimeout(() => { modal.style.display = 'none'; }, 1000);
                };

                xhr.send(formData);
            };
        })();

        // Email functionality
        window.currentDocumentId = null;
        window.currentFileName = null;

        document.getElementById('modalEmailBtn').onclick = function() {
            openEmailModal();
        };

        function openEmailModal() {
            document.getElementById('emailModal').style.display = 'block';
            document.getElementById('attachedFileName').value = window.currentFileName || '';
        }

        function openEmailModalFromTable(documentId, fileName) {
            window.currentDocumentId = documentId;
            window.currentFileName = fileName;
            
            document.getElementById('emailModal').style.display = 'block';
            document.getElementById('attachedFileName').value = fileName || '';
        }

        function closeEmailModal() {
            document.getElementById('emailModal').style.display = 'none';
        }

        // Open compose message modal (admin)
        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; ?>
        }
        // NOTE: closeModal implementation is defined earlier to avoid duplicate definitions.

        document.getElementById('emailForm').onsubmit = function(e) {
            e.preventDefault();
            const recipient = document.getElementById('recipientEmail').value;
            const subject = document.getElementById('emailSubject').value;
            const message = document.getElementById('emailMessage').value;
            const documentId = window.currentDocumentId;

            fetch('send_file_email.php', {
                method: 'POST',
                body: new URLSearchParams({
                    document_id: documentId,
                    recipient: recipient,
                    subject: subject,
                    message: message
                })
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert('Email sent successfully!');
                    closeEmailModal();
                } else {
                    alert('Failed to send email: ' + data.error);
                }
            });
        };

        // Compose message form handler (AJAX) - posts to root send_message.php
        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) {
                    showToast('Message sent successfully', 'success');
                    closeModal('composeMessageModal');
                } else {
                    showToast('Failed to send message: ' + (data.error || 'Unknown'), 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred while sending the message.', 'error');
            });
        }

        // Debounced search helper
            let _searchTimeout = null;
            function performSearch(value) {
                if (_searchTimeout) clearTimeout(_searchTimeout);
                _searchTimeout = setTimeout(() => {
                    loadDocumentsTable(1);
                }, 300);
            }

            // Function to apply filters dynamically (uses unified loader)
            function applyFilters(page = 1) {
                loadDocumentsTable(page);
            }

            // Function to set sort order and apply filters
            function setSortOrder(order) {
                document.getElementById("sortOrder").value = order;

                // Update the sort icon dynamically
                const sortIcon = document.getElementById("sortIcon");
                if (order === "asc" || order === "date_asc") {
                    sortIcon.src = 'icons/action/sort-up.svg';
                } else if (order === "desc" || order === "date_desc") {
                    sortIcon.src = 'icons/action/sort-down.svg';
                } else if (order === "date_asc" || order === "date_desc") {
                    sortIcon.src = 'icons/action/sort-up.svg';
                } else if (order === "date_desc" || order === "date_desc") {
                    sortIcon.src = 'icons/action/sort-down.svg';
                }

                applyFilters(); // Apply the filters to update the table
            }

            // Function to set file type and apply filters
            function setFileType(type) {
                document.getElementById("fileType").value = type;
                applyFilters();
            }

            // Function to clear all filters
            function clearFilters() {
                document.getElementById("sortOrder").value = "asc";
                document.getElementById("fileType").value = "";
                const sortIcon = document.getElementById("sortIcon");
                if (sortIcon) sortIcon.src = 'icons/action/sort.svg';
                loadDocumentsTable(1);
            }

            // Retain sort icon and file type state after page refresh
            document.addEventListener('DOMContentLoaded', function() {
                const urlParams = new URLSearchParams(window.location.search);

                // Update sort icon
                const sort = urlParams.get('sort');
                const sortIcon = document.getElementById('sortIcon');
                if (sortIcon) {
                    if (sort === 'asc') {
                        sortIcon.src = 'icons/action/sort-up.svg';
                    } else if (sort === 'desc') {
                        sortIcon.src = 'icons/action/sort-down.svg';
                    } else if (sort === 'date_asc') {
                        sortIcon.src = 'icons/action/sort-up.svg';
                    } else if (sort === 'date_desc') {
                        sortIcon.src = 'icons/action/sort-down.svg';
                    }
                }

                // Set sort order value
                if (sort) {
                    document.getElementById('sortOrder').value = sort;
                }

                // Highlight selected file type
                const fileType = urlParams.get('file_type');
                if (fileType) {
                    document.getElementById('fileType').value = fileType;
                }
                const fileTypeLinks = document.querySelectorAll('.dropdown-content a');
                fileTypeLinks.forEach(link => {
                    if (link.textContent.toLowerCase() === fileType) {
                        link.classList.add('selected');
                    } else {
                        link.classList.remove('selected');
                    }
                });

                // Set search query if it exists
                const searchQuery = urlParams.get('search_query');
                if (searchQuery) {
                    document.getElementById('searchQuery').value = searchQuery;
                }
            });
    </script>

    <style>
    .pagination {
        display: flex;
        justify-content: center;
        margin-top: 20px;
    }

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

    .pagination-button.active {
        background-color:rgb(255, 0, 0);
        color: white;
        border-color:rgb(255, 0, 0);
    }

    .pagination-button:hover {
        background-color:rgb(179, 0, 0);
        color: white;
    }

    #uploadModal {
        box-shadow: 0 2px 10px #0008;
        font-size: 1em;
        min-width: 300px;
        max-width: 350px;
        word-break: break-all;
    }
    #uploadProgressBar {
        transition: width 0.2s;
    }
    #uploadCancelBtn {
        background:rgb(199, 14, 32);
        color: #fff;
        border: none;
        border-radius: 5px;
        padding: 5px 10px;
        cursor: pointer;
    }
    </style>

    <footer>
        <p><a href="https://lagunappdco.online/GAD_PPMS" target="_blank" style="color: #ffffff;">Programs and Projects Monitoring System</a></p>
          <p>&copy; <?php echo date("Y"); ?> PPDCO. All rights reserved. </p>
    </footer>
</body>
</html>