<?php
session_start();
include 'config.php';

// Restrict access to superadmin, admin, and md roles
if (!isset($_SESSION['role']) || !in_array(strtolower($_SESSION['role']), ['superadmin', 'admin', 'md'])) {
    header("Location: dashboard.php");
    exit();
}

// Handle document deletion
if (isset($_GET['delete'])) {
    $document_id = intval($_GET['delete']);
    
    $check_stmt = $conn->prepare("SELECT id FROM documents WHERE id = ?");
    if ($check_stmt === false) {
        die("Prepare failed: " . $conn->error);
    }
    
    $check_stmt->bind_param("i", $document_id);
    $check_stmt->execute();
    $check_stmt->store_result();
    
    if ($check_stmt->num_rows > 0) {
        $check_stmt->close();
        
        $conn->begin_transaction();
        
        try {
            $stmt1 = $conn->prepare("DELETE FROM document_status WHERE document_id = ?");
            if ($stmt1 === false) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            $stmt1->bind_param("i", $document_id);
            $stmt1->execute();
            
            $stmt2 = $conn->prepare("DELETE FROM documents WHERE id = ?");
            if ($stmt2 === false) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            $stmt2->bind_param("i", $document_id);
            $stmt2->execute();
            
            $conn->commit();
            $_SESSION['message'] = "Document deleted successfully";
        } catch (Exception $e) {
            $conn->rollback();
            $_SESSION['error'] = "Error deleting document: " . $e->getMessage();
        }
    } else {
        $_SESSION['error'] = "Document not found";
    }
    
    header("Location: manage_documents.php");
    exit();
}

$results_per_page = 10;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $results_per_page;

$total_result = $conn->query("SELECT COUNT(*) as total FROM documents");
if ($total_result === false) {
    die("Query failed: " . $conn->error);
}
$total_row = $total_result->fetch_assoc();
$total_pages = ceil($total_row['total'] / $results_per_page);

$stmt = $conn->prepare("SELECT id, title, created_by, pdf_file FROM documents ORDER BY id DESC LIMIT ?, ?");
if ($stmt === false) {
    die("Prepare failed: " . $conn->error);
}

$stmt->bind_param("ii", $offset, $results_per_page);
if (!$stmt->execute()) {
    die("Execute failed: " . $stmt->error);
}

$result = $stmt->get_result();

$username_session = $_SESSION['username'] ?? '';
function h($str) { return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>MPC · Manage Documents</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
/* ─── RESET & TOKENS ─────────────────────────────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

:root {
  --ink:        #0f172a;
  --ink-2:      #334155;
  --muted:      #94a3b8;
  --border:     #e2e8f0;
  --surface:    #ffffff;
  --bg:         #f1f5f9;
  --sidebar-bg: #0f172a;
  --sidebar-w:  260px;
  --radius: 12px;
  --shadow: 0 1px 3px rgba(15,23,42,.06), 0 4px 16px rgba(15,23,42,.06);
  font-family: 'Sora', system-ui, sans-serif;
}

html, body { height: 100%; }
body { background: var(--bg); color: var(--ink); font-size: 14px; line-height: 1.6; -webkit-font-smoothing: antialiased; }

/* ─── LAYOUT ─────────────────────────────────────────────────────────────── */
.layout { display: flex; min-height: 100vh; }

/* ─── SIDEBAR ────────────────────────────────────────────────────────────── */
.sidebar {
  width: var(--sidebar-w); background: var(--sidebar-bg);
  position: fixed; inset: 0 auto 0 0; z-index: 200;
  display: flex; flex-direction: column;
  overflow-y: auto; overflow-x: hidden;
  transition: transform .3s cubic-bezier(.4,0,.2,1); scrollbar-width: none;
}
.sidebar::-webkit-scrollbar { display: none; }
.sidebar.hidden { transform: translateX(-100%); }
.sidebar-brand {
  padding: 24px 20px 16px; display: flex; align-items: center; gap: 10px;
  border-bottom: 1px solid rgba(255,255,255,.06); margin-bottom: 8px;
}
.brand-logo {
  width: 36px; height: 36px; background: linear-gradient(135deg, #3b82f6, #6366f1);
  border-radius: 8px; display: flex; align-items: center; justify-content: center;
  font-size: 16px; font-weight: 700; color: #fff; flex-shrink: 0; letter-spacing: -.5px;
}
.brand-name { font-size: 15px; font-weight: 700; color: #fff; letter-spacing: .3px; }
.brand-sub  { font-size: 10px; color: rgba(255,255,255,.4); letter-spacing: 1.5px; text-transform: uppercase; margin-top: 1px; }
.nav-section { padding: 0 12px 6px; }
.nav-label   { font-size:10px; font-weight:600; letter-spacing:1.2px; text-transform:uppercase; color:rgba(255,255,255,.25); padding:8px 8px 4px; }
.nav-item    { list-style: none; }
.nav-link, .nav-dropdown-toggle {
  display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px;
  color: rgba(255,255,255,.65); text-decoration: none; font-size: 13px; font-weight: 500;
  cursor: pointer; border: none; background: none; width: 100%; text-align: left;
  transition: background .15s, color .15s; position: relative;
}
.nav-link:hover, .nav-dropdown-toggle:hover { background: rgba(255,255,255,.07); color: #fff; }
.nav-link.active { background: rgba(59,130,246,.2); color: #60a5fa; }
.nav-link i, .nav-dropdown-toggle i { width: 16px; text-align: center; font-size: 13px; }
.nav-dropdown-toggle .arrow { margin-left: auto; transition: transform .2s; font-size: 10px; }
.nav-dropdown-toggle.open .arrow { transform: rotate(180deg); }
.nav-submenu { list-style:none; overflow:hidden; max-height:0; transition:max-height .3s ease; padding-left:26px; }
.nav-submenu.open { max-height: 600px; }
.nav-submenu .nav-link { font-size: 12px; padding: 6px 10px; color: rgba(255,255,255,.5); }
.nav-submenu .nav-link:hover { color: #fff; background: rgba(255,255,255,.05); }
.sidebar-footer { margin-top: auto; padding: 12px; border-top: 1px solid rgba(255,255,255,.06); }

/* ─── CONTENT ────────────────────────────────────────────────────────────── */
.content { flex: 1; margin-left: var(--sidebar-w); min-width: 0; display: flex; flex-direction: column; transition: margin .3s cubic-bezier(.4,0,.2,1); }
.content.expanded { margin-left: 0; }

/* ─── TOPBAR ─────────────────────────────────────────────────────────────── */
.topbar {
  height: 60px; background: var(--surface); border-bottom: 1px solid var(--border);
  display: flex; align-items: center; gap: 12px; padding: 0 24px;
  position: sticky; top: 0; z-index: 100;
}
.hamburger-btn {
  width: 36px; height: 36px; border-radius: 8px; border: 1px solid var(--border);
  background: var(--surface); display: flex; align-items: center; justify-content: center;
  cursor: pointer; color: var(--ink-2); font-size: 15px; flex-shrink: 0; transition: background .15s;
}
.hamburger-btn:hover { background: var(--bg); }
.topbar-breadcrumb { display:flex; align-items:center; gap:6px; font-size:13px; color:var(--muted); }
.topbar-breadcrumb .current { color:var(--ink); font-weight:600; }
.topbar-spacer { flex: 1; }
.topbar-user { display:flex; align-items:center; gap:8px; font-size:13px; color:var(--ink-2); font-weight:500; }
.topbar-avatar {
  width: 30px; height: 30px; border-radius: 50%;
  background: linear-gradient(135deg, #3b82f6, #6366f1);
  display: flex; align-items: center; justify-content: center; color: #fff; font-size: 12px; font-weight: 700;
}

/* ─── PAGE ───────────────────────────────────────────────────────────────── */
.page { padding: 24px; flex: 1; }
.page-header { margin-bottom: 20px; }
.page-title  { font-size: 22px; font-weight: 700; color: var(--ink); letter-spacing: -.4px; }
.page-subtitle { font-size: 13px; color: var(--muted); margin-top: 2px; }

/* ─── CARD ───────────────────────────────────────────────────────────────── */
.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; margin-bottom: 20px; }
.card-header {
  display: flex; align-items: center; justify-content: space-between;
  padding: 16px 20px; border-bottom: 1px solid var(--border);
}
.card-title { font-size: 15px; font-weight: 700; color: var(--ink); letter-spacing: -.2px; display: flex; align-items: center; gap: 8px; }
.card-title i { font-size: 14px; color: var(--muted); }
.card-body { padding: 20px; }

/* ─── ALERT ──────────────────────────────────────────────────────────────── */
.alert {
  padding: 12px 16px; border-radius: 10px; font-size: 13px; font-weight: 500;
  display: flex; align-items: flex-start; gap: 10px; margin-bottom: 16px;
  border: 1px solid transparent; animation: fadeUp .25s ease;
}
.alert-success { background: #d1fae5; border-color: #6ee7b7; color: #065f46; }
.alert-danger   { background: #fee2e2; border-color: #fca5a5; color: #991b1b; }
.alert-close { margin-left: auto; cursor: pointer; background: none; border: none; font-size: 16px; color: inherit; opacity: .6; padding: 0 4px; line-height: 1; }
.alert-close:hover { opacity: 1; }
@keyframes fadeUp { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }

/* ─── BUTTONS ────────────────────────────────────────────────────────────── */
.btn {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 7px 14px; border-radius: 8px; border: 1px solid transparent;
  font-size: 12px; font-weight: 600; font-family: 'Sora', sans-serif;
  cursor: pointer; text-decoration: none; transition: opacity .15s;
  white-space: nowrap; line-height: 1;
}
.btn:hover { opacity: .88; }
.btn-primary   { background: #1d4ed8; color: #fff; border-color: #1d4ed8; }
.btn-warning   { background: #d97706; color: #fff; border-color: #d97706; }
.btn-danger    { background: #dc2626; color: #fff; border-color: #dc2626; }
.btn-outline   { background: var(--surface); color: var(--ink-2); border-color: var(--border); }
.btn-outline:hover { background: var(--bg); }
.btn-sm { padding: 5px 10px; font-size: 11px; border-radius: 6px; }
.action-bar { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; }

/* ─── FILTER ─────────────────────────────────────────────────────────────── */
.filter-bar {
  display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-end;
  padding: 14px 16px; background: var(--surface); border: 1px solid var(--border);
  border-radius: var(--radius); margin-bottom: 12px; box-shadow: var(--shadow);
}
.filter-group { display: flex; flex-direction: column; gap: 4px; }
.filter-group.grow { flex: 1; min-width: 180px; }
.filter-label { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .8px; color: var(--muted); }
.filter-input {
  height: 36px; border: 1px solid var(--border); border-radius: 8px;
  padding: 0 10px; font-size: 13px; font-family: 'Sora', sans-serif;
  color: var(--ink); background: var(--bg); outline: none;
  transition: border-color .15s, box-shadow .15s;
}
.filter-input:focus { border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59,130,246,.12); background: var(--surface); }

/* ─── TABLE ──────────────────────────────────────────────────────────────── */
.tbl-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
thead th {
  background: var(--ink); color: rgba(255,255,255,.85);
  font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: .8px;
  padding: 11px 14px; text-align: left; white-space: nowrap;
}
tbody td { padding: 11px 14px; border-bottom: 1px solid var(--border); color: var(--ink-2); vertical-align: middle; }
tbody tr:last-child td { border-bottom: none; }
tbody tr:hover td { background: #f8fafc; }
.sno-cell { font-family: 'JetBrains Mono', monospace; color: var(--muted); font-size: 12px; }

/* ─── PAGINATION ─────────────────────────────────────────────────────────── */
.pagination { display: flex; justify-content: center; gap: 6px; margin-top: 20px; flex-wrap: wrap; }
.page-link {
  display: inline-flex; align-items: center; justify-content: center;
  min-width: 34px; height: 34px; padding: 0 10px;
  border: 1px solid var(--border); border-radius: 8px;
  font-size: 13px; font-weight: 600; color: var(--ink-2); text-decoration: none;
  background: var(--surface); transition: background .15s, border-color .15s;
}
.page-link:hover { background: var(--bg); border-color: #94a3b8; }
.page-link.active { background: #1d4ed8; color: #fff; border-color: #1d4ed8; }

/* ─── RESPONSIVE ─────────────────────────────────────────────────────────── */
@media (max-width: 768px) {
  .sidebar { transform: translateX(-100%); }
  .sidebar:not(.hidden) { transform: none; }
  .content { margin-left: 0; }
  .page { padding: 16px; }
}
</style>
</head>
<body>
<div class="layout">

<!-- ── SIDEBAR ──────────────────────────────────────────────────────────── -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div>
      <div class="brand-name">MPC</div>
      <div class="brand-sub">Admin Portal</div>
    </div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item">
        <a href="dashboard_admin.php" class="nav-link">
          <i class="fas fa-sitemap"></i> Organisation Chart
        </a>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle open" onclick="toggleMenu(this)">
          <i class="fas fa-folder-open"></i> DAP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu open">
          <li><a href="manage_users.php"         class="nav-link"><i class="fas fa-users"></i>        Employee Details</a></li>
          <li><a href="manage_documents.php"     class="nav-link active"><i class="fas fa-file-alt"></i>     Policies Rolled Out</a></li>
          <li><a href="digital.php"              class="nav-link"><i class="fas fa-check-circle"></i> Acceptance Confirmed</a></li>
          <li><a href="change_password.php"      class="nav-link"><i class="fas fa-key"></i>          Change Password</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-calendar-alt"></i> CAB<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="attendance.php"              class="nav-link"><i class="fas fa-clock"></i>             Attendance Dashboard</a></li>
          <li><a href="payroll.php"                 class="nav-link"><i class="fas fa-money-bill"></i>        Payroll Dashboard</a></li>
          <li><a href="task_dashboard.php"          class="nav-link"><i class="fas fa-tasks"></i>            Task Dashboard</a></li>
          <li><a href="daily_reports_dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i>       Daily Report Dashboard</a></li>
          <li><a href="company_holidays.php"        class="nav-link"><i class="fas fa-star"></i>             Company Holidays</a></li>
          <li><a href="hr_approval_salary.php"      class="nav-link"><i class="fas fa-hand-holding-usd"></i> Advance Dashboard</a></li>
          <li><a href="expense_dashboard.php"       class="nav-link"><i class="fas fa-receipt"></i>          Expenses Dashboard</a></li>
          <li><a href="leave_dashboard.php"         class="nav-link"><i class="fas fa-umbrella-beach"></i>   Leave Dashboard</a></li>
          <li><a href="grievance_dashboard.php"     class="nav-link"><i class="fas fa-comment-alt"></i>      Grievance Dashboard</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-user-tie"></i> PEP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="individual_rr.php"     class="nav-link"><i class="fas fa-trophy"></i>   Individual R &amp; R</a></li>
          <li><a href="individual_kpi.php"    class="nav-link"><i class="fas fa-bullseye"></i> Individual KPI</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>  Login Credentials</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-book-open"></i> L&amp;D<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="incident_employee.php"  class="nav-link"><i class="fas fa-exclamation-triangle"></i> Incident Portal</a></li>
          <li><a href="training_dashboard.php" class="nav-link"><i class="fas fa-chalkboard-teacher"></i>   Training Portal</a></li>
          <li><a href="rr.php"                 class="nav-link"><i class="fas fa-award"></i>                Rewards &amp; Recognition</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-star"></i> AAA<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="employee_tiy.php"      class="nav-link"><i class="fas fa-user-check"></i> Employee TIY</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>    Login Credentials</a></li>
        </ul>
      </li>
    </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link" style="color:#f87171;">
      <i class="fas fa-sign-out-alt"></i> Logout
    </a>
  </div>
</nav>

<!-- ── CONTENT ───────────────────────────────────────────────────────────── -->
<div class="content" id="content">

  <!-- Topbar -->
  <div class="topbar">
    <button class="hamburger-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="topbar-breadcrumb">
      <span>DAP</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">Policies Rolled Out</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?php echo strtoupper(substr($username_session ?: 'A', 0, 1)); ?></div>
      <?php echo h($username_session ?: 'Admin'); ?>
    </div>
  </div>

  <!-- Page -->
  <div class="page">

    <div class="page-header">
      <div class="page-title">Manage Documents</div>
      <div class="page-subtitle">Create, view and manage policy documents rolled out to employees</div>
    </div>

    <?php if (isset($_SESSION['message'])): ?>
      <div class="alert alert-success" id="flashMsg">
        <i class="fas fa-check-circle"></i>
        <span><?php echo h($_SESSION['message']); unset($_SESSION['message']); ?></span>
        <button class="alert-close" onclick="this.closest('.alert').remove()">×</button>
      </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
      <div class="alert alert-danger" id="flashMsg">
        <i class="fas fa-exclamation-circle"></i>
        <span><?php echo h($_SESSION['error']); unset($_SESSION['error']); ?></span>
        <button class="alert-close" onclick="this.closest('.alert').remove()">×</button>
      </div>
    <?php endif; ?>

    <div class="action-bar">
      <a href="create_document.php" class="btn btn-primary">
        <i class="fas fa-plus"></i> Create New Document
      </a>
    </div>

    <div class="card">
      <div class="card-header">
        <div class="card-title"><i class="fas fa-file-alt"></i> Document List</div>
        <span style="font-size:12px;color:var(--muted);font-family:'JetBrains Mono',monospace;font-weight:600">
          Showing <?php echo ($offset + 1); ?>–<?php echo min($offset + $results_per_page, $total_row['total']); ?> of <?php echo $total_row['total']; ?>
        </span>
      </div>

      <!-- Filter bar -->
      <div style="padding:14px 20px;border-bottom:1px solid var(--border);background:var(--bg);">
        <div class="filter-bar" style="margin-bottom:0;box-shadow:none;border:none;padding:0;background:transparent;">
          <div class="filter-group grow">
            <span class="filter-label">Search by Title</span>
            <input type="text" id="titleFilter" class="filter-input" placeholder="Filter by title…" onkeyup="filterTable()">
          </div>
          <div class="filter-group grow">
            <span class="filter-label">Search by Creator</span>
            <input type="text" id="creatorFilter" class="filter-input" placeholder="Filter by creator…" onkeyup="filterTable()">
          </div>
        </div>
      </div>

      <div class="tbl-wrap">
        <table id="documentsTable">
          <thead>
            <tr>
              <th style="width:46px">#</th>
              <th>Title</th>
              <th>Created By</th>
              <th>PDF File</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $i = $offset + 1;
            while ($row = $result->fetch_assoc()):
              $creator_name = 'System';
              if ($row['created_by']) {
                $creator_stmt = $conn->prepare("SELECT username FROM users WHERE id = ?");
                $creator_stmt->bind_param("s", $row['created_by']);
                $creator_stmt->execute();
                $creator_result = $creator_stmt->get_result();
                if ($creator_result->num_rows > 0) {
                  $creator = $creator_result->fetch_assoc();
                  $creator_name = $creator['username'];
                } else {
                  $creator_name = 'Unknown';
                }
                $creator_stmt->close();
              }
            ?>
            <tr>
              <td class="sno-cell"><?php echo $i++; ?></td>
              <td class="col-title" style="font-weight:600;color:var(--ink)"><?php echo h($row['title']); ?></td>
              <td class="col-creator" style="color:var(--ink-2)"><?php echo h($creator_name); ?></td>
              <td>
                <?php if ($row['pdf_file']): ?>
                  <a href="<?php echo h($row['pdf_file']); ?>" target="_blank" class="btn btn-sm btn-outline">
                    <i class="fas fa-file-pdf" style="color:#dc2626"></i> View PDF
                  </a>
                <?php else: ?>
                  <span style="font-size:12px;color:var(--muted)">No file</span>
                <?php endif; ?>
              </td>
              <td>
                <div style="display:flex;flex-wrap:wrap;gap:5px">
                  <a href="edit_document.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-warning">
                    <i class="fas fa-edit"></i> Edit
                  </a>
                  <a href="manage_documents.php?delete=<?php echo $row['id']; ?>" class="btn btn-sm btn-danger"
                     onclick="return confirm('Are you sure you want to delete this document? All related data will also be deleted.');">
                    <i class="fas fa-trash-alt"></i> Delete
                  </a>
                </div>
              </td>
            </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>

      <?php if ($total_pages > 1): ?>
      <div style="padding:16px 20px;border-top:1px solid var(--border);">
        <div class="pagination">
          <?php if ($page > 1): ?>
            <a class="page-link" href="manage_documents.php?page=<?php echo $page - 1; ?>">«</a>
          <?php endif; ?>
          <?php for ($p = 1; $p <= $total_pages; $p++): ?>
            <a class="page-link <?php echo ($p == $page) ? 'active' : ''; ?>"
               href="manage_documents.php?page=<?php echo $p; ?>"><?php echo $p; ?></a>
          <?php endfor; ?>
          <?php if ($page < $total_pages): ?>
            <a class="page-link" href="manage_documents.php?page=<?php echo $page + 1; ?>">»</a>
          <?php endif; ?>
        </div>
      </div>
      <?php endif; ?>
    </div>

  </div><!-- /page -->
</div><!-- /content -->
</div><!-- /layout -->

<script>
function toggleSidebar() {
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}
function toggleMenu(btn) {
  btn.nextElementSibling.classList.toggle('open');
  btn.classList.toggle('open');
}
document.addEventListener('DOMContentLoaded', function() {
  var fm = document.getElementById('flashMsg');
  if (!fm) return;
  setTimeout(function() {
    fm.style.transition = 'opacity .5s, transform .5s';
    fm.style.opacity = '0'; fm.style.transform = 'translateY(-6px)';
    setTimeout(function() { if (fm.parentNode) fm.parentNode.removeChild(fm); }, 520);
  }, 5000);
});
function filterTable() {
  var titleFilter   = document.getElementById('titleFilter').value.toLowerCase().trim();
  var creatorFilter = document.getElementById('creatorFilter').value.toLowerCase().trim();
  var rows = document.querySelectorAll('#documentsTable tbody tr');
  rows.forEach(function(r) {
    var title   = (r.querySelector('.col-title')   || {textContent:''}).textContent.toLowerCase();
    var creator = (r.querySelector('.col-creator') || {textContent:''}).textContent.toLowerCase();
    var show = true;
    if (titleFilter   && title.indexOf(titleFilter)     === -1) show = false;
    if (creatorFilter && creator.indexOf(creatorFilter) === -1) show = false;
    r.style.display = show ? '' : 'none';
  });
}
</script>
</body>
</html>