<?php
declare(strict_types=1);

require __DIR__ . '/../lib/helpers.php';
require __DIR__ . '/../lib/query.php';

$app = require __DIR__ . '/../config/app.php';
$db  = require __DIR__ . '/../config/db.php';

$q           = trim($_GET['q'] ?? '');
$status      = $_GET['status']   ?? '';
$docType     = $_GET['doc_type'] ?? '';
$from        = $_GET['from']     ?? '';
$to          = $_GET['to']       ?? '';
$page        = max(1, (int)($_GET['page'] ?? 1));
$pageSize    = min(100, max(5, (int)($_GET['ps'] ?? 20)));
$offset      = ($page - 1) * $pageSize;

[$where, $params] = build_documents_where([
    'q'            => $q,
    'status'       => $status,
    'doc_type'     => $docType,
    'created_from' => $from,
    'created_to'   => $to,
]);

$stmt = $db->prepare("SELECT COUNT(*) AS c FROM documents $where");
$stmt->execute($params);
$total = (int)$stmt->fetchColumn();

$sql = "SELECT id, filename, title, doc_type, filesize, status, created_at, updated_at
        FROM documents
        $where
        ORDER BY created_at DESC
        LIMIT :lim OFFSET :off";
$stmt = $db->prepare($sql);
foreach ($params as $k => $v) $stmt->bindValue($k, $v);
$stmt->bindValue(':lim', $pageSize, PDO::PARAM_INT);
$stmt->bindValue(':off', $offset,  PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll();

$types = $db->query("SELECT DISTINCT doc_type FROM documents WHERE doc_type IS NOT NULL AND doc_type <> '' ORDER BY doc_type ASC")->fetchAll(PDO::FETCH_COLUMN);

$lastPage = max(1, (int)ceil($total / $pageSize));
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title><?=h($app['app_name'])?> · Documents</title>
  <link rel="stylesheet" href="assets/bootstrap.min.css">
  <style>
    body { padding: 20px }
    .table td { vertical-align: middle; }
    .viewer-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.65);display:none;align-items:center;justify-content:center;z-index:1055}
    .viewer{width:90vw;height:90vh;background:#fff;border-radius:8px;overflow:hidden;display:flex;flex-direction:column}
    .viewer header{padding:10px 12px;border-bottom:1px solid #eee;display:flex;gap:8px;align-items:center;justify-content:space-between}
    .viewer iframe{border:0;flex:1}
  </style>
</head>
<body>
<div class="container-fluid">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <h1 class="h3 mb-0">Documents</h1>
    <div>
      <a class="btn btn-primary" href="<?=h(base_url('upload.php'))?>">+ Upload</a>
    </div>
  </div>

  <form class="card card-body mb-3" method="get">
    <div class="row g-2">
      <div class="col-md-4">
        <input type="text" name="q" value="<?=h($q)?>" class="form-control" placeholder="Search title, filename, type...">
      </div>
      <div class="col-md-2">
        <select name="doc_type" class="form-select">
          <option value="">All types</option>
          <?php foreach ($types as $t): ?>
            <option value="<?=h($t)?>" <?= $docType===$t?'selected':''?>><?=h($t)?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <select name="status" class="form-select">
          <option value="">Status: active+archived</option>
          <option value="active"   <?=$status==='active'?'selected':''?>>Active</option>
          <option value="archived" <?=$status==='archived'?'selected':''?>>Archived</option>
          <option value="deleted"  <?=$status==='deleted'?'selected':''?>>Deleted (show)</option>
        </select>
      </div>
      <div class="col-md-2">
        <input type="date" name="from" value="<?=h($from)?>" class="form-control" placeholder="From">
      </div>
      <div class="col-md-2">
        <input type="date" name="to" value="<?=h($to)?>" class="form-control" placeholder="To">
      </div>
    </div>
    <div class="mt-2 d-flex gap-2">
      <button class="btn btn-secondary">Filter</button>
      <a class="btn btn-outline-secondary" href="<?=h(base_url('index.php'))?>">Reset</a>
    </div>
  </form>

  <div class="card">
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-striped mb-0">
          <thead class="table-light">
            <tr>
              <th style="width:70px;">#</th>
              <th>Title</th>
              <th>Type</th>
              <th>Filename</th>
              <th>Size</th>
              <th>Status</th>
              <th>Created</th>
              <th style="width:180px;">Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if (!$rows): ?>
            <tr><td colspan="8" class="text-center text-muted p-4">No documents found.</td></tr>
          <?php endif; ?>
          <?php foreach ($rows as $r): ?>
            <tr>
              <td><?= (int)$r['id'] ?></td>
              <td><?= h($r['title'] ?: '—') ?></td>
              <td><?= h($r['doc_type'] ?: '—') ?></td>
              <td><?= h($r['filename']) ?></td>
              <td><?= h(format_bytes((int)$r['filesize'])) ?></td>
              <td><span class="badge bg-<?= $r['status']==='active'?'success':($r['status']==='archived'?'warning':'secondary') ?>">
                    <?= h($r['status']) ?>
                  </span></td>
              <td><?= h($r['created_at']) ?></td>
              <td class="d-flex gap-2">
                <button class="btn btn-sm btn-outline-primary"
                        data-view="<?=h(base_url('serve.php?id='.(int)$r['id']))?>">View</button>
                <a class="btn btn-sm btn-outline-success"
                   href="<?=h(base_url('download.php?id='.(int)$r['id']))?>">Download</a>

                <?php if ($r['status'] !== 'archived'): ?>
                  <form action="actions.php" method="post" class="d-inline">
                    <input type="hidden" name="csrf" value="<?=h(csrf_token())?>">
                    <input type="hidden" name="action" value="archive">
                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                    <button class="btn btn-sm btn-outline-warning">Archive</button>
                  </form>
                <?php else: ?>
                  <form action="actions.php" method="post" class="d-inline">
                    <input type="hidden" name="csrf" value="<?=h(csrf_token())?>">
                    <input type="hidden" name="action" value="restore">
                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                    <button class="btn btn-sm btn-outline-info">Restore</button>
                  </form>
                <?php endif; ?>

                <form action="actions.php" method="post" class="d-inline"
                      onsubmit="return confirm('Mark as deleted? You can still filter to view deleted items.');">
                  <input type="hidden" name="csrf" value="<?=h(csrf_token())?>">
                  <input type="hidden" name="action" value="delete">
                  <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                  <button class="btn btn-sm btn-outline-danger">Delete</button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <div class="card-footer d-flex justify-content-between align-items-center">
      <div>Showing <?= count($rows) ?> of <?=$total?> | Page <?=$page?> / <?=$lastPage?></div>
      <nav>
        <ul class="pagination mb-0">
          <?php
            $link = function($p) use($q,$status,$docType,$from,$to,$pageSize) {
              $qs = http_build_query([
                'q'=>$q,'status'=>$status,'doc_type'=>$docType,'from'=>$from,'to'=>$to,'ps'=>$pageSize,'page'=>$p
              ]);
              return '?' . $qs;
            };
          ?>
          <li class="page-item <?= $page<=1?'disabled':'' ?>"><a class="page-link" href="<?=h($link(max(1,$page-1)))?>">Prev</a></li>
          <li class="page-item <?= $page>=$lastPage?'disabled':'' ?>"><a class="page-link" href="<?=h($link(min($lastPage,$page+1)))?>">Next</a></li>
        </ul>
      </nav>
    </div>
  </div>
</div>

<div class="viewer-backdrop" id="viewer">
  <div class="viewer">
    <header>
      <strong>Preview</strong>
      <div>
        <a id="viewerDownload" class="btn btn-sm btn-success" href="#" target="_blank">Download</a>
        <button class="btn btn-sm btn-secondary" onclick="closeViewer()">Close</button>
      </div>
    </header>
    <iframe id="viewerFrame" src="about:blank"></iframe>
  </div>
</div>

<script>
  const viewer = document.getElementById('viewer');
  const frame  = document.getElementById('viewerFrame');
  const dl     = document.getElementById('viewerDownload');

  document.querySelectorAll('[data-view]').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.preventDefault();
      const url = btn.getAttribute('data-view');
      frame.src = url;
      dl.href   = url.replace('serve.php','download.php');
      viewer.style.display = 'flex';
    });
  });

  function closeViewer(){
    viewer.style.display = 'none';
    frame.src = 'about:blank';
  }

  viewer.addEventListener('click', (e) => {
    if (e.target === viewer) closeViewer();
  });
</script>
</body>
</html>
