<?php
require_once 'includes/helpers.php';
require_once 'includes/header.php';
require_once 'includes/footer.php';

requireLogin();

$errors = [];
$success = false;

// Pre-select service from URL
$preService = $_GET['service'] ?? '';

// Fetch all services
$services = db()->query(
  'SELECT s.id, s.code, s.label, s.price_per_hour, a.available_slots
   FROM service_types s
   JOIN availability a ON a.service_type_id = s.id
   ORDER BY s.id'
)->fetchAll();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $svcId      = (int) ($_POST['service_type_id'] ?? 0);
  $checkIn    = trim($_POST['check_in'] ?? '');
  $checkOut   = trim($_POST['check_out'] ?? '');
  $vehicle    = trim($_POST['vehicle_number'] ?? '');
  $guests     = max(1, (int) ($_POST['guests'] ?? 1));
  $notes      = trim($_POST['notes'] ?? '');
  $driverId   = $_SESSION['driver_id'];

  // Validate
  if (!$svcId) $errors[] = 'Please select a service.';
  if (!$checkIn)  $errors[] = 'Check-in date/time is required.';
  if (!$checkOut) $errors[] = 'Check-out date/time is required.';
  if ($checkIn && $checkOut && strtotime($checkOut) <= strtotime($checkIn))
    $errors[] = 'Check-out must be after check-in.';

  if (empty($errors)) {
    // Calculate total
    $hrs   = (strtotime($checkOut) - strtotime($checkIn)) / 3600;
    $stmt  = db()->prepare('SELECT price_per_hour FROM service_types WHERE id = ?');
    $stmt->execute([$svcId]);
    $rate  = (float) ($stmt->fetchColumn() ?: 0);
    $total = $rate * $hrs;
    $ref   = generateRef();

    try {
      db()->beginTransaction();

      // Insert booking
      $ins = db()->prepare(
        'INSERT INTO bookings (driver_id, service_type_id, booking_ref, check_in, check_out, vehicle_number, guests, total_amount, notes)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
      );
      $ins->execute([$driverId, $svcId, $ref, $checkIn, $checkOut, $vehicle, $guests, $total, $notes]);

      // Decrement availability
      db()->prepare(
        'UPDATE availability SET available_slots = GREATEST(0, available_slots - 1) WHERE service_type_id = ?'
      )->execute([$svcId]);

      db()->commit();
      flash("Booking confirmed! Your reference is <strong>{$ref}</strong>. Total: ₹" . number_format($total, 2), 'success');
      header('Location: my-bookings.php');
      exit;
    } catch (Exception $e) {
      db()->rollBack();
      $errors[] = 'Booking failed: ' . $e->getMessage();
    }
  }
}

renderHeader('Book a Slot');
?>

<div class="page-hero">
  <div class="container">
    <span class="section-label">Reserve Your Space</span>
    <h1 class="section-title">Book a Slot</h1>
    <p class="section-sub" style="margin:0 auto;text-align:center">
      Quick, secure online booking. Confirmation is instant.
    </p>
  </div>
</div>

<section class="section">
  <div class="booking-wrap">

    <?php if ($errors): ?>
    <div style="background:rgba(224,81,81,0.1);border:1px solid var(--red);border-radius:8px;padding:16px 24px;margin-bottom:28px;color:var(--red);font-family:var(--font-cond)">
      <?php foreach ($errors as $e): ?><div>⚠ <?= h($e) ?></div><?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div class="form-card">
      <h2 style="font-family:var(--font-head);font-size:2rem;margin-bottom:8px">Booking Details</h2>
      <p style="color:var(--text-muted);font-size:0.92rem;margin-bottom:32px">All prices shown are per hour. Total is calculated automatically.</p>

      <form method="POST" action="booking.php">
        <div class="form-grid">

          <!-- Service -->
          <div class="form-group full">
            <label for="service_type_id">SERVICE TYPE *</label>
            <select id="service_type_id" name="service_type_id" required>
              <option value="">— Select a service —</option>
              <?php foreach ($services as $svc): ?>
              <option value="<?= $svc['id'] ?>"
                      data-rate="<?= $svc['price_per_hour'] ?>"
                      <?= ($preService === $svc['code'] || ($_POST['service_type_id'] ?? '') == $svc['id']) ? 'selected' : '' ?>>
                <?= h($svc['label']) ?>
                <?php if ($svc['price_per_hour'] > 0): ?>
                  — ₹<?= number_format($svc['price_per_hour'], 2) ?>/hr
                <?php else: ?>
                  — Complimentary
                <?php endif; ?>
                (<?= $svc['available_slots'] ?> slots available)
              </option>
              <?php endforeach; ?>
            </select>
          </div>

          <!-- Check-in -->
          <div class="form-group">
            <label for="check_in">CHECK-IN DATE & TIME *</label>
            <input type="datetime-local" id="check_in" name="check_in"
                   value="<?= h($_POST['check_in'] ?? '') ?>" required />
          </div>

          <!-- Check-out -->
          <div class="form-group">
            <label for="check_out">CHECK-OUT DATE & TIME *</label>
            <input type="datetime-local" id="check_out" name="check_out"
                   value="<?= h($_POST['check_out'] ?? '') ?>" required />
          </div>

          <!-- Vehicle Number -->
          <div class="form-group">
            <label for="vehicle_number">VEHICLE NUMBER</label>
            <input type="text" id="vehicle_number" name="vehicle_number"
                   placeholder="e.g. MH 12 AB 3456"
                   value="<?= h($_POST['vehicle_number'] ?? '') ?>" />
          </div>

          <!-- Guests -->
          <div class="form-group">
            <label for="guests">NUMBER OF PERSONS</label>
            <input type="number" id="guests" name="guests" min="1" max="10"
                   value="<?= h($_POST['guests'] ?? '1') ?>" />
          </div>

          <!-- Notes -->
          <div class="form-group full">
            <label for="notes">SPECIAL REQUESTS (OPTIONAL)</label>
            <textarea id="notes" name="notes" placeholder="Any special requirements..."><?= h($_POST['notes'] ?? '') ?></textarea>
          </div>

        </div>

        <!-- Total display -->
        <div style="background:rgba(245,166,35,0.06);border:1px solid rgba(245,166,35,0.2);border-radius:8px;padding:16px 24px;margin:24px 0;display:flex;align-items:center;justify-content:space-between">
          <span style="font-family:var(--font-cond);letter-spacing:2px;font-size:0.85rem;color:var(--text-muted)">ESTIMATED TOTAL</span>
          <span id="total_amount" style="font-family:var(--font-head);font-size:2rem;color:var(--amber)">—</span>
        </div>

        <button type="submit" class="btn btn-amber btn-lg" style="width:100%;justify-content:center">
          <i class="fa fa-calendar-check"></i> Confirm Booking
        </button>
      </form>
    </div>

    <p style="text-align:center;margin-top:20px;color:var(--text-muted);font-size:0.88rem">
      Want to see your past bookings? <a href="my-bookings.php">View My Bookings →</a>
    </p>
  </div>
</section>

<?php renderFooter(); ?>
