<?php
include 'auth.php';
require_once '../config/db.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name         = trim($_POST['name'] ?? '');
    $country_code = strtoupper(trim($_POST['country_code'] ?? ''));
    $description  = trim($_POST['description'] ?? '');
    $show_home    = isset($_POST['show_home']) ? 1 : 0;

    if (empty($name)) {
        $error = 'Destination name is required.';
    } else {
        // Check for duplicate name
        $check = $conn->prepare("SELECT id FROM destinations WHERE name = ?");
        $check->bind_param("s", $name);
        $check->execute();
        $check->store_result();

        if ($check->num_rows > 0) {
            $error = "A destination named \"$name\" already exists.";
        } else {
            // Handle image upload
            $image_filename = '';
            if (!empty($_FILES['image']['name'])) {
                $allowed = ['jpg','jpeg','png','webp','gif'];
                $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                if (!in_array($ext, $allowed)) {
                    $error = 'Invalid image type. Allowed: jpg, jpeg, png, webp, gif';
                } elseif ($_FILES['image']['size'] > 5 * 1024 * 1024) {
                    $error = 'Image must be under 5 MB.';
                } else {
                    $image_filename = 'dest_' . time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $_FILES['image']['name']);
                    $upload_path = '../uploads/' . $image_filename;
                    if (!move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) {
                        $error = 'Failed to upload image.';
                        $image_filename = '';
                    }
                }
            }

            if (empty($error)) {
                $stmt = $conn->prepare("INSERT INTO destinations (name, country_code, description, image, show_home) VALUES (?, ?, ?, ?, ?)");
                if ($stmt) {
                    $stmt->bind_param("ssssi", $name, $country_code, $description, $image_filename, $show_home);
                    if ($stmt->execute()) {
                        header("Location: destinations.php?msg=saved");
                        exit;
                    } else {
                        $error = 'Database error: ' . $stmt->error;
                    }
                } else {
                    // Fallback for tables without country_code/description/show_home columns
                    $stmt2 = $conn->prepare("INSERT INTO destinations (name, image) VALUES (?, ?)");
                    if ($stmt2) {
                        $stmt2->bind_param("ss", $name, $image_filename);
                        if ($stmt2->execute()) {
                            header("Location: destinations.php?msg=saved");
                            exit;
                        } else {
                            $error = 'Database error: ' . $stmt2->error;
                        }
                    } else {
                        $error = 'Database prepare error: ' . $conn->error;
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Destination | Methsisila Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    <style>
        * { font-family: 'Inter', sans-serif; }
        body { background: #f0f2f5; margin: 0; }

        .admin-sidebar {
            position: fixed; top: 0; left: 0;
            width: 260px; height: 100vh;
            background: linear-gradient(180deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
            z-index: 100; padding: 30px 0;
            display: flex; flex-direction: column;
            box-shadow: 4px 0 20px rgba(0,0,0,0.3);
        }
        .sidebar-logo { text-align: center; padding: 0 20px 30px; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 20px; }
        .sidebar-logo img { height: 70px; filter: brightness(0) invert(1); }
        .sidebar-logo h6 { color: #aaa; font-size: 11px; text-transform: uppercase; letter-spacing: 3px; margin-top: 8px; }
        .sidebar-nav a { display: flex; align-items: center; padding: 12px 25px; color: rgba(255,255,255,0.65); text-decoration: none; font-size: 14px; font-weight: 500; transition: 0.3s; gap: 12px; border-left: 3px solid transparent; }
        .sidebar-nav a:hover, .sidebar-nav a.active { color: #fff; background: rgba(255,255,255,0.08); border-left-color: #ff6900; }
        .sidebar-nav a i { width: 20px; text-align: center; font-size: 15px; }
        .sidebar-section { padding: 15px 25px 5px; color: rgba(255,255,255,0.3); font-size: 10px; text-transform: uppercase; letter-spacing: 2px; }
        .sidebar-bottom { margin-top: auto; padding: 20px 25px; border-top: 1px solid rgba(255,255,255,0.1); }
        .sidebar-bottom a { display: flex; align-items: center; gap: 10px; color: rgba(255,255,255,0.6); text-decoration: none; font-size: 14px; padding: 10px; border-radius: 10px; transition: 0.3s; }
        .sidebar-bottom a:hover { color: #fff; background: rgba(255,0,0,0.2); }

        .admin-main { margin-left: 260px; min-height: 100vh; padding: 30px; }
        .admin-topbar { display: flex; justify-content: space-between; align-items: center; background: #fff; border-radius: 16px; padding: 15px 25px; margin-bottom: 30px; box-shadow: 0 2px 20px rgba(0,0,0,0.06); }

        .form-card { background: #fff; border-radius: 20px; padding: 35px; box-shadow: 0 4px 20px rgba(0,0,0,0.06); }
        .form-label { font-weight: 600; font-size: 13px; color: #444; margin-bottom: 8px; }
        .form-control, .form-select { border-radius: 12px; border: 1px solid #eee; padding: 12px 16px; font-size: 14px; background: #fafafa; }
        .form-control:focus, .form-select:focus { border-color: #ff6900; box-shadow: 0 0 0 3px rgba(255,105,0,0.12); background: #fff; }

        /* Drag & Drop Image Upload */
        .img-upload-zone {
            border: 2px dashed #ddd; border-radius: 16px;
            padding: 40px; text-align: center; cursor: pointer;
            transition: 0.3s; background: #fafafa; position: relative;
        }
        .img-upload-zone:hover, .img-upload-zone.drag-over {
            border-color: #ff6900; background: #fff8f4;
        }
        .img-upload-zone input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; }
        #img-preview { max-width: 100%; max-height: 250px; border-radius: 12px; margin-top: 15px; display: none; object-fit: cover; }

        .btn-save { background: #ff6900; color: #fff; border: none; border-radius: 12px; padding: 14px 40px; font-weight: 700; font-size: 15px; transition: 0.3s; }
        .btn-save:hover { background: #e55d00; color: #fff; transform: translateY(-2px); box-shadow: 0 8px 20px rgba(255,105,0,0.3); }

        @media(max-width: 768px) { .admin-sidebar { width: 0; overflow: hidden; } .admin-main { margin-left: 0; padding: 15px; } }
    </style>
</head>
<body>

<!-- Sidebar -->
<div class="admin-sidebar">
    <div class="sidebar-logo">
        <img src="../assets/img/logo.png" alt="Logo" onerror="this.style.display='none'">
        <h6>Admin Panel</h6>
    </div>
    <div class="sidebar-nav">
        <a href="index.php"><i class="fas fa-home"></i> Dashboard</a>

        <div class="sidebar-section" style="padding-top:20px;">Tour Management</div>
        <a href="packages.php"><i class="fas fa-globe"></i> International Tours</a>
        <a href="add-package.php"><i class="fas fa-plus-circle"></i> Add Tour</a>
        <a href="local-tours.php"><i class="fas fa-map-marked-alt"></i> Local Tours</a>
        <a href="add-local-tour.php"><i class="fas fa-plus"></i> Add Local Tour</a>

        <div class="sidebar-section" style="padding-top:20px;">Homepage</div>
        <a href="destinations.php"><i class="fas fa-map-pin"></i> Destinations</a>
        <a href="add-destination.php" class="active"><i class="fas fa-plus-circle"></i> Add Destination</a>

        <div class="sidebar-section" style="padding-top:20px;">Media</div>
        <a href="manage-gallery.php"><i class="fas fa-images"></i> Gallery Manager</a>

        <div class="sidebar-section" style="padding-top:20px;">Site</div>
        <a href="../index.php" target="_blank"><i class="fas fa-external-link-alt"></i> View Website</a>
    </div>
    <div class="sidebar-bottom">
        <a href="logout.php"><i class="fas fa-sign-out-alt text-danger"></i> Logout</a>
    </div>
</div>

<!-- Main Content -->
<div class="admin-main">
    <div class="admin-topbar">
        <div>
            <h5 class="fw-bold mb-0">Add New Destination</h5>
            <p class="text-muted small mb-0">This destination will appear on the homepage grid</p>
        </div>
        <a href="destinations.php" class="btn btn-outline-secondary rounded-pill px-4">
            <i class="fas fa-arrow-left me-2"></i>Back to List
        </a>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-danger rounded-4 mb-4"><i class="fas fa-exclamation-circle me-2"></i><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">
        <div class="row g-4">
            <!-- Left Column -->
            <div class="col-lg-8">
                <div class="form-card">
                    <h6 class="fw-bold mb-4" style="color:#333;">Destination Details</h6>

                    <div class="mb-4">
                        <label class="form-label">Destination Name <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control" placeholder="e.g. Japan, Maldives, Greece" required value="<?= htmlspecialchars($_POST['name'] ?? '') ?>">
                        <div class="form-text mt-1">This name appears as the card title on the homepage.</div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label">Country Code <span class="text-muted fw-normal">(optional)</span></label>
                        <input type="text" name="country_code" class="form-control" maxlength="3" placeholder="e.g. JP, MV, GR" value="<?= htmlspecialchars($_POST['country_code'] ?? '') ?>" style="text-transform:uppercase;">
                        <div class="form-text mt-1">2–3 letter country code used for search filters.</div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label">Short Description <span class="text-muted fw-normal">(optional)</span></label>
                        <textarea name="description" class="form-control" rows="3" placeholder="A brief description shown on the destination card tooltip or detail page..."><?= htmlspecialchars($_POST['description'] ?? '') ?></textarea>
                    </div>

                    <div class="form-check form-switch mb-2">
                        <input class="form-check-input" type="checkbox" name="show_home" id="showHome" checked style="width:40px;height:22px;">
                        <label class="form-check-label ms-2 fw-semibold" for="showHome">Show on Homepage</label>
                    </div>
                    <div class="form-text mb-0">Toggle to hide this destination from the public homepage without deleting it.</div>
                </div>
            </div>

            <!-- Right Column -->
            <div class="col-lg-4">
                <div class="form-card">
                    <h6 class="fw-bold mb-4" style="color:#333;">Destination Image</h6>

                    <div class="img-upload-zone" id="upload-zone">
                        <input type="file" name="image" id="img-input" accept="image/*">
                        <i class="fas fa-cloud-upload-alt fa-2x mb-3" style="color:#ff6900;"></i>
                        <p class="fw-semibold mb-1" style="color:#333;">Click or drag to upload</p>
                        <p class="text-muted small mb-0">JPG, PNG, WEBP up to 5 MB</p>
                        <img id="img-preview" src="" alt="Preview">
                    </div>
                    <div class="form-text mt-2">This image appears as the card background on the homepage grid. Recommended: 800×600px landscape.</div>
                </div>

                <div class="mt-3 d-grid">
                    <button type="submit" class="btn-save btn w-100">
                        <i class="fas fa-check me-2"></i>Save Destination
                    </button>
                </div>
                <div class="mt-2 d-grid">
                    <a href="destinations.php" class="btn btn-outline-secondary rounded-3 py-3">Cancel</a>
                </div>
            </div>
        </div>
    </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
const input = document.getElementById('img-input');
const preview = document.getElementById('img-preview');
const zone = document.getElementById('upload-zone');

input.addEventListener('change', function() {
    if (this.files && this.files[0]) {
        const reader = new FileReader();
        reader.onload = e => {
            preview.src = e.target.result;
            preview.style.display = 'block';
        };
        reader.readAsDataURL(this.files[0]);
    }
});

zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
zone.addEventListener('drop', e => {
    e.preventDefault();
    zone.classList.remove('drag-over');
    if (e.dataTransfer.files.length) {
        input.files = e.dataTransfer.files;
        const reader = new FileReader();
        reader.onload = ev => { preview.src = ev.target.result; preview.style.display = 'block'; };
        reader.readAsDataURL(e.dataTransfer.files[0]);
    }
});

// Auto-uppercase country code
document.querySelector('[name="country_code"]').addEventListener('input', function() {
    this.value = this.value.toUpperCase();
});
</script>
</body>
</html>
