<?php
declare(strict_types=1);

/* ============ CONFIG ============ */
require_once __DIR__ . '/../../includes/connect.php'; // MUST define $pdo (PDO)
$table = 'documents';

$filesBaseUrl = '/files/data';
$filesBaseDir = rtrim(str_replace('\\','/', $_SERVER['DOCUMENT_ROOT'] ?? ''), '/')
              . rtrim($filesBaseUrl, '/');

/* ============ SETUP ============ */
ini_set('display_errors', '1');
error_reporting(E_ALL);

function h(?string $s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function humanBytes(int|float $b, int $p = 1): string {
  $u=['B','KB','MB','GB','TB','PB']; $i=$b>0?floor(log($b,1024)):0; $i=max(0,min($i,count($u)-1));
  return round($b/(1024**$i),$p).' '.$u[$i];
}

/* Read inputs */
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
if ($method === 'POST') { $q = trim((string)($_POST['q'] ?? '')); $per = (int)($_POST['per'] ?? 20); }
else { $q = trim((string)($_GET['q'] ?? '')); $per = (int)($_GET['per'] ?? 20); }
$per = max(1, min($per, 100));
$page = max(1, (int)($_GET['page'] ?? 1));
$sort = (string)($_GET['sort'] ?? 'updated_at');
$dir  = strtolower((string)($_GET['dir'] ?? 'desc')) === 'asc' ? 'ASC' : 'DESC';

/* Preserve filters */
function buildUrl(array $overrides = []): string {
  $carry = [
    'q'   => trim((string)($_GET['q'] ?? $_POST['q'] ?? '')),
    'per' => (int)($_GET['per'] ?? $_POST['per'] ?? 20),
    'sort'=> $_GET['sort'] ?? 'updated_at',
    'dir' => $_GET['dir'] ?? 'desc',
  ];
  $q = array_merge($carry, $overrides);
  return strtok($_SERVER['REQUEST_URI'], '?') . (empty($q) ? '' : '?' . http_build_query($q));
}

/* Sort whitelist */
$sortWhitelist = ['updated_at','title','filename','filesize','doc_type','filenumber','reference'];
if (!in_array($sort, $sortWhitelist, true)) $sort = 'updated_at';

/* WHERE + params */
$where = '1'; $params = [];
if ($q !== '') {
  $where='(title LIKE :q OR filename LIKE :q OR doc_type LIKE :q OR filenumber LIKE :q OR `reference` LIKE :q)';
  $params[':q']='%'.$q.'%';
}

/* Count */
$stmt = $pdo->prepare("SELECT COUNT(*) FROM `$table` WHERE $where"); 
$stmt->execute($params);
$total = (int)$stmt->fetchColumn();
$pages = max(1, (int)ceil($total/$per)); 
$page=min($page,$pages); 
$offset=($page-1)*$per;

/* Fetch */
$sql = "SELECT filename, filepath, title, doc_type, filesize, updated_at,
               filenumber, `reference`
        FROM `$table`
        WHERE $where
        ORDER BY $sort $dir
        LIMIT :lim OFFSET :off";
$stmt = $pdo->prepare($sql);
foreach ($params as $k=>$v) $stmt->bindValue($k,$v,PDO::PARAM_STR);
$stmt->bindValue(':lim',$per,PDO::PARAM_INT);
$stmt->bindValue(':off',$offset,PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* Sort link helper */
function sortLink(string $col, string $label): string {
  $is = (($_GET['sort'] ?? 'updated_at') === $col);
  $curr = strtolower((string)($_GET['dir'] ?? 'desc'));
  $next = ($is && $curr==='desc') ? 'asc' : 'desc';
  $url = buildUrl(['sort'=>$col,'dir'=>$next,'page'=>1]);
  $arrow = $is ? ($curr==='desc' ? ' ↓' : ' ↑') : '';
  return '<a class="sort-link" href="'.h($url).'">'.h($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>DMS • View Documents</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
  <style>
    :root {
      --bg: #ffffff; --fg: #1f2937; --muted: #6b7280; --card: #ffffff;
      --table-stripe: #f8fafc; --accent: #0d6efd; --border: #e5e7eb; --modal-bg: rgba(0,0,0,0.65);
    }
    html[data-theme="dark"] {
      --bg: #0b0f16; --fg: #e5e7eb; --muted: #9aa4b2; --card: #111827;
      --table-stripe: #0f172a; --accent: #3b82f6; --border: #1f2937; --modal-bg: rgba(0,0,0,0.8);
    }
    body { background: var(--bg); color: var(--fg); }
    .card { background: var(--card); border-color: var(--border); }
    .form-control, .form-select { background: var(--bg); color: var(--fg); border-color: var(--border); }
    .form-control::placeholder { color: var(--muted); }
    .table { color: var(--fg); }
    thead.table-light { background: var(--table-stripe); color: var(--fg); border-bottom: 1px solid var(--border); }
    .table-striped>tbody>tr:nth-of-type(odd)>* { background: var(--table-stripe); }
    .page-link { color: var(--fg); background: var(--bg); border-color: var(--border); }
    .page-item.active .page-link { background: var(--accent); border-color: var(--accent); color: #fff; }
    .sort-link { text-decoration: none; color: var(--fg); }
    .sort-link:hover { color: var(--accent); }
    .toolbar { gap: .5rem; }
    .pdf-iframe { width: 100%; height: calc(85vh - 56px); border: 0; display: block; }
    .modal-backdrop.show { background-color: var(--modal-bg); }
    .modal-content { border-radius: 12px; border: 1px solid var(--border); background: var(--card); }
    .modal-header { border-bottom: 1px solid var(--border); }
    .modal-footer { border-top: 1px solid var(--border); }
    .badge-type { background: var(--table-stripe); color: var(--fg); border: 1px solid var(--border); }
    .muted { color: var(--muted); }
    .btn-toggle-theme { border-color: var(--border); color: var(--fg); background: var(--bg); }
    .btn-toggle-theme:hover { background: var(--table-stripe); }
  </style>
</head>
<body>
<div class="container py-4">

  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <h2 class="mb-0">Documents</h2>
      <small class="muted">Browse, preview and download files</small>
    </div>
    <div class="toolbar d-flex">
      <button id="themeToggle" type="button" class="btn btn-sm btn-toggle-theme">
        <i class="bi bi-moon-stars"></i> Theme
      </button>
    </div>
  </div>

  <!-- Search -->
  <form class="row gy-2 gx-2 align-items-center mb-3" method="post" action="">
    <div class="col-sm-5">
      <input type="search" class="form-control" name="q"
             placeholder="Search title / filename / doc type / file number / reference"
             value="<?=h($q)?>">
    </div>
    <div class="col-sm-2">
      <select class="form-select" name="per" onchange="this.form.submit()">
        <?php foreach ([10,20,50,100] as $opt): ?>
          <option value="<?=$opt?>" <?=$per===$opt?'selected':''?>><?=$opt?> per page</option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-sm-3">
      <button class="btn btn-primary" type="submit"><i class="bi bi-search"></i> Search</button>
      <a class="btn btn-outline-secondary" href="<?=h(strtok($_SERVER['REQUEST_URI'],'?'))?>"><i class="bi bi-x-circle"></i> Reset</a>
    </div>
    <div class="col-sm-2 text-sm-end">
      <small class="muted">Total: <?=$total?> • Page <?=$page?> of <?=$pages?></small>
    </div>
  </form>

  <!-- Table -->
  <div class="card">
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-striped table-hover align-middle mb-0">
          <thead class="table-light">
            <tr>
              <th class="text-nowrap"><?=sortLink('filenumber','File Number')?></th>
              <th class="text-nowrap"><?=sortLink('reference','Reference')?></th>
              <th><?=sortLink('title','Title')?></th>
              <th><?=sortLink('filename','Filename')?></th>
              <th><?=sortLink('doc_type','Type')?></th>
              <th class="text-end"><?=sortLink('filesize','Size')?></th>
              <th><?=sortLink('updated_at','Updated')?></th>
              <th class="text-center">View</th>
            </tr>
          </thead>
          <tbody>
          <?php if (!$rows): ?>
            <tr>
              <td colspan="8" class="text-center py-5">
                <div class="d-inline-flex flex-column align-items-center">
                  <div class="display-6 mb-2"><i class="bi bi-inbox"></i></div>
                  <div class="fw-semibold">No documents found</div>
                  <small class="muted">Try a different search keyword.</small>
                </div>
              </td>
            </tr>
          <?php else: foreach ($rows as $r):
            $rel = ltrim((string)$r['filepath'], '/');
            $fileUrl = rtrim($filesBaseUrl,'/').'/'.$rel;
            $absPath = rtrim($filesBaseDir,'/').'/'.$rel;
            $viewerUrl = $fileUrl . (str_contains($fileUrl,'?') ? '&' : '?') . 'abs=' . rawurlencode($absPath);
          ?>
            <tr>
              <td class="text-nowrap"><?=h($r['filenumber'] ?? '')?></td>
              <td class="text-nowrap"><?=h($r['reference'] ?? '')?></td>
              <td class="text-truncate" style="max-width:260px;"><span class="fw-semibold"><?=h($r['title'])?></span></td>
              <td class="text-truncate" style="max-width:280px;"><?=h($r['filename'])?></td>
              <td><span class="badge rounded-pill badge-type"><?=h($r['doc_type'])?></span></td>
              <td class="text-end"><?=is_null($r['filesize']) ? '' : h(humanBytes((int)$r['filesize']))?></td>
              <td class="text-nowrap"><small class="muted"><?=h($r['updated_at'])?></small></td>
              <td class="text-center">
                <a href="#" class="btn btn-sm btn-outline-primary view-pdf-btn"
                   data-url="<?=h($viewerUrl)?>"
                   data-rel="<?=h($rel)?>"
                   data-abs="<?=h($absPath)?>"
                   data-name="<?=h(($r['title'] ?: $r['filename']))?>"
                   title="Preview">
                  <i class="bi bi-eye"></i>
                </a>
              </td>
            </tr>
          <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Pagination -->
    <div class="card-footer">
      <nav aria-label="Pagination">
        <ul class="pagination mb-0">
          <?php $prev = max(1, $page-1); $next = min($pages, $page+1); ?>
          <li class="page-item <?=$page<=1?'disabled':''?>"><a class="page-link" href="<?=h(buildUrl(['page'=>1]))?>">First</a></li>
          <li class="page-item <?=$page<=1?'disabled':''?>"><a class="page-link" href="<?=h(buildUrl(['page'=>$prev]))?>">Prev</a></li>
          <li class="page-item disabled"><span class="page-link">Page <?=$page?> / <?=$pages?></span></li>
          <li class="page-item <?=$page>=$pages?'disabled':''?>"><a class="page-link" href="<?=h(buildUrl(['page'=>$next]))?>">Next</a></li>
          <li class="page-item <?=$page>=$pages?'disabled':''?>"><a class="page-link" href="<?=h(buildUrl(['page'=>$pages]))?>">Last</a></li>
        </ul>
      </nav>
    </div>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="pdfModal" tabindex="-1" aria-hidden="true"
     data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-fullscreen-md-down modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header align-items-start">
        <div class="me-3">
          <div class="fw-semibold" id="pdfTitle">Preview</div>
          <small class="muted d-block" id="pdfPath"></small>
        </div>
        <div class="ms-auto d-flex gap-2">
          <a id="openInNewTab" href="#" target="_blank" rel="noopener" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-box-arrow-up-right"></i> Open
          </a>
          <a id="downloadFile" href="#" class="btn btn-primary btn-sm">
            <i class="bi bi-download"></i> Download
          </a>
          <button type="button" class="btn-close ms-1" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
      </div>
      <div class="modal-body p-0">
        <iframe id="pdfFrame" class="pdf-iframe" src="about:blank" title="PDF preview"></iframe>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  (function initTheme(){
    const stored = localStorage.getItem('theme');
    const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
    const theme = stored || (prefersDark ? 'dark' : 'light');
    document.documentElement.setAttribute('data-theme', theme);
  })();

  document.getElementById('themeToggle').addEventListener('click', () => {
    const html = document.documentElement;
    const next = html.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
    html.setAttribute('data-theme', next);
    localStorage.setItem('theme', next);
  });

  (function(){
    const modalEl = document.getElementById('pdfModal');
    const modal   = new bootstrap.Modal(modalEl);
    const frame   = document.getElementById('pdfFrame');
    const titleEl = document.getElementById('pdfTitle');
    const pathEl  = document.getElementById('pdfPath');
    const openTab = document.getElementById('openInNewTab');
    const dlBtn   = document.getElementById('downloadFile');

    document.querySelectorAll('.view-pdf-btn').forEach(btn => {
      btn.addEventListener('click', e => {
        e.preventDefault();
        const url  = btn.getAttribute('data-url') || '';
        const name = btn.getAttribute('data-name') || 'Document';
        const rel  = btn.getAttribute('data-rel') || '';
        const abs  = btn.getAttribute('data-abs') || '';

        frame.src = url;
        openTab.href = url;
        dlBtn.href = 'download.php?p=' + encodeURIComponent(rel);
        titleEl.textContent = name;
        pathEl.textContent = abs;

        modal.show();
      });
    });

    modalEl.addEventListener('hidden.bs.modal', () => {
      frame.src = 'about:blank';
    });
  })();
</script>
</body>
</html>
