<?php
session_start();

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

$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare("SELECT * FROM requests WHERE id=?");
$stmt->execute([$id]);
$req = $stmt->fetch();
if (!$req) { http_response_code(404); echo "Not found"; exit; }

// Files from DB (for metadata like original name / mime / size)
$filesStmt = $pdo->prepare("SELECT * FROM request_files WHERE request_id=? ORDER BY id DESC");
$filesStmt->execute([$id]);
$dbFiles = $filesStmt->fetchAll();

// Notes
$notesStmt = $pdo->prepare("SELECT * FROM request_notes WHERE request_id=? ORDER BY id DESC");
$notesStmt->execute([$id]);
$notes = $notesStmt->fetchAll();

$token = $req['token'];
$uploadDir = rtrim($config['upload_dir'], '/').'/'.$token;
$sharesDir = $uploadDir.'/.shares';
$legacyShareFile = $uploadDir.'/.share.json'; // legacy single-share support (still works in public/share.php)
$shareBase = rtrim($config['base_url'], '/') . '/public/share.php';

// Ensure dirs
if (!is_dir($uploadDir)) { @mkdir($uploadDir, 0775, true); }
if (!is_dir($sharesDir)) { @mkdir($sharesDir, 0775, true); }

// Build a map filename => original label
$fileMetaByName = [];
foreach ($dbFiles as $f) {
  $fileMetaByName[$f['filename']] = $f;
}

// Get actual images currently present on disk
function list_images($dir) {
  if (!is_dir($dir)) return [];
  $out = [];
  foreach (scandir($dir) as $name) {
    if ($name === '.' || $name === '..') continue;
    if ($name === '.share.json' || $name === '.shares') continue;
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if (in_array($ext, ['jpg','jpeg','png','gif','webp','bmp','heic','svg'], true)) {
      $out[] = $name;
    }
  }
  // newest first
  usort($out, fn($a,$b)=> filemtime($dir.'/'.$b) <=> filemtime($dir.'/'.$a));
  return $out;
}
$diskImages = list_images($uploadDir);

// ---- Handle Share tab actions ----
$errors = [];
$notices = [];
$oneTimeMessage = null; // populated when a new share is created to show the message with the plaintext code once

function slug_alias($s) {
  $s = strtolower(trim($s));
  $s = preg_replace('/[^a-z0-9_-]+/','-', $s);
  $s = trim($s, '-_');
  if ($s === '') $s = 'share';
  return $s;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['share_action'])) {
  $action = $_POST['share_action'];

  if ($action === 'create') {
    $aliasRaw = $_POST['alias'] ?? '';
    $alias = slug_alias($aliasRaw);
    $expiryRaw = trim($_POST['expiry'] ?? '');
    $chosen = $_POST['files'] ?? [];

    // Validate
    if ($alias === '') { $errors[] = 'Alias is required.'; }
    if (empty($chosen) || !is_array($chosen)) { $errors[] = 'Please choose at least one image.'; }
    // sanitize chosen to basenames and to existing list
    $chosen = array_values(array_intersect(array_map('basename', $chosen), $diskImages));

    $shareFile = $sharesDir . '/' . $alias . '.json';
    if (file_exists($shareFile)) {
      $errors[] = 'That alias already exists for this request.';
    }

    // Parse expiry (optional)
    $expires_at = null;
    if ($expiryRaw !== '') {
      // Expect HTML datetime-local format: YYYY-MM-DDTHH:MM
      $ts = strtotime($expiryRaw);
      if ($ts === false) {
        $errors[] = 'Invalid expiry date/time.';
      } else {
        $expires_at = date('c', $ts);
      }
    }

    if (!$errors) {
      try {
        $code = strval(random_int(1000, 9999));
        $payload = [
          'request_id' => (int)$req['id'],
          'token'      => $token,
          'alias'      => $alias,
          'code_hash'  => password_hash($code, PASSWORD_DEFAULT),
          'created_at' => date('c'),
          'expires_at' => $expires_at,
          'files'      => $chosen,
        ];
        if (!is_dir($sharesDir)) { @mkdir($sharesDir, 0775, true); }
        if (file_put_contents($shareFile, json_encode($payload, JSON_PRETTY_PRINT)) === false) {
          throw new RuntimeException('Failed to write share file.');
        }
        $link = $shareBase . '?token=' . urlencode($token) . '&a=' . urlencode($alias);
        $oneTimeMessage = "We would like to share some images related to the registration {$req['reg_mark']}, you can view these here: {$link} using this code {$code}";
        $notices[] = 'Share created.';
      } catch (Throwable $e) {
        $errors[] = 'Error creating share: '.$e->getMessage();
      }
    }
  } elseif ($action === 'delete') {
    $alias = slug_alias($_POST['alias'] ?? '');
    $shareFile = $sharesDir . '/' . $alias . '.json';
    if ($alias === '' || !file_exists($shareFile)) {
      $errors[] = 'Share not found.';
    } else {
      @unlink($shareFile);
      $notices[] = 'Share deleted.';
    }
  }
}

// Load shares list
$shares = [];
if (is_dir($sharesDir)) {
  foreach (glob($sharesDir.'/*.json') as $jf) {
    $meta = json_decode(@file_get_contents($jf), true);
    if (!$meta || empty($meta['alias'])) continue;
    $alias = $meta['alias'];
    $meta['_path'] = $jf;
    $meta['_count'] = isset($meta['files']) && is_array($meta['files']) ? count($meta['files']) : 0;
    $meta['_expired'] = (!empty($meta['expires_at']) && strtotime($meta['expires_at']) < time());
    $meta['_link'] = $shareBase . '?token=' . urlencode($token) . '&a=' . urlencode($alias);
    $shares[$alias] = $meta;
  }
  ksort($shares);
}

?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8"><title>Request #<?= (int)$req['id'] ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    :root{--brand:#0f6fff}
    body{font-family:system-ui,Segoe UI,Arial,sans-serif;max-width:1100px;margin:24px auto;padding:0 16px}
    h1{margin-bottom:8px}
    .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:12px}
    .card{border:1px solid #ddd;border-radius:8px;padding:8px}
    img{max-width:100%;height:auto;border-radius:6px;cursor:pointer}
    .meta{color:#555;font-size:12px}
    .pill{padding:4px 8px;border-radius:999px;font-size:12px;display:inline-block;background:#f5f5f5}
    .toolbar{display:flex;gap:8px;align-items:center;margin:10px 0 18px 0}
    .alert{padding:10px;border-radius:8px;margin:10px 0}
    .alert.error{background:#ffecec;border:1px solid #f5b5b5;color:#8a0000}
    .alert.note{background:#eff7ff;border:1px solid #b6dcff;color:#003a73}
    .btn{display:inline-flex;align-items:center;gap:6px;border:1px solid #ccc;background:#f8f8f8;border-radius:8px;padding:8px 10px;cursor:pointer}
    .btn.primary{background:var(--brand);color:#fff;border-color:var(--brand)}
    .btn.danger{background:#c62828;color:#fff;border-color:#c62828}
    .row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
    .copybox{width:100%;min-height:70px;border:1px solid #ddd;border-radius:8px;padding:8px}
    .hidden{display:none}

    /* Tabs */
    .tabs{border-bottom:1px solid #eee;margin-top:18px}
    .tabs a{display:inline-block;padding:10px 12px;margin-right:6px;border:1px solid #eee;border-bottom:none;border-radius:8px 8px 0 0;text-decoration:none;color:#333}
    .tabs a.active{background:#fafafa;font-weight:600}
    .tabpane{padding:12px 4px}
    .muted{opacity:.65}

    /* Lightbox (for admin preview) */
    .lightbox{display:none;position:fixed;top:0;left:0;width:100%;height:100%;
      background:rgba(0,0,0,0.9);justify-content:center;align-items:center;z-index:9999;}
    .lightbox img{max-width:90%;max-height:90%;border-radius:8px}
    .lightbox .x,.lightbox .prev,.lightbox .next{position:absolute;color:white;font-size:34px;font-weight:bold;cursor:pointer;user-select:none;padding:10px;line-height:1}
    .lightbox .x{top:10px;right:20px}
    .lightbox .prev{top:50%;left:20px;transform:translateY(-50%)}
    .lightbox .next{top:50%;right:20px;transform:translateY(-50%)}

    table{width:100%;border-collapse:collapse}
    th,td{padding:8px;border-bottom:1px solid #eee;text-align:left}
    tr.expired td{opacity:.7}
    .tag{display:inline-block;background:#eee;border-radius:999px;padding:2px 8px;font-size:12px}
  </style>
</head>
<body>
  <h1>Request #<?= (int)$req['id'] ?> — <?= esc($req['reg_mark']) ?></h1>
  <p><strong>Status:</strong> <span class="pill"><?= esc($req['status']) ?></span></p>
  <p><strong>Customer:</strong> <?= esc($req['customer_name'] ?: '—') ?> (<?= esc($req['customer_email'] ?: '—') ?>)</p>
  <p><strong>Upload link:</strong> <a href="<?= esc($config['base_url'] . '/public/upload.php?token=' . $token) ?>" target="_blank"><?= esc($config['base_url'] . '/public/upload.php?token=' . $token) ?></a></p>
  <p><strong>Expires:</strong> <?= esc($req['expires_at'] ?: '—') ?></p>

  <?php foreach ($errors as $e): ?><div class="alert error"><?= esc($e) ?></div><?php endforeach; ?>
  <?php foreach ($notices as $n): ?><div class="alert note"><?= esc($n) ?></div><?php endforeach; ?>

  <?php if ($oneTimeMessage): ?>
    <div class="alert note">
      <strong>Copy & send:</strong>
      <textarea class="copybox" id="copyMsg" readonly><?= esc($oneTimeMessage) ?></textarea>
      <div class="row" style="margin-top:6px"><button class="btn" id="copyBtn">Copy message</button><span class="meta muted">The access code is shown once and not stored in plaintext.</span></div>
    </div>
  <?php endif; ?>

  <!-- Tabs -->
  <nav class="tabs" id="tabbar">
    <a href="#files" class="active">Files</a>
    <a href="#notes">Notes</a>
    <a href="#share">Share</a>
  </nav>

  <section id="pane-files" class="tabpane">
    <?php if (!$dbFiles): ?>
      <p>No files uploaded.</p>
    <?php else: ?>
      <div class="grid">
      <?php foreach($dbFiles as $i => $f):
        $src = '../uploads/' . esc($token) . '/' . esc($f['filename']);
      ?>
        <div class="card">
          <div class="meta"><?= esc($f['kind']) ?> • <?= esc($f['mime']) ?> • <?= number_format($f['size_bytes']) ?> B</div>
          <img src="<?= $src ?>" alt="" data-index="<?= $i ?>">
          <div class="meta"><?= esc($f['original']) ?></div>
        </div>
      <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </section>

  <section id="pane-notes" class="tabpane hidden">
    <h2 class="hidden">Notes</h2>
    <?php if (!$notes): ?>
      <p>No notes yet.</p>
    <?php else: ?>
      <ul>
      <?php foreach($notes as $n): ?>
        <li><em class="meta"><?= esc($n['created_at']) ?></em><br><?= nl2br(esc($n['notes'])) ?></li>
      <?php endforeach; ?>
      </ul>
    <?php endif; ?>
  </section>

  <section id="pane-share" class="tabpane hidden">
    <h2 class="hidden">Share</h2>

    <h3 style="margin:6px 0">Existing shares</h3>
    <?php if (empty($shares)): ?>
      <p class="muted">No shares yet.</p>
    <?php else: ?>
      <table>
        <thead>
          <tr><th>Alias</th><th>Created</th><th>Expiry</th><th>Files</th><th>Link</th><th></th></tr>
        </thead>
        <tbody>
          <?php foreach ($shares as $alias => $s): ?>
            <tr class="<?= $s['_expired'] ? 'expired' : '' ?>">
              <td><strong><?= esc($alias) ?></strong> <?= $s['_expired'] ? '<span class="tag">expired</span>' : '' ?></td>
              <td class="meta"><?= esc($s['created_at'] ?? '—') ?></td>
              <td class="meta"><?= esc($s['expires_at'] ?? '—') ?></td>
              <td><?= (int)$s['_count'] ?></td>
              <td class="meta"><a href="<?= esc($s['_link']) ?>" target="_blank"><?= esc($s['_link']) ?></a></td>
              <td>
                <form method="post" onsubmit="return confirm('Delete this share?');">
                  <input type="hidden" name="share_action" value="delete">
                  <input type="hidden" name="alias" value="<?= esc($alias) ?>">
                  <button class="btn danger" type="submit">Delete</button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>

    <h3 style="margin:18px 0 8px">Create a new share</h3>
    <form method="post">
      <input type="hidden" name="share_action" value="create">
      <div class="row" style="margin-bottom:8px">
        <label>Alias:
          <input name="alias" required placeholder="e.g. insurer-jan18" style="padding:8px;border:1px solid #ccc;border-radius:8px">
        </label>
        <label>Expiry (optional):
          <input type="datetime-local" name="expiry" style="padding:8px;border:1px solid #ccc;border-radius:8px">
        </label>
      </div>
      <div style="margin:8px 0 6px"><strong>Choose images</strong> <label class="meta" style="margin-left:10px"><input type="checkbox" id="selAll"> Select all</label></div>
      <div style="border:1px solid #eee;border-radius:8px;max-height:300px;overflow:auto;padding:8px">
        <?php if (empty($diskImages)): ?>
          <p class="muted">No images found on disk.</p>
        <?php else: foreach ($diskImages as $name):
          $orig = $fileMetaByName[$name]['original'] ?? $name;
        ?>
          <label style="display:flex;align-items:center;gap:8px;margin:4px 0">
            <input type="checkbox" name="files[]" value="<?= esc($name) ?>">
            <span class="meta"><?= esc($name) ?></span>
            <span class="meta" style="opacity:.7">— <?= esc($orig) ?></span>
          </label>
        <?php endforeach; endif; ?>
      </div>
      <div class="row" style="margin-top:10px">
        <button class="btn primary" type="submit">Create share</button>
      </div>
    </form>
    <p class="meta" style="margin-top:8px">A 4-digit access code will be generated and shown once after creation.</p>
  </section>

  <p style="margin-top:20px"><a href="index.php">Back</a></p>

  <!-- Lightbox for admin preview -->
  <div id="lightbox" class="lightbox" aria-hidden="true">
    <span class="x" title="Close">&times;</span>
    <span class="prev" title="Previous">&#10094;</span>
    <img id="lightbox-img" src="" alt="">
    <span class="next" title="Next">&#10095;</span>
  </div>

  <script>
    // Tabs
    const tabs = { files:'pane-files', notes:'pane-notes', share:'pane-share' };
    function setTab(t){
      for (const k in tabs){
        document.getElementById(tabs[k]).classList.toggle('hidden', k!==t);
        document.querySelector(`.tabs a[href="#${k}"]`).classList.toggle('active', k===t);
      }
      history.replaceState(null,'', '#'+t);
    }
    document.getElementById('tabbar').addEventListener('click', (e)=>{
      if (e.target.tagName==='A'){
        e.preventDefault();
        const t = e.target.getAttribute('href').substring(1);
        if (tabs[t]) setTab(t);
      }
    });
    setTab(location.hash.replace('#','') in tabs ? location.hash.replace('#','') : 'files');

    // Copy one-time message
    document.getElementById('copyBtn')?.addEventListener('click', async ()=>{
      const ta = document.getElementById('copyMsg');
      ta.select();
      try { await navigator.clipboard.writeText(ta.value); event.target.textContent='Copied!'; setTimeout(()=>event.target.textContent='Copy message', 1200);} catch{}
    });

    // Select all
    const selAll = document.getElementById('selAll');
    if (selAll) selAll.addEventListener('change', ()=>{
      document.querySelectorAll('input[name="files[]"]').forEach(cb => cb.checked = selAll.checked);
    });

    // Lightbox (admin)
    const imgs = Array.from(document.querySelectorAll('#pane-files .grid img'));
    const lb = document.getElementById('lightbox');
    const lbImg = document.getElementById('lightbox-img');
    const x = lb.querySelector('.x'), prev = lb.querySelector('.prev'), next = lb.querySelector('.next');
    let idx = 0;
    function openLB(i){ idx=i; lbImg.src = imgs[idx].src; lb.style.display='flex'; }
    function closeLB(){ lb.style.display='none'; }
    function n(){ idx=(idx+1)%imgs.length; lbImg.src=imgs[idx].src; }
    function p(){ idx=(idx-1+imgs.length)%imgs.length; lbImg.src=imgs[idx].src; }
    imgs.forEach((im,i)=> im.addEventListener('click', ()=> openLB(i)));
    x.addEventListener('click', closeLB); next.addEventListener('click', n); prev.addEventListener('click', p);
    document.addEventListener('keydown', e=>{ if(lb.style.display==='flex'){ if(e.key==='Escape') closeLB(); if(e.key==='ArrowRight') n(); if(e.key==='ArrowLeft') p(); }});
  </script>
</body>
</html>
