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

$error = '';
$success = '';
$parkId = $_GET['id'] ?? null;

// Defaults
$parkName = $location = $description = $opened = '';
$is_family_friendly = '';
$areas = [];
$imagePath = null;

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

    if ($park) {
        $parkName = $park['name'];
        $location = $park['location'];
        $opened = $park['opened'];
        $is_family_friendly = $park['is_family_friendly'];
        $description = $park['description'];
        $imagePath = $park['image_path'];

        $stmtAreas = $pdo->prepare("SELECT * FROM park_areas WHERE park_id = ?");
        $stmtAreas->execute([$parkId]);
        $areas = $stmtAreas->fetchAll(PDO::FETCH_ASSOC);
    }
}

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'] ?? [];

    // Handle logo upload/remove
    if (!empty($_POST['remove_logo'])) {
        $imagePath = null;
    }

    if (!empty($_FILES['park_logo']) && $_FILES['park_logo']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/../uploads/parks/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

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

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

            if ($parkId) {
                // Update park
                $stmt = $pdo->prepare("UPDATE parks 
                    SET name=?, location=?, opened=?, is_family_friendly=?, description=?, image_path=? 
                    WHERE id=?");
                $stmt->execute([$parkName, $location, $opened, $is_family_friendly, $description, $imagePath, $parkId]);

                // Update park areas
                $existingAreas = $pdo->prepare("SELECT id, name FROM park_areas WHERE park_id = ?");
                $existingAreas->execute([$parkId]);
                $existing = $existingAreas->fetchAll(PDO::FETCH_KEY_PAIR); // id => name

                $usedIds = [];

                foreach ($areaNames as $index => $areaName) {
                    $areaName = trim($areaName);
                    if ($areaName === '') continue;

                    // Check if already exists
                    $foundId = array_search($areaName, $existing, true);
                    if ($foundId !== false) {
                        $usedIds[] = $foundId;
                        continue;
                    }

                    // Insert new area
                    $stmtArea = $pdo->prepare("INSERT INTO park_areas (park_id, name, image_path) VALUES (?, ?, ?)");
                    $stmtArea->execute([$parkId, $areaName, null]);
                    $usedIds[] = $pdo->lastInsertId();
                }

                // Delete removed areas
                if (!empty($existing)) {
                    $idsToDelete = array_diff(array_keys($existing), $usedIds);
                    if (!empty($idsToDelete)) {
                        $in = str_repeat('?,', count($idsToDelete) - 1) . '?';
                        $del = $pdo->prepare("DELETE FROM park_areas WHERE id IN ($in)");
                        $del->execute($idsToDelete);
                    }
                }
            } else {
                // Insert new park
                $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, $imagePath]);
                $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 = $parkId ? 'Park updated successfully!' : 'Park created successfully!';

            if (!$parkId) {
                $parkName = $location = $opened = $description = $is_family_friendly = '';
                $areas = [];
                $imagePath = null;
            }
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error = 'Database error: ' . htmlspecialchars($e->getMessage());
        }
    }
}
?>

<h1><?= $parkId ? 'Edit Park' : '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 class="form-label">Park Logo</label>
    <input type="file" name="park_logo" class="form-control" accept="image/*">
    <?php if ($imagePath): ?>
      <div style="margin-top:10px;">
        <img src="/<?= htmlspecialchars($imagePath) ?>" alt="Park Logo" style="max-width:150px;display:block;">
        <div class="form-check mt-2">
          <input type="checkbox" class="form-check-input" name="remove_logo" value="1" id="remove_logo">
          <label class="form-check-label" for="remove_logo">Remove Logo</label>
        </div>
      </div>
    <?php endif; ?>
  </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">
          <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']) ?>">
            <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">
          <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"><?= $parkId ? 'Update Park' : '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">
      <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>

