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

$error = '';
$success = '';
$parkName = $location = $description = $opened = $is_family_friendly = '';
$areas = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $parkName = $_POST['park_name'] ?? '';
    $location = $_POST['location'] ?? '';
    $opened = $_POST['opened'] ?? '';
    $is_family_friendly = isset($_POST['is_family_friendly']) ? (int) $_POST['is_family_friendly'] : '';
    $description = $_POST['description'] ?? '';
    $areaNames = $_POST['areas']['name'] ?? [];

    // File upload handling
    $logoPath = null;
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/../uploads/parks/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $fileTmp = $_FILES['logo']['tmp_name'];
        $fileName = uniqid('park_', true) . '.' . pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
        $destPath = $uploadDir . $fileName;

        if (move_uploaded_file($fileTmp, $destPath)) {
            $logoPath = 'uploads/parks/' . $fileName; // relative path for DB
        } else {
            $error = 'Failed to upload logo.';
        }
    }

    if (!$parkName || !$location || $is_family_friendly === '' || !$description) {
        $error = 'Please fill in all required fields.';
    } elseif (!$error) {
        try {
            $pdo->beginTransaction();

            // Insert park with logo path
            $stmt = $pdo->prepare("INSERT INTO parks (name, location, opened, is_family_friendly, description, image_path) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$parkName, $location, $opened, $is_family_friendly, $description, $logoPath]);
            $parkId = $pdo->lastInsertId();

            // Insert areas
            $stmtArea = $pdo->prepare("INSERT INTO park_areas (park_id, name, image_path) VALUES (?, ?, ?)");
            foreach ($areaNames as $areaName) {
                $areaName = trim($areaName);
                if ($areaName === '') continue;
                $stmtArea->execute([$parkId, $areaName, null]);
            }

            $pdo->commit();
            $success = 'Park and areas saved successfully!';

            // Clear form
            $parkName = $location = $opened = $description = $is_family_friendly = '';
            $areas = [];
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error = 'Database error: ' . htmlspecialchars($e->getMessage());
        }
    }
}
?>

<h1>Create New Park</h1>

<?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_name" class="form-label">Park Name</label>
    <input type="text" name="park_name" id="park_name" class="form-control" required value="<?= htmlspecialchars($parkName) ?>">
  </div>

  <div class="mb-3">
    <label for="location" class="form-label">Location</label>
    <input type="text" name="location" id="location" class="form-control" required value="<?= htmlspecialchars($location) ?>">
  </div>

  <div class="mb-3">
    <label for="opened" class="form-label">Year Opened</label>
    <input type="text" name="opened" id="opened" class="form-control" required value="<?= htmlspecialchars($opened) ?>">
  </div>

  <div class="mb-3">
    <label for="is_family_friendly" class="form-label">Family Friendly</label>
    <select name="is_family_friendly" id="is_family_friendly" class="form-control" required>
      <option value="">Select an option</option>
      <option value="1" <?= ($is_family_friendly === '1' || $is_family_friendly === 1) ? 'selected' : '' ?>>Yes</option>
      <option value="0" <?= ($is_family_friendly === '0' || $is_family_friendly === 0) ? 'selected' : '' ?>>No</option>
    </select>
  </div>

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

  <div class="mb-3">
    <label for="logo" class="form-label">Park Logo</label>
    <input type="file" name="logo" id="logo" class="form-control" accept="image/*">
  </div>

  <div class="mb-3">
    <label class="form-label">Park Areas</label>
    <div id="areaInputs">
      <?php if (empty($areas)): ?>
        <div class="input-group mb-2 area-row">
          <input type="text" name="areas[name][]" class="form-control" placeholder="Area Name" required>
          <button type="button" class="btn btn-outline-secondary add-area" style="margin-left:10px;">+</button>
        </div>
      <?php else: ?>
        <?php foreach ($areas as $area): ?>
          <div class="input-group mb-2 area-row">
            <input type="text" name="areas[name][]" class="form-control" value="<?= htmlspecialchars($area['name']) ?>" required>
            <button type="button" class="btn btn-outline-danger remove-area" style="margin-left:10px;">&minus;</button>
          </div>
        <?php endforeach; ?>
        <div class="input-group mb-2 area-row">
          <input type="text" name="areas[name][]" class="form-control" placeholder="Area Name" required>
          <button type="button" class="btn btn-outline-secondary add-area" style="margin-left:10px;">+</button>
        </div>
      <?php endif; ?>
    </div>
  </div>

  <button type="submit" class="btn btn-primary">Save Park</button>
</form>

<script>
document.getElementById('areaInputs').addEventListener('click', function(e) {
  if (e.target.classList.contains('add-area')) {
    e.preventDefault();
    const wrapper = document.createElement('div');
    wrapper.className = 'input-group mb-2 area-row';
    wrapper.innerHTML = `
      <input type="text" name="areas[name][]" class="form-control" placeholder="Area Name" required>
      <button type="button" class="btn btn-outline-danger remove-area" style="margin-left:10px;">&minus;</button>
    `;
    this.appendChild(wrapper);
  } else if (e.target.classList.contains('remove-area')) {
    e.preventDefault();
    e.target.closest('.area-row').remove();
  }
});
</script>
