<?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 = '';
$slug = '';
$location = '';
$description = '';
$opened = '';
$is_family_friendly = '';
$areas = [];
$imagePath = null;

// ----------------------
// SLUGIFY HELPER
// ----------------------
function slugify($text) {
    $text = trim((string)$text);
    $text = strtolower($text);
    $text = str_replace('&', 'and', $text);
    $text = preg_replace('/[^a-z0-9\s-]/', '', $text);
    $text = preg_replace('/\s+/', '-', $text);
    $text = preg_replace('/-+/', '-', $text);
    $text = trim($text, '-');

    return $text;
}

// 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'] ?? '';
        $slug = $park['slug'] ?? '';
        $location = $park['location'] ?? '';
        $opened = $park['opened'] ?? '';
        $is_family_friendly = $park['is_family_friendly'] ?? '';
        $description = $park['description'] ?? '';
        $imagePath = $park['image_path'] ?? null;

        $stmtAreas = $pdo->prepare("SELECT * FROM park_areas WHERE park_id = ?");
        $stmtAreas->execute([$parkId]);
        $areas = $stmtAreas->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $error = 'Park not found.';
    }
}

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

    // If slug is empty, create it from park name
    if ($slug === '') {
        $slug = slugify($parkName);
    } else {
        $slug = slugify($slug);
    }

    // Rebuild areas so they stay in the form if validation fails
    $areas = [];
    foreach ($areaNames as $areaName) {
        $areaName = trim($areaName);

        if ($areaName !== '') {
            $areas[] = ['name' => $areaName];
        }
    }

    // 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);
        }

        $fileExtension = strtolower(pathinfo($_FILES['park_logo']['name'], PATHINFO_EXTENSION));
        $allowedExtensions = ['jpg', 'jpeg', 'png', 'webp', 'gif'];

        if (!in_array($fileExtension, $allowedExtensions, true)) {
            $error = 'Invalid logo file type. Please upload a JPG, PNG, WEBP or GIF.';
        } else {
            $filename = uniqid('park_', true) . '.' . $fileExtension;

            if (move_uploaded_file($_FILES['park_logo']['tmp_name'], $uploadDir . $filename)) {
                $imagePath = 'uploads/parks/' . $filename;
            } else {
                $error = 'Failed to upload logo.';
            }
        }
    }

    if (!$parkName || !$location || $is_family_friendly === '' || !$description) {
        $error = 'Please fill in all required fields.';
    } elseif ($slug === '') {
        $error = 'Please add a valid slug.';
    } elseif (!$error) {
        try {
            // Check duplicate slug
            if ($parkId) {
                $checkStmt = $pdo->prepare("
                    SELECT COUNT(*)
                    FROM parks
                    WHERE slug = ?
                    AND id != ?
                ");
                $checkStmt->execute([$slug, $parkId]);
            } else {
                $checkStmt = $pdo->prepare("
                    SELECT COUNT(*)
                    FROM parks
                    WHERE slug = ?
                ");
                $checkStmt->execute([$slug]);
            }

            $slugExists = (int)$checkStmt->fetchColumn();

            if ($slugExists > 0) {
                $error = 'That slug is already in use. Please choose another one.';
            } else {
                $pdo->beginTransaction();

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

                    $stmt->execute([
                        $parkName,
                        $slug,
                        $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 $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, slug, location, opened, is_family_friendly, description, image_path) 
                        VALUES 
                            (?, ?, ?, ?, ?, ?, ?)
                    ");

                    $stmt->execute([
                        $parkName,
                        $slug,
                        $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!';

                // Reload areas after save
                if ($parkId) {
                    $stmtAreas = $pdo->prepare("
                        SELECT * 
                        FROM park_areas 
                        WHERE park_id = ?
                    ");
                    $stmtAreas->execute([$parkId]);
                    $areas = $stmtAreas->fetchAll(PDO::FETCH_ASSOC);
                }
            }
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $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="slug" class="form-label">Slug</label>
    <input type="text"
           name="slug"
           id="slug"
           class="form-control"
           required
           value="<?= htmlspecialchars($slug) ?>">
    <small class="text-muted">
      This will be used in the URL, for example: /park/alton-towers
    </small>
  </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(ltrim($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.addEventListener('DOMContentLoaded', function () {
    const parkNameInput = document.getElementById('park_name');
    const slugInput = document.getElementById('slug');
    const areaInputs = document.getElementById('areaInputs');

    function createSlug(value) {
        return value
            .toString()
            .toLowerCase()
            .trim()
            .replace(/&/g, 'and')
            .replace(/[^a-z0-9\s-]/g, '')
            .replace(/\s+/g, '-')
            .replace(/-+/g, '-')
            .replace(/^-+|-+$/g, '');
    }

    if (parkNameInput && slugInput) {
        parkNameInput.addEventListener('blur', function () {
            if (slugInput.value.trim() === '') {
                slugInput.value = createSlug(parkNameInput.value);
            }
        });

        slugInput.addEventListener('blur', function () {
            slugInput.value = createSlug(slugInput.value);
        });
    }

    if (areaInputs) {
        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);
            }

            if (e.target.classList.contains('remove-area')) {
                e.preventDefault();

                const row = e.target.closest('.area-row');

                if (row) {
                    row.remove();
                }
            }
        });
    }
});
</script>