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

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

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

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

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

    // Keep entered areas if validation fails
    $areas = [];
    foreach ($areaNames as $areaName) {
        $areaName = trim($areaName);
        if ($areaName !== '') {
            $areas[] = ['name' => $areaName];
        }
    }

    // ----------------------
    // 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'];
        $fileExtension = strtolower(pathinfo($_FILES['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;
            $destPath = $uploadDir . $fileName;

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

    // ----------------------
    // VALIDATION
    // ----------------------
    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
            $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();

                // Insert park with slug and logo path
                $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,
                    $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 = '';
                $slug = '';
                $location = '';
                $opened = '';
                $description = '';
                $is_family_friendly = '';
                $areas = [];
            }
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $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="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 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.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"
                           required>
                    <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>