<?php
session_start();

$config = require __DIR__ . '/../lib/config.php';
require __DIR__ . '/../lib/db.php';
require __DIR__ . '/../lib/helpers.php';
require_admin_auth($config);

// Current user / tenancy
$me        = $_SESSION['user'] ?? [];
$orgId     = isset($me['organisation_id']) ? (int)$me['organisation_id'] : 0;
$companyId = isset($me['company_id'])      ? (int)$me['company_id']      : 0;
$role      = $me['role'] ?? '';

// System / org roles
$isAdmin        = ($role === 'admin');
$isOrgAdmin     = ($role === 'org_admin') || !empty($me['is_org_admin']); // keep legacy flag support
$isCompanyAdmin = ($role === 'company_admin');
$canMultiCompany = $isAdmin || $isOrgAdmin;

if ($orgId <= 0) {
  http_response_code(403);
  exit('Forbidden: no organisation scope.');
}

if ($pdo instanceof PDO) {
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

/**
 * Company scope:
 * - Normal users: fixed to their company_id.
 * - Org admins: can choose:
 *      - "All companies" within their org
 *      - A specific company (by id) in their org
 *
 * Selection is stored in $_SESSION['active_company_id'].
 */

$companies        = [];
$scopeCompanyId   = $companyId; // default for normal users
$scopeCompanyName = null;

if ($canMultiCompany) {
    // Admin / Org admin: can choose org-wide or specific company
    $stmt = $pdo->prepare("SELECT id, name FROM companies WHERE organisation_id = ? ORDER BY name");
    $stmt->execute([$orgId]);
    $companies = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Handle scope change via ?company=...
    if (isset($_GET['company'])) {
        $c = trim($_GET['company']);
        if ($c === '' || $c === 'all') {
            $_SESSION['active_company_id'] = null; // all companies in org
        } else {
            $cid = (int)$c;
            $valid = false;
            foreach ($companies as $co) {
                if ((int)$co['id'] === $cid) { $valid = true; break; }
            }
            if ($valid) {
                $_SESSION['active_company_id'] = $cid;
            }
        }
    }

    $active = $_SESSION['active_company_id'] ?? null;
    if ($active) {
        foreach ($companies as $co) {
            if ((int)$co['id'] === (int)$active) {
                $scopeCompanyId   = (int)$active;
                $scopeCompanyName = $co['name'];
                break;
            }
        }
        if (!$scopeCompanyName) {
            $_SESSION['active_company_id'] = null;
            $scopeCompanyId = null; // all companies
        }
    } else {
        // "All companies" in this org
        $scopeCompanyId = null;
    }
} else {
    // Non admin/org-admin: locked to their company
    if ($companyId <= 0) {
        http_response_code(403);
        exit('Forbidden: no company scope.');
    }
    $scopeCompanyId = $companyId;
}

// Filters & search
$filter = $_GET['filter'] ?? 'active'; // active|closed|all
$q      = trim($_GET['q'] ?? '');
$limit  = 200;

$where  = [];
$params = [];

// Status filter
if ($filter === 'active') {
  $where[] = "(LOWER(r.status) IN ('open','submitted'))";
} elseif ($filter === 'closed') {
  $where[] = "(LOWER(r.status) IN ('closed','expired'))";
}

// Search
if ($q !== '') {
  $where[] = "(r.reg_mark LIKE ? OR r.customer_name LIKE ? OR r.customer_email LIKE ?)";
  $like = '%' . $q . '%';
  $params[] = $like; $params[] = $like; $params[] = $like;
}

// Tenancy constraints
// Always restrict to current user's org:
$where[]  = "r.organisation_id = ?";
$params[] = $orgId;

if (!$canMultiCompany) {
  // Normal user: single company
  $where[]  = "r.company_id = ?";
  $params[] = $scopeCompanyId;
} else {
  // Org admin:
  if ($scopeCompanyId) {
    // Specific company selected
    $where[]  = "r.company_id = ?";
    $params[] = $scopeCompanyId;
  } else {
    // "All companies" -> no extra company filter (still org-bound)
  }
}

// Build final query
$sql = "
  SELECT r.*,
         (SELECT COUNT(*) FROM request_files m WHERE m.request_id = r.id) AS photo_count
  FROM requests r
";
if ($where) {
  $sql .= " WHERE " . implode(" AND ", $where);
}
$sql .= " ORDER BY r.id DESC LIMIT " . (int)$limit;

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$base   = rtrim($config['base_url'], '/');
$flash  = $_GET['msg'] ?? null;
$isDemo = !empty($config['demo_mode']);
?>

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Towlens<?= $isDemo ? ' (Demo Mode)' : '' ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
  /* ===== Custom Scrollbar ===== */
  ::-webkit-scrollbar { width:10px; height:10px; }
  ::-webkit-scrollbar-track { background:#f1f4f8; border-left:1px solid var(--line); }
  ::-webkit-scrollbar-thumb { background:linear-gradient(var(--brand),var(--brand-dark)); border-radius:5px; border:1px solid rgba(255,255,255,0.4); }
  ::-webkit-scrollbar-thumb:hover { background:linear-gradient(var(--brand-dark),#1e4c83); }
  * { scrollbar-width:thin; scrollbar-color:var(--brand) #f1f4f8; }

  /* ===== Classic Commercial Theme ===== */
  :root{
    --bg:#eceff3; --win:#ffffff; --ink:#1f2933; --muted:#5d6b78; --line:#cfd6de;
    --brand:#2f6db2; --brand-dark:#255a95; --ok:#3a7d3a; --danger:#b22f2f; --warning:#b28a2f;
    --radius:4px; --shadow:0 1px 0 rgba(0,0,0,.04), 0 2px 4px rgba(0,0,0,.06);
    --hdr-grad: linear-gradient(#f8fafc, #e8edf3);
    --btn-grad: linear-gradient(#f8fafc, #e6ecf2);
    --btn-grad-active: linear-gradient(#e6ecf2, #d9e1e9);
    --tbl-head-grad: linear-gradient(#eef3f8, #e2e9f1);
    --chip-open:#dfeaf7; --chip-submitted:#e4f1e4; --chip-closed:#ececec; --chip-expired:#f5dcdc;
  }
  *{box-sizing:border-box}
  html,body{height:100%}
  body{margin:0;font:13px/1.45 Segoe UI,Tahoma,Arial,Helvetica,sans-serif;color:var(--ink);background:var(--bg)}
  .app{min-height:100%;display:flex;flex-direction:column}
  .ribbon{background:var(--hdr-grad);border-bottom:1px solid var(--line);box-shadow:var(--shadow)}
  .ribbon-inner{max-width:1200px;margin:0 auto;padding:10px 14px;display:flex;align-items:center;justify-content:space-between;gap:10px}
  .title{display:flex;align-items:center;gap:10px}
  .title .mark{width:28px;height:28px;border-radius:4px;background:#2f6db2;box-shadow:inset 0 0 0 1px rgba(255,255,255,.4)}
  h1{font-size:16px;margin:0}.sub{color:var(--muted);font-size:12px}
  .toolbar{background:#f4f7fa;border-bottom:1px solid var(--line)}
  .toolbar-inner{max-width:1200px;margin:0 auto;padding:10px 14px;display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end;justify-content:space-between}
  .group{display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap}
  label{display:block;font-size:12px;color:var(--muted);margin-bottom:4px}
  input[type="text"],input[type="email"],select{
    background:#fff;border:1px solid var(--line);color:var(--ink);
    padding:6px 8px;border-radius:var(--radius);min-width:190px;outline:none;
    box-shadow:inset 0 1px 0 rgba(255,255,255,.8)
  }
  input[type="text"]:focus,input[type="email"]:focus,select:focus{border-color:#99b4d6}
  .btn,button,input[type="submit"]{
    appearance:none;border:1px solid #bfc8d2;color:#123;background:var(--btn-grad);
    font-weight:600;padding:6px 10px;border-radius:var(--radius);cursor:pointer;
    box-shadow:inset 0 1px 0 rgba(255,255,255,.85),0 1px 0 rgba(255,255,255,.5)
  }
  .btn:hover{background:var(--btn-grad-active)}
  .btn.primary{border-color:#2a5f9c;color:#fff;background:linear-gradient(#3b79c1,#2b67ab)}
  .btn.primary:hover{background:linear-gradient(#366fb2,#255f9f)}
  .btn.small{padding:4px 8px;font-size:12px}
  .window{max-width:1200px;margin:16px auto 24px;padding:0 14px;width:100%}
  .panel{background:var(--win);border:1px solid var(--line);border-radius:var(--radius);box-shadow:var(--shadow);padding:12px;margin-top:14px}
  .info{border:1px solid #bcd3bc;background:#edf5ed;color:#1d4e1d;padding:8px 10px;border-radius:4px;margin:10px 0}
  .demo{border:1px solid #e0bcbc;background:#f8e9e9;color:#7a2222;padding:8px 10px;border-radius:4px;margin:10px 0;font-weight:600}
  .table-wrap{overflow:auto;border:1px solid var(--line);border-radius:var(--radius)}
  table{border-collapse:separate;border-spacing:0;width:100%;background:#fff}
  thead th{
    background:var(--tbl-head-grad);border-bottom:1px solid var(--line);
    color:#2a3b4b;font-weight:700;text-align:left;font-size:12px;
    padding:8px 10px;position:sticky;top:0;z-index:1
  }
  tbody td{padding:7px 10px;border-bottom:1px solid #e7ecf1;vertical-align:top;font-size:13px}
  tbody tr:nth-child(even){background:#fafbfd}
  tbody tr:hover{background:#fffde7;cursor:pointer}
  .mono{font-family:Consolas,"Courier New",monospace}
  .actions{display:flex;gap:6px;flex-wrap:wrap}
  .col-actions{white-space:nowrap}
  .chip{display:inline-block;padding:3px 6px;border-radius:3px;border:1px solid var(--line);font-size:12px;font-weight:700}
  .chip.open{background:var(--chip-open)} .chip.submitted{background:var(--chip-submitted)} .chip.closed{background:var(--chip-closed)} .chip.expired{background:var(--chip-expired)}
  .bulkbar{display:none;margin-top:10px}
  .bulkbar .bar{background:#f6f9fc;border:1px solid var(--line);border-radius:var(--radius);padding:8px 10px;display:flex;align-items:center;justify-content:space-between;gap:10px}
  footer{color:var(--muted);font-size:12px;text-align:center;margin:16px 0}
  .demo-badge{position:fixed;right:12px;bottom:12px;background:#f8e9e9;color:#7a2222;border:1px solid #e0bcbc;border-radius:12px;padding:6px 10px;font-size:12px;box-shadow:var(--shadow)}

  /* Modal */
  .modal-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.35);display:none;align-items:center;justify-content:center;z-index:1000;}
  .modal{width:min(1000px,92vw);height:min(720px,88vh);background:#fff;border:1px solid var(--line);border-radius:6px;box-shadow:0 10px 30px rgba(0,0,0,.25);display:flex;flex-direction:column;overflow:hidden;}
  .modal-hdr{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:8px 10px;background:var(--tbl-head-grad);border-bottom:1px solid var(--line);}
  .modal-title{font-weight:700}
  .modal-actions{display:flex;gap:6px}
  .modal-body{flex:1;background:#f4f7fa}
  .modal-body iframe{display:block;width:100%;height:100%;border:0;background:#fff}

  /* Confirm modal */
  .aslink{background:none;border:0;padding:0;margin:0;font:inherit;color:#2f6db2;text-decoration:underline;cursor:pointer;}
  .aslink:hover{text-decoration:none;}

  /* Disable selection & context menu */
  html,body,.app,*{
    -webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;
    -webkit-touch-callout:none;
  }

  @keyframes pulseRow { 0%{background:#fff9c4}100%{background:transparent} }
  tr.status-updated { animation:pulseRow 1.2s ease-out 1; }
  </style>
</head>
<body class="<?= $isDemo ? 'demo' : '' ?>">
<div class="app">

  <!-- Ribbon -->
  <div class="ribbon">
    <div class="ribbon-inner">
      <div class="title">
       <!-- <div class="mark" aria-hidden="true"></div> -->
        <div>
          <h1>Towlens (THE EMAIL SYSTEM IS CURRENTLY DOWN)</h1>
          <div class="sub">Vehicle Imaging System</div>
        </div>
      </div>
<div class="actions">
  <?php if ($isAdmin || $isOrgAdmin): ?>
    <!-- Full system / org-level settings -->
    <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/settings.php">Settings</button>
  <?php elseif ($isCompanyAdmin): ?>
    <!-- Company-only settings -->
    <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/company_settings.php">Settings</button>
  <?php endif; ?>

  <button type="button" class="btn primary" data-nav="<?= esc($base) ?>/admin/logout.php">Logout</button>
</div>

    </div>
  </div>

  <!-- Toolbars -->
  <div class="toolbar">
    <div class="toolbar-inner">
      <!-- Create request (scoped by current company in create.php) -->
      <form class="group" action="<?= $base ?>/admin/create" method="post">
        <div>
          <label>Vehicle Registration</label>
          <input type="text" name="reg_mark" required maxlength="20" placeholder="ABC123" autocomplete="off">
        </div>
        <div>
          <label>Name</label>
          <input type="text" name="customer_name" maxlength="120" autocomplete="off">
        </div>
        <div>
          <label>Email</label>
          <input type="email" name="customer_email" maxlength="190" autocomplete="off">
        </div>
        <div>
          <label>Expires in (days)</label>
          <select name="days">
            <option value="">No expiry</option>
            <option>2</option><option>7</option><option>14</option><option>30</option>
          </select>
        </div>
        <div><button type="submit" class="btn primary">Generate Link</button></div>
      </form>

      <!-- Filters + search -->
      <form class="group" method="get" action="">
        <div>
          <label>Status</label>
          <select name="filter">
            <option value="active" <?= $filter==='active'?'selected':'' ?>>Active (Open + Submitted)</option>
            <option value="closed" <?= $filter==='closed'?'selected':'' ?>>Closed (Closed + Expired)</option>
            <option value="all"    <?= $filter==='all'   ?'selected':'' ?>>All</option>
          </select>
        </div>
        <div>
          <label>Search</label>
          <input type="text" name="q" value="<?= esc($q) ?>" placeholder="Email, Name, or Reg">
        </div>
        <div>
          <button type="submit" class="btn small">Apply</button>
          <button type="button" class="btn small" data-nav="?filter=active">Reset</button>
        </div>
      </form>

      <?php if ($canMultiCompany && $companies): ?>
        <form class="group" method="get" action="">
          <div>
            <label>Company scope</label>
            <select name="company" onchange="this.form.submit()">
              <option value="all" <?= $scopeCompanyId ? '' : 'selected' ?>>All companies</option>
              <?php foreach ($companies as $co): ?>
                <option value="<?= (int)$co['id'] ?>"
                  <?= ($scopeCompanyId === (int)$co['id']) ? 'selected' : '' ?>>
                  <?= esc($co['name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <!-- Preserve current filter/search when changing scope -->
          <?php if ($filter !== ''): ?>
            <input type="hidden" name="filter" value="<?= esc($filter) ?>">
          <?php endif; ?>
          <?php if ($q !== ''): ?>
            <input type="hidden" name="q" value="<?= esc($q) ?>">
          <?php endif; ?>
        </form>
      <?php endif; ?>

    </div>
  </div>

  <!-- Window -->
  <div class="window">
    <?php if ($isDemo): ?><div class="demo">DEMO MODE – visual flag only.</div><?php endif; ?>
    <?php if ($flash): ?><div class="info"><?= esc($flash) ?></div><?php endif; ?>

    <form id="bulkCloseForm" action="<?= $base ?>/admin/close" method="post" class="panel">
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:6px">
        <div style="font-weight:700">Requests</div>
        <div style="font-size:12px;color:var(--muted)">
          Legend:
          <span class="chip open">Open</span>
          <span class="chip submitted">Submitted</span>
          <span class="chip closed">Closed</span>
          <span class="chip expired">Expired</span>
        </div>
      </div>

      <div class="table-wrap">
        <table id="reqTable">
          <thead>
          <tr>
            <th style="width:34px"><input type="checkbox" onclick="toggleAll(this)"></th>
            <th>Created</th>
            <th>Reg</th>
            <th>Name</th>
            <th>Email</th>
            <th style="width:70px">Photos</th>
            <th>Status</th>
            <th>Expires</th>
            <th><!-- Link --></th>
            <th class="col-actions">Actions</th>
          </tr>
          </thead>
          <tbody>
          <?php if (!$rows): ?>
            <tr><td colspan="10" style="text-align:center;color:var(--muted);padding:18px">No requests found.</td></tr>
          <?php else:
            foreach ($rows as $r):
              $status     = strtolower($r['status']);
              #$link       = $base . '/public/upload.php?token=' . $r['token'];
              $canClose   = in_array($status, ['open','submitted'], true);
              $canReopen  = in_array($status, ['closed','expired'], true);
              $photoCount = (int)($r['photo_count'] ?? 0);
          ?>
            <tr data-id="<?= (int)$r['id'] ?>">
              <td>
                <?php if ($canClose): ?>
                  <input type="checkbox" class="rowcheck" name="ids[]" value="<?= (int)$r['id'] ?>" onchange="bulkBar()">
                <?php endif; ?>
              </td>
              <td><?= esc($r['created_at']) ?></td>
              <td><strong><?= esc($r['reg_mark']) ?></strong></td>
              <td><?= esc($r['customer_name'] ?: '-') ?></td>
              <td><?= esc($r['customer_email'] ?: '-') ?></td>
              <td class="mono"><?= $photoCount ?></td>
              <td class="col-status">
                <span class="chip <?= $status ?>"><?= esc($r['status']) ?></span>
              </td>
              <td class="col-expires"><?= esc($r['expires_at'] ?: '-') ?></td>
              <td class="mono">
                <!--<button type="button" class="aslink" data-open="<?= esc($link) ?>">Open</button> ·
                <button type="button" class="aslink" data-copy="<?= esc($link) ?>">Copy</button> -->
              </td>
<td class="col-actions">
  <div class="actions">
    <?php if ($canClose): ?>
      <button type="submit" name="id" value="<?= (int)$r['id'] ?>"
              class="btn primary small btn-confirm"
              formaction="<?= $base ?>/admin/close" formmethod="post"
              data-confirm-intent="close">Close</button>
    <?php endif; ?>

    <?php if ($canReopen): ?>
      <button type="submit" name="id" value="<?= (int)$r['id'] ?>"
              class="btn small btn-confirm"
              formaction="<?= $base ?>/admin/reopen" formmethod="post"
              data-confirm-intent="reopen">Reopen</button>
    <?php endif; ?>
  </div>
</td>

            </tr>
          <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>

      <!-- Bulk Action Bar -->
      <div class="bulkbar" id="bulkbar">
        <div class="bar">
          <div><strong id="bulkCount">0</strong> selected</div>
          <div>
            <button type="submit"
                    class="btn primary small btn-confirm-bulk"
                    formaction="<?= $base ?>/admin/close" formmethod="post"
                    data-confirm-intent="close-selected">
              Close Selected
            </button>
          </div>
        </div>
      </div>
    </form>

  <!--  <footer>
      <span class="mono">Powered by </span>
      <button type="button" class="aslink" data-open="https://mpmg.co.uk/software">
        Mount Pleasant Motoring Services
      </button>
    </footer>
  </div> -->

  <?php if ($isDemo): ?><div class="demo-badge">DEMO</div><?php endif; ?>
</div>

<!-- Modal: view request -->
<div class="modal-backdrop" id="modalBackdrop" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
  <div class="modal" role="document">
    <div class="modal-hdr">
      <div class="modal-title" id="modalTitle">Request</div>
      <div class="modal-actions">
        <button class="btn small" id="modalOpenNew">Open in new tab</button>
        <button class="btn small" id="modalCloseBtn">Close</button>
      </div>
    </div>
    <div class="modal-body">
      <iframe id="modalFrame" src="about:blank"></iframe>
    </div>
  </div>
</div>

<!-- Confirm modal -->
<div class="modal-backdrop" id="confirmBackdrop" role="dialog" aria-modal="true" aria-labelledby="confirmTitle" style="display:none">
  <div class="modal" role="document" style="width:min(520px,92vw);height:auto;max-height:80vh">
    <div class="modal-hdr">
      <div class="modal-title" id="confirmTitle">Confirm</div>
      <div class="modal-actions">
        <button class="btn small" id="confirmCloseX" type="button">Close</button>
      </div>
    </div>
    <div class="modal-body" style="padding:14px;background:#fff">
      <div id="confirmMessage" style="line-height:1.5"></div>
      <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:16px">
        <button class="btn" id="confirmCancel" type="button">Cancel</button>
        <button class="btn primary" id="confirmOk" type="button">Confirm</button>
      </div>
    </div>
  </div>
</div>

<script>
const BASE = "<?= esc($base) ?>";

/* Selection toggle */
function toggleAll(cb){
  document.querySelectorAll('.rowcheck').forEach(x => x.checked = cb.checked);
  bulkBar();
}
function bulkBar(){
  const checks = Array.from(document.querySelectorAll('.rowcheck'));
  const count = checks.filter(x => x.checked).length;
  const bar = document.getElementById('bulkbar');
  const cEl = document.getElementById('bulkCount');
  if (cEl) cEl.textContent = count;
  bar.style.display = count > 0 ? 'block' : 'none';
}

/* Copy helper */
function copyLink(text){
  try{
    if (navigator.clipboard) navigator.clipboard.writeText(text);
    else {
      const ta=document.createElement('textarea');
      ta.value=text; document.body.appendChild(ta);
      ta.select(); document.execCommand('copy'); ta.remove();
    }
    alert('Link copied to clipboard');
  }catch(e){ console.log(e); }
  return false;
}

/* Row double-click -> modal */
(function(){
  const tbody = document.querySelector('#reqTable tbody');
  if (!tbody) return;
  tbody.addEventListener('dblclick', function(ev){
    const tr = ev.target.closest('tr[data-id]');
    if (!tr) return;
    openModal(tr.getAttribute('data-id'));
  });
})();

/* ---------- Modal helpers ---------- */
const modalBackdrop = document.getElementById('modalBackdrop');
const modalFrame    = document.getElementById('modalFrame');
const modalTitle    = document.getElementById('modalTitle');
const modalOpenNew  = document.getElementById('modalOpenNew');
const modalCloseBtn = document.getElementById('modalCloseBtn');

function openModal(id) {
  if (!id) return;
  const url = 'view.php?id=' + encodeURIComponent(id);
  if (modalTitle) modalTitle.textContent = 'Request #' + id;
  if (modalFrame) modalFrame.src = url;
  if (modalOpenNew) {
    modalOpenNew.onclick = () => window.open(url, '_blank', 'noopener');
  }
  if (modalBackdrop) {
    modalBackdrop.style.display = 'flex';
    document.body.style.overflow = 'hidden';
  }
}

function closeModal() {
  if (modalBackdrop) modalBackdrop.style.display = 'none';
  if (modalFrame) modalFrame.src = 'about:blank';
  document.body.style.overflow = '';
}

if (modalCloseBtn) {
  modalCloseBtn.addEventListener('click', closeModal);
}
if (modalBackdrop) {
  modalBackdrop.addEventListener('click', (e) => {
    if (e.target === modalBackdrop) closeModal();
  });
}
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape' && modalBackdrop && modalBackdrop.style.display === 'flex') {
    closeModal();
  }
});

/* ---------- Double-click to open row in modal ---------- */
document.addEventListener('DOMContentLoaded', () => {
  const tbody = document.querySelector('#reqTable tbody');
  if (!tbody) return;

  tbody.addEventListener('dblclick', (ev) => {
    const tr = ev.target.closest('tr[data-id]');
    if (!tr) return;
    const id = tr.dataset.id;
    if (!id) return;
    openModal(id);
  });
});

/* ===== Global nav + actions using data-* ===== */
document.addEventListener('click', (e) => {
  const navBtn = e.target.closest('[data-nav]');
  if (navBtn) {
    window.location.assign(navBtn.getAttribute('data-nav'));
    return;
  }

  const openBtn = e.target.closest('[data-open]');
  if (openBtn) {
    window.open(openBtn.getAttribute('data-open'), '_blank', 'noopener');
    return;
  }

  const copyBtn = e.target.closest('[data-copy]');
  if (copyBtn) {
    copyLink(copyBtn.getAttribute('data-copy'));
    return;
  }
});

/* Block right-click */
window.addEventListener('contextmenu', (e) => e.preventDefault(), { capture: true });

/* ===== Styled confirm modal (for close/reopen) ===== */
const confirmBackdrop  = document.getElementById('confirmBackdrop');
const confirmTitleEl   = document.getElementById('confirmTitle');
const confirmMsgEl     = document.getElementById('confirmMessage');
const confirmOkBtn     = document.getElementById('confirmOk');
const confirmCancelBtn = document.getElementById('confirmCancel');
const confirmCloseX    = document.getElementById('confirmCloseX');
let _resolveConfirm    = null;

function showConfirm({ title = 'Confirm', message = 'Are you sure?', okText = 'Confirm' } = {}) {
  if (confirmTitleEl) confirmTitleEl.textContent = title;
  if (confirmMsgEl) {
    confirmMsgEl.textContent = '';
    if (typeof message === 'string') confirmMsgEl.textContent = message;
    else confirmMsgEl.innerHTML = message;
  }
  if (confirmOkBtn) confirmOkBtn.textContent = okText;

  if (confirmBackdrop) confirmBackdrop.style.display = 'flex';
  document.body.style.overflow = 'hidden';

  return new Promise((resolve) => { _resolveConfirm = resolve; });
}

function closeConfirm(result = false) {
  if (confirmBackdrop) confirmBackdrop.style.display = 'none';
  document.body.style.overflow = '';
  if (_resolveConfirm) _resolveConfirm(result);
  _resolveConfirm = null;
}

if (confirmOkBtn)     confirmOkBtn.addEventListener('click', () => closeConfirm(true));
if (confirmCancelBtn) confirmCancelBtn.addEventListener('click', () => closeConfirm(false));
if (confirmCloseX)    confirmCloseX.addEventListener('click', () => closeConfirm(false));
if (confirmBackdrop) {
  confirmBackdrop.addEventListener('click', (e) => {
    if (e.target === confirmBackdrop) closeConfirm(false);
  });
}
document.addEventListener('keydown', (e)=> {
  if (e.key === 'Escape' && confirmBackdrop && confirmBackdrop.style.display === 'flex') {
    closeConfirm(false);
  }
});

/* ===== Intercept row Close/Reopen to use styled confirm ===== */
document.addEventListener('click', async (e) => {
  const btn = e.target.closest('.btn-confirm');
  if (!btn) return;

  e.preventDefault();

  const tr = btn.closest('tr[data-id]');
  const id = tr ? tr.getAttribute('data-id') : null;
  const intent = btn.getAttribute('data-confirm-intent') || '';

const isClose    = intent === 'close';
const isReopen   = intent === 'reopen';
const isReqMore  = intent === 'request-more';

const title = isClose
  ? 'Close Request'
  : isReopen
    ? 'Reopen Request'
    : isReqMore
      ? 'Request More Photos'
      : 'Confirm';

const action = isClose
  ? 'close'
  : isReopen
    ? 'reopen'
    : isReqMore
      ? 'send another photo request email for'
      : 'proceed with';

const okText = isClose
  ? 'Close'
  : isReopen
    ? 'Reopen'
    : isReqMore
      ? 'Send email'
      : 'Confirm';

  const message = id
    ? `Are you sure you want to ${action} request #${id}?`
    : `Are you sure you want to ${action} this request?`;

  const ok = await showConfirm({
    title,
    message,
    okText: isClose ? 'Close' : (isReopen ? 'Reopen' : 'Confirm')
  });
  if (!ok) return;

  if (btn.form && typeof btn.form.requestSubmit === 'function') {
    btn.form.requestSubmit(btn);
  } else if (btn.form) {
    btn.form.submit();
  }
});

/* ===== Intercept Bulk Close Selected ===== */
document.addEventListener('click', async (e) => {
  const btn = e.target.closest('.btn-confirm-bulk');
  if (!btn) return;

  e.preventDefault();

  const count = Array.from(document.querySelectorAll('.rowcheck'))
    .filter(x => x.checked).length;
  if (count === 0) {
    alert('No rows selected.');
    return;
  }

  const ok = await showConfirm({
    title: 'Close Selected Requests',
    message: `Are you sure you want to close ${count} selected request${count===1?'':'s'}?`,
    okText: 'Close Selected'
  });
  if (!ok) return;

  if (btn.form && typeof btn.form.requestSubmit === 'function') {
    btn.form.requestSubmit(btn);
  } else if (btn.form) {
    btn.form.submit();
  }
});

/* ---------- Helpers for live status updates ---------- */
function toggleAll(cb){
  document.querySelectorAll('.rowcheck').forEach(x => x.checked = cb.checked);
  bulkBar();
}
function bulkBar(){
  const checks = Array.from(document.querySelectorAll('.rowcheck'));
  const count  = checks.filter(x => x.checked).length;
  const bar    = document.getElementById('bulkbar');
  const cEl    = document.getElementById('bulkCount');
  if (cEl) cEl.textContent = count;
  if (bar) bar.style.display = count > 0 ? 'block' : 'none';
}
function copyLink(text){
  try{
    if (navigator.clipboard) navigator.clipboard.writeText(text);
    else {
      const ta=document.createElement('textarea');
      ta.value=text; document.body.appendChild(ta);
      ta.select(); document.execCommand('copy'); ta.remove();
    }
    alert('Link copied to clipboard');
  }catch(e){ console.log(e); }
  return false;
}

function makeCloseBtn(id){
  const b = document.createElement('button');
  b.type = 'submit';
  b.name = 'id';
  b.value = id;
  b.className = 'btn primary small btn-confirm';
  b.setAttribute('formaction', `${BASE}/admin/close`);
  b.setAttribute('formmethod', 'post');
  b.setAttribute('data-confirm-intent', 'close');
  b.textContent = 'Close';
  return b;
}
function makeReopenBtn(id){
  const b = document.createElement('button');
  b.type = 'submit';
  b.name = 'id';
  b.value = id;
  b.className = 'btn small btn-confirm';
  b.setAttribute('formaction', `${BASE}/admin/reopen`);
  b.setAttribute('formmethod', 'post');
  b.setAttribute('data-confirm-intent', 'reopen');
  b.textContent = 'Reopen';
  return b;
}

function applyStatus(tr, statusText, newExpires){
  const chip = tr.querySelector('.col-status .chip');
  if (!chip) return;

  const incoming   = String(statusText || '').trim();
  const incomingLc = incoming.toLowerCase();
  const currentLc  = chip.textContent.trim().toLowerCase();
  if (incomingLc === currentLc) return;

  chip.textContent = incoming.charAt(0).toUpperCase() + incoming.slice(1);
  chip.classList.remove('open','submitted','closed','expired');
  if (['open','submitted','closed','expired'].includes(incomingLc)) {
    chip.classList.add(incomingLc);
  }

  if (typeof newExpires !== 'undefined') {
    const expiresTd = tr.querySelector('.col-expires');
    if (expiresTd) expiresTd.textContent = newExpires || '-';
  }

  const actions   = tr.querySelector('.col-actions .actions');
  const closeBtn  = actions?.querySelector('[data-confirm-intent="close"]');
  const reopenBtn = actions?.querySelector('[data-confirm-intent="reopen"]');
  const cb        = tr.querySelector('.rowcheck');

  if (incomingLc === 'closed' || incomingLc === 'expired') {
    if (cb) {
      cb.checked = false;
      cb.closest('td').innerHTML = '';
      bulkBar();
    }
    if (closeBtn) closeBtn.remove();
    if (actions && !reopenBtn) actions.appendChild(makeReopenBtn(tr.dataset.id));
  } else {
    if (reopenBtn) reopenBtn.remove();
    if (actions && !closeBtn) actions.prepend(makeCloseBtn(tr.dataset.id));
    const firstTd = tr.cells[0];
    if (firstTd && !firstTd.querySelector('input.rowcheck')) {
      firstTd.innerHTML =
        `<input type="checkbox" class="rowcheck" name="ids[]" value="${tr.dataset.id}" onchange="bulkBar()">`;
    }
  }

  tr.classList.remove('status-updated');
  void tr.offsetWidth;
  tr.classList.add('status-updated');
}

/* ----- status poller ----- */
let pollTimer = null;
let backoff   = 0;
const BASE_POLL_MS = 7000;

async function pollStatuses(){
  try{
    const rows = Array.from(document.querySelectorAll('#reqTable tbody tr[data-id]'));
    if (!rows.length) return scheduleNextPoll();
    const ids  = rows.map(tr => tr.dataset.id);

    const res = await fetch(`${BASE}/admin/poll_status.php`, {
      method:'POST',
      headers:{ 'Content-Type':'application/json', 'Accept':'application/json' },
      body: JSON.stringify({ ids })
    });
    if (!res.ok) throw new Error('http ' + res.status);
    const json = await res.json();
    if (!json.ok || !Array.isArray(json.statuses)) throw new Error('bad json');

    json.statuses.forEach(s => {
      const tr = document.querySelector(`#reqTable tbody tr[data-id="${s.id}"]`);
      if (!tr) return;
      applyStatus(tr, s.status, s.expires_at);
    });

    backoff = 0;
  }catch(e){
    backoff = Math.min(backoff + 2000, 30000);
    console.warn('Status poll failed:', e);
  }finally{
    scheduleNextPoll();
  }
}

function scheduleNextPoll(){
  clearTimeout(pollTimer);
  pollTimer = setTimeout(pollStatuses, BASE_POLL_MS + backoff);
}

document.addEventListener('visibilitychange', () => {
  if (document.hidden) clearTimeout(pollTimer);
  else scheduleNextPoll();
});
window.addEventListener('load', scheduleNextPoll);
</script>
