<?php
// public/create.php
declare(strict_types=1);

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

/** Prevent cached copies of this page */
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');

$base        = rtrim($config['base_url'] ?? '', '/');
$isDemo      = !empty($config['demo_mode']);
$orgId       = 1; // Always use organisation_id = 1 for these public requests

/**
 * Resolve company from short code (?c=1)
 * - Short link: ?c=1
 * - For now treat c as the actual company_id.
 */
$cParam    = $_GET['c'] ?? $_GET['company'] ?? null;
$companyId = null;

if ($cParam !== null) {
    $companyId = filter_var($cParam, FILTER_VALIDATE_INT, [
        'options' => ['min_range' => 1]
    ]) ?: null;
}

if ($companyId === null) {
    render_message(
        400,
        'Invalid link',
        'This request link is incomplete.',
        'Please contact your coordinator for a valid link.'
    );
}

/* -------------------- helpers -------------------- */
if (!function_exists('client_ip')) {
  function client_ip(): string {
    $candidates = ['HTTP_CF_CONNECTING_IP','HTTP_X_FORWARDED_FOR','HTTP_CLIENT_IP','REMOTE_ADDR'];
    foreach ($candidates as $key) {
      if (empty($_SERVER[$key])) continue;
      $raw = $_SERVER[$key];
      if ($key === 'HTTP_X_FORWARDED_FOR') {
        foreach (array_map('trim', explode(',', $raw)) as $part) {
          if (filter_var($part, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)) return $part;
        }
        continue;
      }
      if (filter_var($raw, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)) return $raw;
    }
    return 'unknown';
  }
}

if (!function_exists('uuidv4')) {
  function uuidv4(): string {
    $data = random_bytes(16);
    $data[6] = chr((ord($data[6]) & 0x0f) | 0x40);
    $data[8] = chr((ord($data[8]) & 0x3f) | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  }
}

if (!function_exists('normalize_reg')) {
  function normalize_reg(string $s): string {
    $s = strtoupper($s);
    return preg_replace('/[^A-Z0-9]/', '', $s) ?? '';
  }
}

function render_message(int $code, string $title, string $lead, string $detail = ''): void {
  http_response_code($code);
  $isDemo = !empty($GLOBALS['isDemo']);
  $base   = $GLOBALS['base'] ?? '';
  ?>
  <!doctype html>
  <html lang="en" class="h-full">
  <head>
    <meta charset="utf-8">
    <title><?= esc($title) ?><?= $isDemo ? ' — Demo Mode' : '' ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="color-scheme" content="light dark">
    <style>
      :root{ --brand:#0f6fff; --ink:#0b1220; --muted:#5b6478; --bg:#f6f7fb; --card:#ffffff; --ring:#d6d9e2; }
      @media (prefers-color-scheme: dark){ :root{ --ink:#eef3ff; --muted:#a9b3c7; --bg:#0b0f1a; --card:#12192a; --ring:#27314a; } }
      *{box-sizing:border-box} html,body{height:100%}
      body{
        margin:0;
        font:16px/1.5 system-ui,Segoe UI,Roboto,Arial,Helvetica,sans-serif;
        color:var(--ink);
        background:
          radial-gradient(1200px 600px at 10% -10%, rgba(15,111,255,.16), transparent 60%),
          radial-gradient(900px 500px at 110% 0%, rgba(15,111,255,.10), transparent 60%),
          var(--bg);
        display:grid;
        place-items:center;
        padding:24px;
      }
      .card{
        width:min(720px, 92vw);
        background:var(--card);
        border:1px solid var(--ring);
        border-radius:20px;
        box-shadow:0 18px 40px rgba(15,17,23,.08);
        overflow:hidden;
        animation:pop .35s ease-out;
        position:relative;
      }
      @keyframes pop{
        from{transform:translateY(8px) scale(.98);opacity:0}
        to{transform:none;opacity:1}
      }
      .hdr{
        display:flex;
        gap:14px;
        align-items:center;
        padding:20px 22px;
        background:linear-gradient(180deg, rgba(15,111,255,.12), transparent 70%);
        border-bottom:1px solid var(--ring)
      }
      .logo{
        width:44px;height:44px;
        border-radius:12px;
        background:var(--brand);
        color:#fff;
        display:grid;
        place-items:center;
        font-weight:800;
        letter-spacing:.5px;
        box-shadow:inset 0 0 0 2px rgba(255,255,255,.25)
      }
      .title{margin:0;font-size:20px}
      .body{padding:22px}
      .lead{font-size:18px;margin:0 0 8px}
      .muted{color:var(--muted);margin:0 0 18px}
      .cta{display:flex;gap:10px;flex-wrap:wrap}
      .btn{
        background:var(--brand);
        color:#fff;
        border:0;
        border-radius:10px;
        padding:10px 14px;
        font-weight:600;
        text-decoration:none;
        display:inline-flex;
        align-items:center
      }
      .btn.secondary{
        background:transparent;
        color:var(--brand);
        border:1px solid var(--brand)
      }
      footer{
        text-align:center;
        padding:14px;
        font-size:13px;
        color:var(--muted);
        border-top:1px solid var(--ring)
      }
      footer a{color:var(--brand);text-decoration:none}
      footer a:hover{text-decoration:underline}
      .demo-badge{
        position:absolute;
        right:12px;
        top:12px;
        background:#f8d7da;
        color:#842029;
        border:1px solid #f5c2c7;
        border-radius:999px;
        padding:4px 8px;
        font-size:12px;
        box-shadow:0 2px 8px rgba(0,0,0,.08)
      }
    </style>
  </head>
  <body>
    <main class="card" role="main" aria-labelledby="msg-title">
      <?php if ($isDemo): ?><div class="demo-badge">DEMO</div><?php endif; ?>
      <header class="hdr">
        <div class="logo">MP</div>
        <h1 id="msg-title" class="title"><?= esc($title) ?></h1>
      </header>
      <section class="body">
        <p class="lead"><?= esc($lead) ?></p>
        <?php if ($detail !== ''): ?><p class="muted"><?= esc($detail) ?></p><?php endif; ?>
        <div class="cta"></div>
      </section>
      <footer>
        Powered by <a href="https://mpmg.co.uk" target="_blank" rel="noopener">Mount Pleasant Motoring Services Ltd</a> •
        <a href="mailto:controlroom@mountpleasantrecovery.co.uk" target="_blank" rel="noopener">controlroom@mountpleasantrecovery.co.uk</a>
      </footer>
    </main>
  </body>
  </html>
  <?php
  exit;
}

/* -------------------- main logic -------------------- */
$rawReg = trim($_GET['reg'] ?? ($_GET['registration'] ?? ''));
$reg    = normalize_reg($rawReg);

if ($reg === '') {
  render_message(400, 'Missing registration', 'Please contact your coordinator for a valid link.');
}

// basic sanity: UK plates are typically 2–8 chars; loosen as needed
if (strlen($reg) < 2 || strlen($reg) > 10) {
  render_message(400, 'Invalid registration', 'That registration looks incorrect.', 'Please check and try again.');
}

try {
  // 1) Try to reuse an existing live request for this reg + org + company
  $find = $pdo->prepare("
    SELECT *
    FROM requests
    WHERE organisation_id = ?
      AND company_id = ?
      AND UPPER(reg_mark) = UPPER(?)
      AND LOWER(status) IN ('open','submitted')
      AND (expires_at IS NULL OR expires_at > NOW())
    ORDER BY id DESC
    LIMIT 1
  ");
  $find->execute([$orgId, $companyId, $reg]);
  $req = $find->fetch();

  if ($req && !empty($req['token'])) {
    // Log a note that the magic link was reused
    try {
      $ip   = client_ip();
      $note = "Reused existing request via API for reg {$reg}; IP: {$ip}; org_id={$orgId}; company_id={$companyId}";
      $logStmt = $pdo->prepare("INSERT INTO request_notes (request_id, notes) VALUES (?, ?)");
      $logStmt->execute([$req['id'], $note]);
    } catch (Throwable $e) { /* ignore logging failures */ }

    header("Location: {$base}/public/upload.php?token=" . urlencode($req['token']), true, 302);
    exit;
  }

  // 2) Create a brand new request for this org + company
  $token     = uuidv4();
  $days      = (int)($config['request_expires_days'] ?? 2);
  $expiresAt = (new DateTime("+{$days} days"))->format('Y-m-d H:i:s');

  $ins = $pdo->prepare("
    INSERT INTO requests (organisation_id, company_id, token, reg_mark, status, expires_at, created_at)
    VALUES (?, ?, ?, ?, 'open', ?, NOW())
  ");
  $ins->execute([$orgId, $companyId, $token, $reg, $expiresAt]);

  $newId = (int)$pdo->lastInsertId();

  // Log creation note
  try {
    $ip   = client_ip();
    $note = "Request created via API for reg {$reg}; IP: {$ip}; org_id={$orgId}; company_id={$companyId}";
    $logStmt = $pdo->prepare("INSERT INTO request_notes (request_id, notes) VALUES (?, ?)");
    $logStmt->execute([$newId, $note]);
  } catch (Throwable $e) { /* ignore logging failures */ }

  // 3) Forward to upload.php with token
  header("Location: {$base}/public/upload.php?token=" . urlencode($token), true, 302);
  exit;

} catch (Throwable $e) {
  if (($config['env'] ?? 'prod') === 'dev') {
    render_message(500, 'Failed to create request', 'A server error occurred.', $e->getMessage());
  } else {
    render_message(500, 'Failed to create request', 'A server error occurred. Please try again.');
  }
}