<?php
require_once __DIR__ . '/../includes/auth.php';
require_login();

$id = isset($_GET['id']) ? (int) $_GET['id'] : null;
$isEdit = $id !== null;
$pageTitle = ($isEdit ? 'Edit' : 'Add') . ' Country';

$country = [];
if ($isEdit) {
    $stmt = db()->prepare('SELECT * FROM countries WHERE id = ?');
    $stmt->execute([$id]);
    $country = $stmt->fetch() ?: [];
    if (!$country) { http_response_code(404); die('Country not found.'); }
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $errors[] = 'Session expired, please try again.';
    } else {
        $name = trim($_POST['name'] ?? '');
        $slug = trim($_POST['slug'] ?? '') ?: slugify($name);

        $data = [
            'name' => $name,
            'slug' => slugify($slug),
            'tagline' => trim($_POST['tagline'] ?? ''),
            'short_description' => trim($_POST['short_description'] ?? ''),
            'why_points' => lines_to_json($_POST['why_points'] ?? ''),
            'cost_items' => cost_lines_to_json($_POST['cost_items'] ?? ''),
            'universities' => lines_to_json($_POST['universities'] ?? ''),
            'scholarships' => lines_to_json($_POST['scholarships'] ?? ''),
            'visa_steps' => lines_to_json($_POST['visa_steps'] ?? ''),
            'gallery_images' => lines_to_json($_POST['gallery_images'] ?? ''),
            'seo_title' => trim($_POST['seo_title'] ?? ''),
            'seo_description' => trim($_POST['seo_description'] ?? ''),
            'sort_order' => (int) ($_POST['sort_order'] ?? 0),
            'status' => in_array($_POST['status'] ?? '', ['active', 'inactive']) ? $_POST['status'] : 'active',
        ];
        $data['hero_image'] = handle_image_upload('hero_image', 'countries', $country['hero_image'] ?? null);

        if ($name === '') $errors[] = 'Country name is required.';

        if (!$errors) {
            $oldSlug = $country['slug'] ?? null;
            if ($isEdit) {
                $set = implode(', ', array_map(fn($k) => "$k = :$k", array_keys($data)));
                $stmt = db()->prepare("UPDATE countries SET $set WHERE id = :id");
                $data['id'] = $id;
                $stmt->execute($data);
            } else {
                $cols = implode(', ', array_keys($data));
                $ph = implode(', ', array_map(fn($k) => ":$k", array_keys($data)));
                $stmt = db()->prepare("INSERT INTO countries ($cols) VALUES ($ph)");
                $stmt->execute($data);
            }
            write_route_stub('study-abroad-', $data['slug'], 'study-abroad-single.php', $oldSlug);
            flash_set('success', 'Country page saved.');
            redirect('countries.php');
        } else {
            $country = array_merge($country, $data);
        }
    }
}

require __DIR__ . '/partials/header.php';
require __DIR__ . '/partials/sidebar.php';
require __DIR__ . '/partials/topbar.php';
?>

<?php if ($errors): ?>
  <div class="mb-6 px-4 py-3 rounded-xl bg-red-50 text-brand-red text-sm font-medium border border-red-200">
    <ul class="list-disc list-inside"><?php foreach ($errors as $err): ?><li><?= e($err) ?></li><?php endforeach; ?></ul>
  </div>
<?php endif; ?>

<form method="post" enctype="multipart/form-data" class="space-y-6 max-w-4xl">
  <?= csrf_field() ?>

  <div class="bg-white rounded-2xl shadow-sm p-6">
    <h2 class="font-heading font-bold text-lg mb-5"><i class="fa-solid fa-earth-americas text-brand-red mr-2"></i>Basics</h2>
    <div class="grid md:grid-cols-2 gap-5">
      <div><label class="block text-sm font-medium mb-1.5">Country Name <span class="text-brand-red">*</span></label>
        <input type="text" name="name" value="<?= e($country['name'] ?? '') ?>" required class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green"></div>
      <div><label class="block text-sm font-medium mb-1.5">Slug (leave blank to auto-generate)</label>
        <input type="text" name="slug" value="<?= e($country['slug'] ?? '') ?>" placeholder="e.g. australia" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green">
        <p class="text-xs text-gray-400 mt-1">Public URL: study-abroad-<?= e($country['slug'] ?? '{slug}') ?>.php</p></div>
      <div class="md:col-span-2"><label class="block text-sm font-medium mb-1.5">Tagline (shown in the page banner)</label>
        <input type="text" name="tagline" value="<?= e($country['tagline'] ?? '') ?>" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green"></div>
      <div class="md:col-span-2"><label class="block text-sm font-medium mb-1.5">Short Description (used on the Study Abroad hub card)</label>
        <textarea name="short_description" rows="2" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green"><?= e($country['short_description'] ?? '') ?></textarea></div>
      <div>
        <label class="block text-sm font-medium mb-1.5">Hero / Banner Image</label>
        <?php if (!empty($country['hero_image'])): ?><img src="<?= e(resolve_image($country['hero_image'])) ?>" class="h-20 rounded-lg mb-2 border"><?php endif; ?>
        <input type="file" name="hero_image" accept="image/*" class="w-full text-sm">
      </div>
      <div class="grid grid-cols-2 gap-4">
        <div><label class="block text-sm font-medium mb-1.5">Sort Order</label>
          <input type="number" name="sort_order" value="<?= e((string) ($country['sort_order'] ?? 0)) ?>" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green"></div>
        <div><label class="block text-sm font-medium mb-1.5">Status</label>
          <select name="status" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green">
            <option value="active" <?= ($country['status'] ?? 'active') === 'active' ? 'selected' : '' ?>>Active</option>
            <option value="inactive" <?= ($country['status'] ?? '') === 'inactive' ? 'selected' : '' ?>>Inactive</option>
          </select></div>
      </div>
    </div>
  </div>

  <div class="bg-white rounded-2xl shadow-sm p-6">
    <h2 class="font-heading font-bold text-lg mb-2"><i class="fa-solid fa-circle-check text-brand-green mr-2"></i>Why Study Here</h2>
    <p class="text-xs text-gray-400 mb-3">One point per line.</p>
    <textarea name="why_points" rows="5" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-green"><?= e(json_to_lines($country['why_points'] ?? '[]')) ?></textarea>
  </div>

  <div class="bg-white rounded-2xl shadow-sm p-6">
    <h2 class="font-heading font-bold text-lg mb-2"><i class="fa-solid fa-coins text-brand-gold mr-2"></i>Cost of Living</h2>
    <p class="text-xs text-gray-400 mb-3">One item per line, format: <code>icon|amount|label</code> &mdash; e.g. <code>fa-house|AUD 1,400-2,500/mo|Accommodation</code>. Icons are Font Awesome classes (fa-house, fa-utensils, fa-bus, etc.)</p>
    <textarea name="cost_items" rows="4" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-green"><?= e(json_to_cost_lines($country['cost_items'] ?? '[]')) ?></textarea>
  </div>

  <div class="bg-white rounded-2xl shadow-sm p-6">
    <h2 class="font-heading font-bold text-lg mb-2"><i class="fa-solid fa-university text-brand-red mr-2"></i>Popular Universities</h2>
    <p class="text-xs text-gray-400 mb-3">One university name per line.</p>
    <textarea name="universities" rows="4" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-green"><?= e(json_to_lines($country['universities'] ?? '[]')) ?></textarea>
  </div>

  <div class="bg-white rounded-2xl shadow-sm p-6">
    <h2 class="font-heading font-bold text-lg mb-2"><i class="fa-solid fa-award text-brand-gold mr-2"></i>Scholarships</h2>
    <p class="text-xs text-gray-400 mb-3">One scholarship per line.</p>
    <textarea name="scholarships" rows="3" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-green"><?= e(json_to_lines($country['scholarships'] ?? '[]')) ?></textarea>
  </div>

  <div class="bg-white rounded-2xl shadow-sm p-6">
    <h2 class="font-heading font-bold text-lg mb-2"><i class="fa-solid fa-passport text-brand-green mr-2"></i>Visa Process Steps</h2>
    <p class="text-xs text-gray-400 mb-3">One step per line, in order.</p>
    <textarea name="visa_steps" rows="6" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-green"><?= e(json_to_lines($country['visa_steps'] ?? '[]')) ?></textarea>
  </div>

  <div class="bg-white rounded-2xl shadow-sm p-6">
    <h2 class="font-heading font-bold text-lg mb-2"><i class="fa-solid fa-images text-brand-red mr-2"></i>Gallery Images</h2>
    <p class="text-xs text-gray-400 mb-3">One image reference per line &mdash; either an Unsplash photo id (e.g. <code>photo-1523482580672-f109ba8cb9be</code>) or an uploaded path (e.g. <code>uploads/countries/xxxx.jpg</code>).</p>
    <textarea name="gallery_images" rows="4" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-green"><?= e(json_to_lines($country['gallery_images'] ?? '[]')) ?></textarea>
  </div>

  <div class="bg-white rounded-2xl shadow-sm p-6">
    <h2 class="font-heading font-bold text-lg mb-5"><i class="fa-solid fa-magnifying-glass text-brand-gold mr-2"></i>Page SEO</h2>
    <div class="grid gap-5">
      <div><label class="block text-sm font-medium mb-1.5">SEO Title</label>
        <input type="text" name="seo_title" value="<?= e($country['seo_title'] ?? '') ?>" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green"></div>
      <div><label class="block text-sm font-medium mb-1.5">SEO Description</label>
        <textarea name="seo_description" rows="2" class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green"><?= e($country['seo_description'] ?? '') ?></textarea></div>
    </div>
  </div>

  <div class="flex items-center gap-3">
    <button type="submit" class="bg-gradient-to-r from-brand-red to-brand-green text-white font-semibold px-8 py-3 rounded-xl hover:brightness-110 transition">
      <i class="fa-solid fa-floppy-disk mr-2"></i>Save Country Page
    </button>
    <a href="countries.php" class="text-gray-500 text-sm font-medium hover:text-gray-700">Cancel</a>
  </div>
</form>

<?php require __DIR__ . '/partials/footer.php'; ?>
