<?php
require_once __DIR__ . '/db.php';

header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');

$ref   = strtoupper(trim($_GET['ref'] ?? ''));
$type  = in_array($_GET['type'] ?? '', ['license','insurance']) ? $_GET['type'] : '';
$error = '';
$done  = false;
$booking = null;

if ($ref && $type) {
    $stmt = db()->prepare("SELECT id, name, email, booking_ref, rental_date, status FROM bookings WHERE booking_ref=?");
    $stmt->execute([$ref]);
    $booking = $stmt->fetch();
    if (!$booking)                         $error = 'Booking not found. Please check your confirmation email.';
    elseif ($booking['status'] === 'cancelled') $error = 'This booking has been cancelled.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $booking && !$error) {
    $file = $_FILES['doc'] ?? null;
    if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
        $error = 'Upload failed — please try again or check file size.';
    } else {
        $mime = detectAllowedMime($file['tmp_name']);
        if (!$mime) {
            $error = 'Only JPG, PNG, or PDF files are accepted.';
        } elseif ($file['size'] > 10 * 1024 * 1024) {
            $error = 'File must be under 10 MB.';
        } else {
            $ext  = ALLOWED_DOC_MIMES[$mime];
            $dir  = __DIR__ . '/uploads/' . $ref;
            if (!is_dir($dir)) mkdir($dir, 0750, true);
            $fname = $type . '_' . date('YmdHis') . '.' . $ext;
            $dest  = $dir . '/' . $fname;
            if (move_uploaded_file($file['tmp_name'], $dest)) {
                $col = $type === 'license' ? 'license_file' : 'insurance_file';
                $rel = 'uploads/' . $ref . '/' . $fname;
                db()->prepare("UPDATE bookings SET {$col}=? WHERE booking_ref=?")->execute([$rel, $ref]);

                $typeLabel = $type === 'license' ? "Driver's License" : 'Proof of Insurance';
                $dateLabel = date('F j, Y', strtotime($booking['rental_date']));
                $adminHtml = "<div style='font-family:Arial,sans-serif;max-width:560px;margin:0 auto'>
  <div style='background:#f97316;padding:18px;text-align:center'>
    <h1 style='color:#fff;margin:0;font-size:18px'>{$typeLabel} Uploaded — {$booking['booking_ref']}</h1>
  </div>
  <div style='padding:24px;background:#fff;border:1px solid #e5e7eb'>
    <p><strong>" . htmlspecialchars($booking['name']) . "</strong> uploaded their <strong>{$typeLabel}</strong> for booking <strong>{$booking['booking_ref']}</strong> (rental: {$dateLabel}).</p>
    <p style='margin-top:12px;font-size:13px;color:#6b7280'>View it in the admin panel under their booking detail.</p>
    <div style='margin-top:16px'><a href='" . SITE_URL . "/admin/' style='display:inline-block;background:#f97316;color:#fff;text-decoration:none;padding:10px 22px;border-radius:6px;font-weight:700;font-size:13px'>Open Admin Panel &rarr;</a></div>
  </div>
</div>";
                sendEmail(ADMIN_EMAIL, 'Parker Slingshot Admin', "{$typeLabel} Uploaded — {$booking['booking_ref']}: " . $booking['name'], $adminHtml);
                $done = true;
            } else {
                $error = 'Could not save file. Please try again.';
            }
        }
    }
}

$typeLabel = $type === 'license' ? "Driver's License" : ($type === 'insurance' ? 'Proof of Insurance' : '');
$dateLabel = $booking ? date('F j, Y', strtotime($booking['rental_date'])) : '';
?><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Upload Document — Parker County Slingshot Rentals</title>
  <meta name="robots" content="noindex,nofollow" />
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Barlow+Condensed:wght@700;800&display=swap" rel="stylesheet" />
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    :root { --orange: #f97316; --black: #0d0d0d; }
    body { font-family: 'Inter', sans-serif; background: #f3f4f6; color: #111; }
    header { background: var(--black); padding: 1.25rem 2rem; display: flex; align-items: center; justify-content: space-between; }
    header a { font-family: 'Barlow Condensed', sans-serif; font-size: 1.3rem; font-weight: 800; color: var(--orange); text-decoration: none; }
    header span { font-size: 0.85rem; color: rgba(255,255,255,0.4); }
    .wrap { max-width: 560px; margin: 2.5rem auto; padding: 0 1rem 4rem; }
    .card { background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.08); padding: 2rem 2.5rem; }
    @media (max-width: 560px) { .card { padding: 1.5rem; } }
    h1 { font-family: 'Barlow Condensed', sans-serif; font-size: 1.9rem; font-weight: 800; margin-bottom: 0.25rem; }
    .booking-badge { display: inline-block; background: #fff7ed; border: 1px solid #fed7aa; border-radius: 8px; padding: 0.6rem 1rem; margin: 1rem 0 1.5rem; }
    .booking-badge .ref { font-size: 1.1rem; font-weight: 700; color: var(--orange); }
    .booking-badge .meta { font-size: 0.82rem; color: #6b7280; margin-top: 2px; }
    .upload-area { border: 2px dashed #d1d5db; border-radius: 10px; padding: 2rem; text-align: center; cursor: pointer; transition: border-color .2s, background .2s; background: #fafafa; position: relative; margin: 1rem 0; }
    .upload-area:hover, .upload-area.drag { border-color: var(--orange); background: #fff7ed; }
    .upload-area input[type=file] { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%; }
    .upload-icon { font-size: 2.5rem; margin-bottom: 0.5rem; }
    .upload-area p { font-size: 0.9rem; color: #6b7280; margin: 0; }
    .upload-area .file-name { font-size: 0.88rem; color: var(--orange); font-weight: 600; margin-top: 0.5rem; display: none; }
    .btn { display: block; width: 100%; background: var(--orange); color: #fff; border: none; border-radius: 8px; padding: 0.9rem; font-size: 1rem; font-weight: 700; cursor: pointer; transition: background .2s; margin-top: 1rem; }
    .btn:hover { background: #ea580c; }
    .btn:disabled { background: #d1d5db; cursor: not-allowed; }
    .alert { padding: 0.85rem 1rem; border-radius: 8px; font-size: 0.9rem; margin-bottom: 1.25rem; }
    .alert-error { background: rgba(239,68,68,.08); border: 1px solid rgba(239,68,68,.25); color: #dc2626; }
    .success-icon { font-size: 3rem; text-align: center; margin-bottom: 1rem; }
    .success-box { text-align: center; padding: .5rem 0; }
    .success-box h1 { color: #16a34a; margin-bottom: 0.5rem; }
    .success-box p { color: #374151; font-size: 0.95rem; max-width: 400px; margin: 0 auto .75rem; }
    .hint { font-size: 0.8rem; color: #9ca3af; margin-top: 0.5rem; text-align: center; }
  </style>
</head>
<body>
<header>
  <a href="/">Parker County Slingshot Rentals</a>
  <span>Document Upload</span>
</header>
<div class="wrap">

<?php if (!$ref || !$type || (!$booking && !$error)): ?>
  <div class="card">
    <h1>Upload Document</h1>
    <p style="color:#6b7280;margin-top:.5rem">Invalid or missing upload link. Please use the link from your email or contact us.</p>
  </div>

<?php elseif ($error && !$booking): ?>
  <div class="card">
    <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
    <p style="color:#6b7280;font-size:.9rem">Need help? Call or text <strong>(817) 266-2022</strong>.</p>
  </div>

<?php elseif ($done): ?>
  <div class="card">
    <div class="success-icon">✅</div>
    <div class="success-box">
      <h1>Upload Received!</h1>
      <p>Thanks, <?= htmlspecialchars($booking['name']) ?>! Your <strong><?= htmlspecialchars($typeLabel) ?></strong> has been submitted for booking <strong><?= htmlspecialchars($booking['booking_ref']) ?></strong>.</p>
      <p style="color:#6b7280;font-size:.85rem">We'll review it and still do a quick visual check at pickup. See you on <?= htmlspecialchars($dateLabel) ?>!</p>
    </div>
  </div>

<?php else: ?>
  <?php if ($error): ?><div class="alert alert-error"><?= htmlspecialchars($error) ?></div><?php endif; ?>
  <div class="card">
    <h1>Upload <?= htmlspecialchars($typeLabel) ?></h1>
    <div class="booking-badge">
      <div class="ref"><?= htmlspecialchars($booking['booking_ref']) ?></div>
      <div class="meta"><?= htmlspecialchars($booking['name']) ?> &mdash; <?= htmlspecialchars($dateLabel) ?></div>
    </div>
    <p style="color:#374151;font-size:.9rem;margin-bottom:.25rem">
      <?php if ($type === 'insurance'): ?>
        Please upload a photo or scan of your current auto insurance card. JPG, PNG, or PDF accepted (max 10 MB).
      <?php else: ?>
        Please upload a photo or scan of the front of your driver's license. JPG, PNG, or PDF accepted (max 10 MB).
      <?php endif; ?>
    </p>
    <p style="color:#9ca3af;font-size:.8rem;margin-bottom:1rem">We'll still do a visual check at pickup — this is just for our records.</p>
    <form method="post" enctype="multipart/form-data" id="uploadForm">
      <div class="upload-area" id="dropZone">
        <input type="file" name="doc" id="docInput" accept=".jpg,.jpeg,.png,.pdf" required />
        <div class="upload-icon">📎</div>
        <p>Tap or drag your file here</p>
        <p style="font-size:.78rem;margin-top:4px">JPG &bull; PNG &bull; PDF &bull; max 10 MB</p>
        <div class="file-name" id="fileName"></div>
      </div>
      <button type="submit" class="btn" id="submitBtn">Upload <?= htmlspecialchars($typeLabel) ?></button>
    </form>
    <p class="hint">Your document is stored securely and only visible to Parker County Slingshot Rentals staff.</p>
  </div>
<?php endif; ?>

</div>
<script>
(function(){
  const input  = document.getElementById('docInput');
  const label  = document.getElementById('fileName');
  const zone   = document.getElementById('dropZone');
  const btn    = document.getElementById('submitBtn');
  if (!input) return;
  input.addEventListener('change', function() {
    if (this.files[0]) {
      label.textContent = this.files[0].name;
      label.style.display = 'block';
    }
  });
  ['dragover','dragenter'].forEach(e => zone.addEventListener(e, ev => { ev.preventDefault(); zone.classList.add('drag'); }));
  ['dragleave','drop'].forEach(e => zone.addEventListener(e, ev => zone.classList.remove('drag')));
  document.getElementById('uploadForm')?.addEventListener('submit', function() {
    if (btn) { btn.disabled = true; btn.textContent = 'Uploading…'; }
  });
})();
</script>
</body>
</html>
