<?php
// view_files.php
declare(strict_types=1);
session_start();
require_once __DIR__ . '/../../includes/connect.php'; // must define $pdo (PDO)

// ---------- Config ----------
$PER_PAGE_DEFAULT = 10;
$PER_PAGE_MAX     = 100;

// Whitelist sortable columns -> DB expressions
$sortable = [
    'filenumber'     => 't1.filenumber',
    'oldfilenumber'  => 't1.oldfilenumber',
    'datecreated'    => 't1.datecreated',
    'created_by'     => 'created_by', // alias from SELECT
];

// ---------- Inputs ----------
$page      = max(1, (int)($_GET['page']     ?? 1));
$perPage   = min($PER_PAGE_MAX, max(1, (int)($_GET['per_page'] ?? $PER_PAGE_DEFAULT)));
$search    = trim((string)($_GET['q']        ?? ''));
$sortKey   = (string)($_GET['sort']          ?? 'datecreated');
$sortDir   = strtolower((string)($_GET['dir'] ?? 'desc'));
$sortDir   = in_array($sortDir, ['asc','desc'], true) ? $sortDir : 'desc';
$orderBy   = $sortable[$sortKey] ?? 't1.datecreated';

// ---------- WHERE (search) ----------
$where = [];
$params = [];

if ($search !== '') {
    $where[] = "(t1.filenumber LIKE :q OR t1.oldfilenumber LIKE :q OR CONCAT(t2.surname,' ',t2.firstname) LIKE :q)";
    $params[':q'] = "%{$search}%";
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

// ---------- Count ----------
$countSql = "
    SELECT COUNT(*) AS cnt
    FROM file t1
    INNER JOIN users t2 ON t1.creatorid = t2.userid
    {$whereSql}
";
$stmt = $pdo->prepare($countSql);
$stmt->execute($params);
$total = (int)$stmt->fetchColumn();

// ---------- Pagination calc ----------
$pages   = max(1, (int)ceil($total / $perPage));
$offset  = ($page - 1) * $perPage;
if ($offset >= $total && $total > 0) { $page = 1; $offset = 0; }

// ---------- Data ----------
$sql = "
    SELECT
        t1.fileid,
        t1.filenumber,
        t1.oldfilenumber,
        t1.datecreated,
        CONCAT(t2.surname, ' ', t2.firstname) AS created_by
    FROM file t1
    INNER JOIN users t2 ON t1.creatorid = t2.userid
    {$whereSql}
    ORDER BY {$orderBy} {$sortDir}
    LIMIT :limit OFFSET :offset
";
$stmt = $pdo->prepare($sql);
foreach ($params as $k => $v) { $stmt->bindValue($k, $v, PDO::PARAM_STR); }
$stmt->bindValue(':limit',  $perPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset,  PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// helpers
function url_with(array $overrides = []): string {
    $q = $_GET;
    foreach ($overrides as $k => $v) { if ($v === null) unset($q[$k]); else $q[$k] = $v; }
    return htmlspecialchars($_SERVER['PHP_SELF'] . (empty($q) ? '' : ('?' . http_build_query($q))), ENT_QUOTES, 'UTF-8');
}
function sort_link(string $key, string $label, string $currentKey, string $currentDir): string {
    $dir = ($currentKey === $key && $currentDir === 'asc') ? 'desc' : 'asc';
    $href = url_with(['sort' => $key, 'dir' => $dir, 'page' => 1]);
    $arrow = ($currentKey === $key) ? ($currentDir === 'asc' ? ' ▲' : ' ▼') : '';
    return '<a class="th-sort" href="' . $href . '">' . htmlspecialchars($label) . $arrow . '</a>';
}
?>
<!doctype html>
<html lang="en" data-theme="light">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>View Files</title>
<style>
:root {
  --bg: #ffffff; --panel: #ffffff; --text: #0f172a; --muted: #475569;
  --accent: #2563eb; --accent-2: #4f46e5; --border: #e5e7eb;
  --row: #ffffff; --row-alt: #f8fafc; --thead: #f1f5f9;
}
html[data-theme="dark"] {
  --bg: #0b1220; --panel: #111827; --text: #e5e7eb; --muted: #9ca3af;
  --accent: #2563eb; --accent-2: #4f46e5; --border: #1f2937;
  --row: #0f172a; --row-alt: #0c1324; --thead: #0a1020;
}
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, "Helvetica Neue", Arial; background: var(--bg); color: var(--text); }
.container { max-width: 1200px; margin: 32px auto; padding: 0 16px; }
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
.h1 { font-size: 22px; font-weight: 800; }
.theme-toggle { border: 1px solid var(--border); background: var(--row-alt); color: var(--text); padding: 8px 12px; border-radius: 10px; cursor: pointer; }

/* Prominent Search */
.search-wrap {
  position: relative; margin: 16px 0 20px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap;
}
.search-input {
  flex: 1 1 520px; max-width: 840px; width: 100%;
  height: 48px; font-size: 16px; line-height: 48px;
  background: var(--row); color: var(--text); border: 2px solid var(--border);
  border-radius: 14px; padding: 0 14px 0 44px; outline: none;
  box-shadow: 0 8px 28px rgba(0,0,0,0.07);
}
.search-input:focus { border-color: var(--accent); box-shadow: 0 0 0 4px rgba(37,99,235,0.15); }
.search-icon {
  position: absolute; left: 14px; width: 20px; height: 20px; pointer-events: none;
  opacity: .7;
}
.button {
  background: linear-gradient(135deg, var(--accent), var(--accent-2));
  color: #fff; border: none; height: 48px; padding: 0 16px; border-radius: 12px; cursor: pointer; font-weight: 700;
}
.button.secondary { background: transparent; border: 1px solid var(--border); color: var(--text); }

/* Card/Table */
.card { background: var(--panel); border: 1px solid var(--border); border-radius: 16px; overflow: hidden; box-shadow: 0 6px 28px rgba(0,0,0,0.12); }
.table { width: 100%; border-collapse: collapse; font-size: 14px; }
thead th { background: var(--thead); position: sticky; top: 0; z-index: 1; text-align: left; padding: 12px; border-bottom: 1px solid var(--border); font-weight: 700; }
tbody tr:nth-child(odd) { background: var(--row); }
tbody tr:nth-child(even) { background: var(--row-alt); }
tbody td { padding: 12px; border-bottom: 1px solid var(--border); }
.th-sort { color: var(--text); text-decoration: none; }
.th-sort:hover { text-decoration: underline; }
.badge { display: inline-block; padding: 6px 10px; border-radius: 999px; background: rgba(79,70,229,0.12); color: inherit; border: 1px solid var(--border); font-size: 12px; font-weight: 600; }
.actions { display: flex; gap: 8px; align-items: center; }
.action-link { text-decoration: none; color: var(--accent); font-weight: 600; border: 1px solid var(--border); padding: 6px 10px; border-radius: 8px; }
.action-link:hover { filter: brightness(0.9); }

/* Header + Footer inside card */
.toolbar { display: flex; justify-content: space-between; align-items: center; padding: 12px; border-bottom: 1px solid var(--border); color: var(--muted); }
.footer { display: grid; grid-template-columns: 1fr auto auto; gap: 10px; align-items: center; padding: 12px; border-top: 1px solid var(--border); }
.pagination { display: flex; gap: 8px; align-items: center; justify-content: center; }
.page-btn { padding: 8px 12px; border: 1px solid var(--border); border-radius: 8px; background: transparent; color: var(--text); text-decoration: none; }
.page-btn[aria-current="page"] { font-weight: 700; outline: 2px solid var(--accent); outline-offset: 2px; }
.small { color: var(--muted); font-size: 12px; }

/* Per-page form (bottom) */
.perpage-form { display: flex; gap: 8px; align-items: center; }
.perpage-select {
  height: 40px; background: var(--row); color: var(--text); border: 1px solid var(--border);
  border-radius: 10px; padding: 0 10px;
}

/* Modal */
.modal-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,0.6); display: none; align-items: center; justify-content: center; }
.modal {
  width: min(1000px, 92vw); height: min(88vh, 900px);
  background: var(--panel); border: 1px solid var(--border); border-radius: 16px; overflow: hidden;
  display: flex; flex-direction: column;
}
.modal-header { display: flex; justify-content: space-between; align-items: center; padding: 10px 12px; border-bottom: 1px solid var(--border); }
.modal-body { flex: 1; background: var(--row); }
.modal-actions { display: flex; gap: 8px; }
.icon-btn { border: 1px solid var(--border); background: transparent; color: var(--text); padding: 8px 10px; border-radius: 8px; cursor: pointer; }
iframe { width: 100%; height: 100%; border: 0; background: var(--row); }
</style>
</head>
<body>
<div class="container">
  <div class="header">
    <div class="h1">View Files</div>
    <button class="theme-toggle" id="themeBtn" type="button" title="Toggle theme">Toggle Theme</button>
  </div>

  <!-- Prominent SEARCH BAR -->
  <form method="get" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" class="search-wrap" role="search" aria-label="Search files">
    <!-- Magnifier icon -->
    <svg class="search-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <circle cx="11" cy="11" r="7" stroke="currentColor" stroke-width="2"></circle>
      <path d="M20 20l-3.5-3.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path>
    </svg>
    <input class="search-input" type="text" name="q" placeholder="Search by File Number, Old File Number, or Created By…" value="<?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8'); ?>" />
    <input type="hidden" name="per_page" value="<?= (int)$perPage ?>">
    <input type="hidden" name="sort" value="<?= htmlspecialchars($sortKey, ENT_QUOTES, 'UTF-8') ?>">
    <input type="hidden" name="dir"  value="<?= htmlspecialchars($sortDir, ENT_QUOTES, 'UTF-8') ?>">
    <input type="hidden" name="page" value="1">
    <button class="button" type="submit">Search</button>
    <a class="button secondary" href="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">Reset</a>
  </form>

  <div class="card">
    <div class="toolbar small">
      <div>Total: <span class="badge"><?= number_format($total) ?></span></div>
      <div>Page <?= $page ?> of <?= $pages ?></div>
    </div>

    <?php if (empty($rows)): ?>
      <div style="text-align:center; padding:48px 16px; color:var(--muted);">No files found. Try a different search.</div>
    <?php else: ?>
      <div style="overflow:auto;">
        <table class="table">
          <thead>
            <tr>
              <th style="width:80px;">S/N</th>
              <th><?= sort_link('filenumber', 'File Number', $sortKey, $sortDir) ?></th>
              <th><?= sort_link('oldfilenumber', 'Old File Number', $sortKey, $sortDir) ?></th>
              <th><?= sort_link('datecreated', 'Date Created', $sortKey, $sortDir) ?></th>
              <th><?= sort_link('created_by', 'Created By', $sortKey, $sortDir) ?></th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php
              $snStart = $offset + 1;
              foreach ($rows as $i => $r):
                $sn = $snStart + $i;
                $fileNumber  = (string)$r['filenumber'];
                $oldNumber   = (string)($r['oldfilenumber'] ?? '');
                $dateCreated = $r['datecreated'] ? date('Y-m-d H:i', strtotime($r['datecreated'])) : '';
                $createdBy   = (string)$r['created_by'];
                $viewUrl     = 'document_view.php?filenumber=' . rawurlencode($fileNumber);
            ?>
              <tr>
                <td><?= $sn ?></td>
                <td><?= htmlspecialchars($fileNumber, ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($oldNumber, ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($dateCreated, ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($createdBy, ENT_QUOTES, 'UTF-8') ?></td>
                <td class="actions">
                  <a class="action-link" href="<?= htmlspecialchars($viewUrl, ENT_QUOTES, 'UTF-8') ?>" rel="noopener">View Document</a>
                  <a class="action-link" href="#" data-doc-href="<?= htmlspecialchars($viewUrl, ENT_QUOTES, 'UTF-8') ?>" onclick="openDoc(event)">Quick View</a>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <!-- FOOTER: range, pagination (center), RESULTS PER PAGE (right) -->
      <div class="footer">
        <div class="small">
          Showing <?= number_format(min($total, $offset + 1)) ?>–<?= number_format(min($total, $offset + count($rows))) ?> of <?= number_format($total) ?>
        </div>

        <div class="pagination">
          <?php
            $neighbors = 2; $first = 1; $last = $pages;
            $prev = max($first, $page - 1); $next = min($last, $page + 1);
            if ($page > $first) {
              echo '<a class="page-btn" href="'.url_with(['page'=>$first]).'">« First</a>';
              echo '<a class="page-btn" href="'.url_with(['page'=>$prev]).'">‹ Prev</a>';
            }
            $start = max($first, $page - $neighbors);
            $end   = min($last,  $page + $neighbors);
            if ($start > $first) echo '<span class="small" style="padding:0 6px;">…</span>';
            for ($p = $start; $p <= $end; $p++) {
              $current = $p === $page ? ' aria-current="page"' : '';
              echo '<a class="page-btn"'.$current.' href="'.url_with(['page'=>$p]).'">'.$p.'</a>';
            }
            if ($end < $last) echo '<span class="small" style="padding:0 6px;">…</span>';
            if ($page < $last) {
              echo '<a class="page-btn" href="'.url_with(['page'=>$next]).'">Next ›</a>';
              echo '<a class="page-btn" href="'.url_with(['page'=>$last]).'">Last »</a>';
            }
          ?>
        </div>

        <!-- Results-per-page selector (moved to bottom) -->
        <form method="get" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" class="perpage-form">
          <label for="per_page" class="small">Results per page</label>
          <select id="per_page" name="per_page" class="perpage-select" onchange="this.form.submit()">
            <?php foreach ([10,20,50,100] as $n): ?>
              <option value="<?= $n ?>" <?= $perPage===$n ? 'selected' : '' ?>><?= $n ?></option>
            <?php endforeach; ?>
          </select>
          <!-- preserve filters/sort, reset to page 1 -->
          <input type="hidden" name="q"    value="<?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8') ?>">
          <input type="hidden" name="sort" value="<?= htmlspecialchars($sortKey, ENT_QUOTES, 'UTF-8') ?>">
          <input type="hidden" name="dir"  value="<?= htmlspecialchars($sortDir, ENT_QUOTES, 'UTF-8') ?>">
          <input type="hidden" name="page" value="1">
        </form>
      </div>
    <?php endif; ?>
  </div>
</div>

<!-- Quick-View Modal -->
<div id="backdrop" class="modal-backdrop" role="dialog" aria-modal="true" aria-hidden="true">
  <div class="modal">
    <div class="modal-header">
      <strong>Document Preview</strong>
      <div class="modal-actions">
        <a id="downloadBtn" class="action-link" href="#" download>Download</a>
        <button class="icon-btn" onclick="closeDoc()">Close</button>
      </div>
    </div>
    <div class="modal-body">
      <iframe id="docFrame" src="about:blank"></iframe>
    </div>
  </div>
</div>

<script>
// Theme handling
(function initTheme(){
  const saved = localStorage.getItem('theme');
  const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
  const theme = saved || (prefersDark ? 'dark' : 'light');
  document.documentElement.setAttribute('data-theme', theme);
  updateThemeBtn(theme);
})();
document.getElementById('themeBtn').addEventListener('click', () => {
  const current = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'light';
  const next = current === 'dark' ? 'light' : 'dark';
  document.documentElement.setAttribute('data-theme', next);
  localStorage.setItem('theme', next);
  updateThemeBtn(next);
});
function updateThemeBtn(theme) {
  const btn = document.getElementById('themeBtn');
  btn.textContent = theme === 'dark' ? 'Light Mode' : 'Dark Mode';
}

// Modal
function openDoc(e){
  e.preventDefault();
  const href = e.currentTarget.getAttribute('data-doc-href');
  const frame = document.getElementById('docFrame');
  const dl = document.getElementById('downloadBtn');
  frame.src = href;
  dl.href = href;
  const bd = document.getElementById('backdrop');
  bd.style.display = 'flex';
  bd.setAttribute('aria-hidden','false');
}
function closeDoc(){
  const bd = document.getElementById('backdrop');
  const frame = document.getElementById('docFrame');
  frame.src = 'about:blank';
  bd.style.display = 'none';
  bd.setAttribute('aria-hidden','true');
}
</script>
</body>
</html>
