<?php
include 'admin-header.php';
require_once '../includes/image-resizer.php';

$message = '';
// --- ACTION HANDLING: ADD/EDIT/DELETE DESTINATIONS ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // --- DELETE DESTINATION ---
    if (isset($_POST['delete_destination'])) {
        $id_to_delete = intval($_POST['id']);
        // First, delete the associated image file
        $stmt_img = $conn->prepare("SELECT hero_image_url FROM destinations WHERE id = ?");
        $stmt_img->bind_param("i", $id_to_delete);
        $stmt_img->execute();
        if($row_img = $stmt_img->get_result()->fetch_assoc()) {
            if(!empty($row_img['hero_image_url']) && file_exists('../' . $row_img['hero_image_url'])) {
                unlink('../' . $row_img['hero_image_url']);
            }
        }
        $stmt_del = $conn->prepare("DELETE FROM destinations WHERE id = ?");
        $stmt_del->bind_param("i", $id_to_delete);
        $stmt_del->execute();
        $message = '<div class="alert alert-success">Destination guide deleted successfully.</div>';
    } 
    // --- SAVE (ADD/EDIT) DESTINATION ---
    elseif (isset($_POST['save_destination'])) {
        $id = intval($_POST['id'] ?? 0);
        $name = trim($_POST['name']);
        $short_description = trim($_POST['short_description']);
        $full_guide = $_POST['full_guide'];
        $hero_image_url = $_POST['current_image_url'] ?? '';

        // Handle image upload with resizing
        if (isset($_FILES['hero_image']) && $_FILES['hero_image']['error'] == 0) {
            $target_dir = "../uploads/destinations/";
            if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
            $target_file = $target_dir . "dest-" . uniqid() . basename($_FILES["hero_image"]["name"]);
            if (resizeImage($_FILES["hero_image"]["tmp_name"], $target_file, 1600, 900)) { // 16:9 ratio for hero images
                $hero_image_url = str_replace('../', '', $target_file);
            }
        }

        if ($id > 0) { // Update
            $stmt = $conn->prepare("UPDATE destinations SET name=?, short_description=?, full_guide=?, hero_image_url=? WHERE id=?");
            $stmt->bind_param("ssssi", $name, $short_description, $full_guide, $hero_image_url, $id);
            $message = '<div class="alert alert-success">Destination guide updated successfully.</div>';
        } else { // Insert
            $stmt = $conn->prepare("INSERT INTO destinations (name, short_description, full_guide, hero_image_url) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $name, $short_description, $full_guide, $hero_image_url);
            $message = '<div class="alert alert-success">New destination guide added successfully.</div>';
        }
        $stmt->execute();
        $stmt->close();
    }
}

// Fetch destination for editing if an ID is provided
$edit_dest = null;
if (isset($_GET['edit'])) {
    $stmt = $conn->prepare("SELECT * FROM destinations WHERE id = ?");
    $stmt->bind_param("i", $_GET['edit']);
    $stmt->execute();
    $edit_dest = $stmt->get_result()->fetch_assoc();
}
$tinymce_api_key = $site_settings['tinymce_api_key'] ?? 'no-api-key';
?>
<script src="https://cdn.tiny.cloud/1/<?php echo htmlspecialchars($tinymce_api_key); ?>/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>tinymce.init({ selector: '#fullGuideEditor', height: 500, plugins: 'code lists link image table', toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright | bullist numlist | code | table | link image'});</script>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Manage Destination Guides</h1>
</div>
<?php echo $message; ?>

<div class="card shadow-sm mb-4">
    <div class="card-header fw-bold"><?php echo $edit_dest ? 'Edit Destination Guide' : 'Add New Destination Guide'; ?></div>
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="id" value="<?php echo $edit_dest['id'] ?? 0; ?>">
            <div class="mb-3"><label>Destination Name</label><input type="text" name="name" class="form-control" placeholder="e.g., Palawan" value="<?php echo htmlspecialchars($edit_dest['name'] ?? ''); ?>" required></div>
            <div class="mb-3"><label>Short Description (for listing page)</label><textarea name="short_description" class="form-control" rows="3" required><?php echo htmlspecialchars($edit_dest['short_description'] ?? ''); ?></textarea></div>
            <div class="mb-3"><label>Full Guide Content</label><textarea id="fullGuideEditor" name="full_guide" class="form-control"><?php echo htmlspecialchars($edit_dest['full_guide'] ?? ''); ?></textarea></div>
            <div class="mb-3">
                <label>Hero Image</label><input type="file" name="hero_image" class="form-control" accept="image/*">
                <input type="hidden" name="current_image_url" value="<?php echo htmlspecialchars($edit_dest['hero_image_url'] ?? ''); ?>">
                <?php if (!empty($edit_dest['hero_image_url'])): ?><div class="mt-2"><small>Current:</small><br><img src="../<?php echo htmlspecialchars($edit_dest['hero_image_url']); ?>" style="max-height: 100px;" class="img-thumbnail"></div><?php endif; ?>
            </div>
            <button type="submit" name="save_destination" class="btn btn-primary"><?php echo $edit_dest ? 'Save Changes' : 'Add Guide'; ?></button>
            <?php if ($edit_dest): ?><a href="manage-destinations.php" class="btn btn-secondary">Cancel Edit</a><?php endif; ?>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header fw-bold">Existing Destination Guides</div>
    <div class="table-responsive">
        <table class="table table-hover align-middle">
            <thead class="table-dark"><tr><th>Image</th><th>Name</th><th>Actions</th></tr></thead>
            <tbody>
                <?php
                $result = $conn->query("SELECT * FROM destinations ORDER BY name ASC");
                while ($dest = $result->fetch_assoc()):
                ?>
                <tr>
                    <td><img src="../<?php echo htmlspecialchars($dest['hero_image_url']); ?>" alt="Hero Image" style="width: 150px; height: 80px; object-fit: cover;" class="img-thumbnail"></td>
                    <td><strong><?php echo htmlspecialchars($dest['name']); ?></strong></td>
                    <td>
                        <div class="btn-group">
                            <a href="?edit=<?php echo $dest['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                            <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure?');">
                                <input type="hidden" name="id" value="<?php echo $dest['id']; ?>">
                                <button type="submit" name="delete_destination" class="btn btn-sm btn-danger">Delete</button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include 'admin-footer.php'; ?>
