<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/layout.php';

$error = '';
$success = '';

$rideId = $_GET['id'] ?? null;
$rideId = $rideId ? (int)$rideId : null;

// Defaults
$park_id = '';
$area_id = null;
$name = '';
$avg_wait_time = null;
$description = '';
$min_height_cm = null;
$thrill_level = 'Moderate';
$duration_minutes = null;
$imagePath = null;
$wait_time_data_source = '';
$rating = null;
$featured = 0;

// Load parks + areas for dropdowns
$parksStmt = $pdo->query("SELECT id, name FROM parks ORDER BY name ASC");
$parks = $parksStmt->fetchAll(PDO::FETCH_ASSOC);

$areasStmt = $pdo->query("SELECT id, park_id, name FROM park_areas ORDER BY park_id ASC, name ASC");
$allAreas = $areasStmt->fetchAll(PDO::FETCH_ASSOC);

// Load ride if editing
if ($rideId) {
  $stmt = $pdo->prepare("SELECT * FROM rides WHERE id = ?");
  $stmt->execute([$rideId]);
  $ride = $stmt->fetch(PDO::FETCH_ASSOC);

  if ($ride) {
    $park_id = (int)$ride['park_id'];
    $area_id = $ride['area_id'] !== null ? (int)$ride['area_id'] : null;
    $name = $ride['name'] ?? '';
    $avg_wait_time = $ride['avg_wait_time'] !== null ? (int)$ride['avg_wait_time'] : null;
    $description = $ride['description'] ?? '';
    $min_height_cm = $ride['min_height_cm'] !== null ? (int)$ride['min_height_cm'] : null;
    $thrill_level = $ride['thrill_level'] ?? 'Moderate';
    $duration_minutes = $ride['duration_minutes'] !== null ? (int)$ride['duration_minutes'] : null;
    $imagePath = $ride['image_path'] ?? null;
    $wait_time_data_source = $ride['wait_time_data_source'] ?? '';
    $rating = $ride['rating'] !== null ? $ride['rating'] : null;
    $featured = !empty($ride['featured']) ? 1 : 0;
  } else {
    $error = "Ride not found.";
  }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $park_id = isset($_POST['park_id']) ? (int)$_POST['park_id'] : '';
  $area_id = isset($_POST['area_id']) && $_POST['area_id'] !== '' ? (int)$_POST['area_id'] : null;

  $name = trim($_POST['name'] ?? '');
  $avg_wait_time = ($_POST['avg_wait_time'] ?? '') !== '' ? (int)$_POST['avg_wait_time'] : null;
  $description = trim($_POST['description'] ?? '');
  $min_height_cm = ($_POST['min_height_cm'] ?? '') !== '' ? (int)$_POST['min_height_cm'] : null;
  $thrill_level = $_POST['thrill_level'] ?? 'Moderate';
  $duration_minutes = ($_POST['duration_minutes'] ?? '') !== '' ? (int)$_POST['duration_minutes'] : null;
  $wait_time_data_source = trim($_POST['wait_time_data_source'] ?? '');
  $rating = ($_POST['rating'] ?? '') !== '' ? (float)$_POST['rating'] : null;
  $featured = !empty($_POST['featured']) ? 1 : 0;

  // Remove image
  if (!empty($_POST['remove_image'])) {
    $imagePath = null;
  }

  // Upload image (optional)
  if (!empty($_FILES['ride_image']) && $_FILES['ride_image']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = __DIR__ . '/../uploads/rides/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

    $filename = uniqid('ride_', true) . '_' . basename($_FILES['ride_image']['name']);
    if (move_uploaded_file($_FILES['ride_image']['tmp_name'], $uploadDir . $filename)) {
      $imagePath = 'uploads/rides/' . $filename;
    }
  }

  // Basic validation
  $validThrills = ['Low', 'Moderate', 'High'];
  if (!$park_id || $name === '') {
    $error = 'Please fill in all required fields (Park + Ride Name).';
  } elseif (!in_array($thrill_level, $validThrills, true)) {
    $error = 'Invalid thrill level.';
  } else {
    try {
      if ($rideId) {
        $stmt = $pdo->prepare("
          UPDATE rides
          SET park_id = ?,
              area_id = ?,
              name = ?,
              avg_wait_time = ?,
              description = ?,
              min_height_cm = ?,
              thrill_level = ?,
              duration_minutes = ?,
              image_path = ?,
              wait_time_data_source = ?,
              rating = ?,
              featured = ?
          WHERE id = ?
        ");

        $stmt->execute([
          $park_id,
          $area_id,
          $name,
          $avg_wait_time,
          $description !== '' ? $description : null,
          $min_height_cm,
          $thrill_level,
          $duration_minutes,
          $imagePath,
          $wait_time_data_source !== '' ? $wait_time_data_source : null,
          $rating,
          $featured,
          $rideId
        ]);

        $success = 'Ride updated successfully!';
      } else {
        $stmt = $pdo->prepare("
          INSERT INTO rides
            (park_id, area_id, name, avg_wait_time, description, min_height_cm, thrill_level, duration_minutes, image_path, wait_time_data_source, rating, featured)
          VALUES
            (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->execute([
          $park_id,
          $area_id,
          $name,
          $avg_wait_time,
          $description !== '' ? $description : null,
          $min_height_cm,
          $thrill_level,
          $duration_minutes,
          $imagePath,
          $wait_time_data_source !== '' ? $wait_time_data_source : null,
          $rating,
          $featured
        ]);

        $rideId = (int)$pdo->lastInsertId();
        $success = 'Ride created successfully!';

        // Optional: redirect to edit mode after create
        // header("Location: ride_form.php?id=" . $rideId);
        // exit;
      }
    } catch (PDOException $e) {
      $error = 'Database error: ' . htmlspecialchars($e->getMessage());
    }
  }
}
?>

<h1><?= $rideId ? 'Edit Ride' : 'Create New Ride' ?></h1>

<div class="mb-3">
  <a href="rides.php" class="btn btn-link">&larr; Back to Rides</a>
</div>

<?php if ($error): ?>
  <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<?php if ($success): ?>
  <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>

<form method="post" enctype="multipart/form-data">
  <div class="mb-3">
    <label for="park_id" class="form-label">Park <span class="text-danger">*</span></label>
    <select name="park_id" id="park_id" class="form-control" required>
      <option value="">Select a park</option>
      <?php foreach ($parks as $p): ?>
        <option value="<?= (int)$p['id'] ?>" <?= ((string)$park_id !== '' && (int)$park_id === (int)$p['id']) ? 'selected' : '' ?>>
          <?= htmlspecialchars($p['name']) ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="mb-3">
    <label for="area_id" class="form-label">Area (optional)</label>
    <select name="area_id" id="area_id" class="form-control">
      <option value="">No area</option>
      <?php foreach ($allAreas as $a): ?>
        <option
          value="<?= (int)$a['id'] ?>"
          data-park-id="<?= (int)$a['park_id'] ?>"
          <?= ($area_id !== null && (int)$area_id === (int)$a['id']) ? 'selected' : '' ?>
        >
          <?= htmlspecialchars($a['name']) ?>
        </option>
      <?php endforeach; ?>
    </select>
    <small class="text-muted">Areas will filter based on the selected park.</small>
  </div>

  <div class="mb-3">
    <label for="name" class="form-label">Ride Name <span class="text-danger">*</span></label>
    <input type="text" name="name" id="name" class="form-control" required value="<?= htmlspecialchars($name) ?>">
  </div>

  <div class="mb-3">
    <label for="description" class="form-label">Description</label>
    <textarea name="description" id="description" class="form-control" rows="4"><?= htmlspecialchars($description) ?></textarea>
  </div>

  <div class="row">
    <div class="col-md-4 mb-3">
      <label for="thrill_level" class="form-label">Thrill Level</label>
      <select name="thrill_level" id="thrill_level" class="form-control">
        <?php foreach (['Low', 'Moderate', 'High'] as $t): ?>
          <option value="<?= $t ?>" <?= ($thrill_level === $t) ? 'selected' : '' ?>><?= $t ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="col-md-4 mb-3">
      <label for="min_height_cm" class="form-label">Min Height (cm)</label>
      <input type="number" name="min_height_cm" id="min_height_cm" class="form-control"
             value="<?= $min_height_cm !== null ? (int)$min_height_cm : '' ?>">
    </div>

    <div class="col-md-4 mb-3">
      <label for="duration_minutes" class="form-label">Duration (minutes)</label>
      <input type="number" name="duration_minutes" id="duration_minutes" class="form-control"
             value="<?= $duration_minutes !== null ? (int)$duration_minutes : '' ?>">
    </div>
  </div>

  <div class="row">
    <div class="col-md-4 mb-3">
      <label for="avg_wait_time" class="form-label">Avg Wait Time (minutes)</label>
      <input type="number" name="avg_wait_time" id="avg_wait_time" class="form-control"
             value="<?= $avg_wait_time !== null ? (int)$avg_wait_time : '' ?>">
    </div>

    <div class="col-md-4 mb-3">
      <label for="rating" class="form-label">Rating (0.0 - 9.9)</label>
      <input type="number" name="rating" id="rating" class="form-control" step="0.1" min="0" max="9.9"
             value="<?= $rating !== null ? htmlspecialchars($rating) : '' ?>">
    </div>

    <div class="col-md-4 mb-3 d-flex align-items-center">
      <div class="form-check mt-4">
        <input type="checkbox" class="form-check-input" name="featured" id="featured" value="1" <?= !empty($featured) ? 'checked' : '' ?>>
        <label class="form-check-label" for="featured">Featured</label>
      </div>
    </div>
  </div>

  <div class="mb-3">
    <label for="wait_time_data_source" class="form-label">Wait Time Data Source (optional)</label>
    <input type="text" name="wait_time_data_source" id="wait_time_data_source" class="form-control"
           value="<?= htmlspecialchars($wait_time_data_source) ?>">
  </div>

  <div class="mb-3">
    <label class="form-label">Ride Image</label>
    <input type="file" name="ride_image" class="form-control" accept="image/*">

    <?php if (!empty($imagePath)): ?>
      <div style="margin-top:10px;">
        <img src="/<?= htmlspecialchars($imagePath) ?>" alt="Ride Image" style="max-width:200px;display:block;">
        <div class="form-check mt-2">
          <input type="checkbox" class="form-check-input" name="remove_image" value="1" id="remove_image">
          <label class="form-check-label" for="remove_image">Remove Image</label>
        </div>
      </div>
    <?php endif; ?>
  </div>

  <button type="submit" class="btn btn-primary"><?= $rideId ? 'Update Ride' : 'Save Ride' ?></button>
</form>

<script>
(function() {
  const parkSelect = document.getElementById('park_id');
  const areaSelect = document.getElementById('area_id');

  function filterAreas() {
    const selectedParkId = parkSelect.value;
    const options = Array.from(areaSelect.options);

    // Always keep first "No area" option visible
    options.forEach((opt, idx) => {
      if (idx === 0) return;

      const optParkId = opt.getAttribute('data-park-id');
      const shouldShow = !selectedParkId || optParkId === selectedParkId;

      opt.hidden = !shouldShow;

      // If current selection becomes hidden, reset to "No area"
      if (opt.selected && !shouldShow) {
        areaSelect.value = '';
      }
    });
  }

  parkSelect.addEventListener('change', filterAreas);
  filterAreas(); // run once on load
})();
</script>