<?php
// /admin/create.php

session_start();

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

// dev error display
if (($config['env'] ?? null) === 'dev') {
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);
}

$base = rtrim($config['base_url'] ?? '', '/');

// 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;
$isOrgAdmin = !empty($me['is_org_admin']);

if ($orgId <= 0) {
  http_response_code(403);
  echo "<p>Forbidden: no organisation scope.</p>";
  exit;
}

// Determine target company for this request
$targetOrgId     = $orgId;
$targetCompanyId = 0;

if ($isOrgAdmin) {
  // Org admin: use active_company_id (set from index.php scope selector)
  $activeCompanyId = isset($_SESSION['active_company_id']) ? (int)$_SESSION['active_company_id'] : 0;

  if ($activeCompanyId > 0) {
    // Validate that company belongs to this org
    $stmt = $pdo->prepare("SELECT id FROM companies WHERE id = ? AND organisation_id = ?");
    $stmt->execute([$activeCompanyId, $orgId]);
    if ($stmt->fetchColumn()) {
      $targetCompanyId = $activeCompanyId;
    }
  }

  if ($targetCompanyId <= 0) {
    http_response_code(400);
    echo "<h1>Cannot create request</h1>";
    echo "<p>Please select a company in the dashboard (Company scope) before generating a link.</p>";
    echo "<p><a href='index.php'>&larr; Back to Admin</a></p>";
    exit;
  }
} else {
  // Normal user: fixed to their company
  if ($companyId <= 0) {
    http_response_code(403);
    echo "<p>No company is associated with your account.</p>
          <p><a href='index.php'>&larr; Back</a></p>";
    exit;
  }
  $targetCompanyId = $companyId;
}

// ---- existing form input handling ----
$reg   = strtoupper(trim($_POST['reg_mark'] ?? ''));
$name  = trim($_POST['customer_name'] ?? '');
$email = trim($_POST['customer_email'] ?? '');
$days  = trim($_POST['days'] ?? '');

if ($reg === '') {
  http_response_code(400);
  echo "<p>Vehicle Registration is required.</p><p><a href='index.php'>&larr; Back</a></p>";
  exit;
}

if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  http_response_code(400);
  echo "<p>Customer email looks invalid.</p><p><a href='index.php'>&larr; Back</a></p>";
  exit;
}

$token   = uuidv4();
$expires = null;
if ($days !== '' && ctype_digit($days)) {
  $expires = (new DateTimeImmutable('now'))
              ->modify('+' . (int)$days . ' days')
              ->format('Y-m-d H:i:s');
}

// Insert (same as we had, but using target org + company)
try {
  $stmt = $pdo->prepare(
    "INSERT INTO requests (
        organisation_id,
        company_id,
        token,
        reg_mark,
        customer_name,
        customer_email,
        expires_at
     ) VALUES (?,?,?,?,?,?,?)"
  );
  $stmt->execute([
    $targetOrgId,
    $targetCompanyId,
    $token,
    $reg,
    ($name !== '' ? $name : null),
    ($email !== '' ? $email : null),
    $expires
  ]);
} catch (Throwable $e) {
  http_response_code(500);
  echo "<h1>Couldn’t create request</h1>";
  echo "<p>There was a problem saving to the database.</p>";
  if (($config['env'] ?? null) === 'dev') {
    echo "<pre>" . htmlspecialchars($e->getMessage()) . "</pre>";
  }
  echo "<p><a href='index.php'>&larr; Back</a></p>";
  exit;
}

// ... keep the rest of your email + HTML response exactly as in the previous version ...


$link = rtrim($config['base_url'] ?? '', '/') . '/public/upload.php?token=' . $token;

/** -----------------------------
 *  Email the customer (if given)
 *  ----------------------------- */
$emailError = null;
if ($email !== '') {
  $prettyName = $name !== '' ? $name : 'Customer';

  $expiryLine = '';
  if (!empty($expires)) {
    $expiryLine = "This link will expire on " . (new DateTimeImmutable($expires))->format('j M Y, H:i') . ".";
  }

  $brand = $config['mail']['from_name'] ?? 'Images | Towlens';
  $subject = "Upload Photos for " . $reg;

  $html = '
    <div style="font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;font-size:16px;line-height:1.5;color:#111">
      <p>Hi ' . esc($prettyName) . ',</p>
      <p>We\'ve created a secure link for you to upload photos for vehicle registration <strong>' . esc($reg) . '</strong>.</p>
      <p><a href="' . esc($link) . '" style="display:inline-block;padding:10px 16px;background:#0f6fff;color:#fff;text-decoration:none;border-radius:6px;">Upload your photos</a></p>
      <p>Or copy this link into your browser:<br><span style="word-break:break-all;">' . esc($link) . '</span></p>
      <p>' . esc($expiryLine) . '</p>
      <hr style="border:none;border-top:1px solid #e5e7eb;margin:16px 0" />
      <p style="color:#6b7280;font-size:14px;margin:0">' . esc($brand) . '</p>
    </div>';

  $text = "Hi {$prettyName},\n\n"
        . "We’ve created a secure link for you to upload photos for vehicle registration {$reg}.\n\n"
        . "Upload link: {$link}\n"
        . ($expiryLine !== '' ? "\n{$expiryLine}\n" : "\n")
        . "{$brand}\n";

  // Use shared mailer (respects config.php)
  [$ok, $err] = mpms_mail_send_for_org($pdo, $targetOrgId, $email, $subject, $html, $text, $config);
  if (!$ok) {
    $emailError = ($config['env'] ?? null) === 'dev'
      ? $err
      : 'Email could not be sent.';
  }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Request Created — Admin</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    :root{
      --bg:#eceff3; --win:#ffffff; --ink:#1f2933; --muted:#5d6b78; --line:#cfd6de;
      --brand:#2f6db2; --brand-dark:#255a95; --ok:#2f7d3d; --danger:#b22f2f;
      --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);
    }
    *{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:1100px; 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}
    .mark{width:26px; height:26px; border-radius:4px; background:#2f6db2; box-shadow:inset 0 0 0 1px rgba(255,255,255,.5)}
    h1{font-size:16px; margin:0}
    .sub{font-size:12px; color:var(--muted)}
    .container{max-width:1100px; margin:16px auto 24px; padding:0 14px; width:100%}
    .panel{background:#fff; border:1px solid var(--line); border-radius:var(--radius); box-shadow:var(--shadow); padding:12px; margin-top:14px}
    .ok{background:#eaf4ea; border:1px solid #bcd8bc; color:#1e4b1e; padding:10px; border-radius:4px; margin-top:10px}
    .err{background:#fae7e7; border:1px solid #e3b1b1; color:#7f2020; padding:10px; border-radius:4px; margin-top:10px}
    .muted{color:var(--muted); font-size:12px}
    .btn{appearance:none; border:1px solid #bfc8d2; background:var(--btn-grad); color:#123; 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.small{padding:4px 8px; font-size:12px}
    .aslink{background:none; border:0; padding:0; margin:0; font:inherit; color:#2f6db2; text-decoration:underline; cursor:pointer}
    .aslink:hover{text-decoration:none}
    .row{display:flex; gap:10px; align-items:center; flex-wrap:wrap}
    .mono{font-family:Consolas,"Courier New",monospace; word-break:break-all}
    html, body, .app, * {
      -webkit-user-select:none; -moz-user-select:none; -ms-user-select:none; user-select:none;
      -webkit-touch-callout:none;
    }
  </style>
</head>
<body>
<div class="app">
  <div class="ribbon">
    <div class="ribbon-inner">
      <div class="title">
        <div class="mark" aria-hidden="true"></div>
        <div>
          <h1>Request created</h1>
          <div class="sub">Share the upload link with the customer</div>
        </div>
      </div>
      <div class="actions" style="display:flex; gap:8px">
        <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/index.php">Dashboard</button>
        <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/settings.php">Settings</button>
      </div>
    </div>
  </div>

  <div class="container">
    <section class="panel">
      <div class="row">
        <div><strong>Reg:</strong></div>
        <div><?= esc($reg) ?></div>
      </div>

      <div class="row" style="margin-top:8px">
        <div><strong>Link:</strong></div>
        <div class="mono" id="theLink"><?= esc($link) ?></div>
      </div>

      <div class="row" style="margin-top:8px">
        <button type="button" class="btn primary small" data-open="<?= esc($link) ?>">Open link</button>
        <button type="button" class="btn small" data-copy="<?= esc($link) ?>">Copy link</button>
      </div>

      <p class="muted" style="margin-top:8px">Copy and send this link to the customer.</p>

      <?php if ($email !== ''): ?>
        <?php if ($emailError === null): ?>
          <div class="ok">An email with the link has been sent to <strong><?= esc($email) ?></strong>.</div>
        <?php else: ?>
          <div class="err">
            We couldn’t send the email to <strong><?= esc($email) ?></strong>.
            <div class="muted"><?= esc($emailError) ?></div>
          </div>
        <?php endif; ?>
      <?php else: ?>
        <p class="muted">No customer email was provided, so no email was sent.</p>
      <?php endif; ?>

      <div class="row" style="margin-top:12px">
        <button type="button" class="aslink" data-nav="index.php">&larr; Back to Admin</button>
      </div>
    </section>
  </div>
</div>

<script>
  document.addEventListener('click', (e) => {
    const nav = e.target.closest('[data-nav]');
    if (nav) {
      window.location.assign(nav.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) {
      const text = copyBtn.getAttribute('data-copy');
      try {
        if (navigator.clipboard && navigator.clipboard.writeText) {
          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 (err) {
        console.log(err);
      }
      return;
    }
  });

  window.addEventListener('contextmenu', e => e.preventDefault(), { capture: true });
</script>
</body>
</html>
