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

// --- CONFIGURATION & SETUP ---
define('UPLOAD_BASE_PATH', realpath(__DIR__ . '/../uploads') . '/');
$message = '';
// Determine if we are in an "add" or "edit" context
$is_editing_or_adding = isset($_GET['edit']);
$item_id_context = intval($_GET['edit'] ?? $_POST['id'] ?? 0);

// --- ACTION HANDLING ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Determine the action from the submitted button's name
    $action = isset($_POST['save_destination']) ? 'save_destination' : (isset($_POST['delete_destination']) ? 'delete_destination' : '');

    switch ($action) {
        // --- ACTION: SAVE (ADD/EDIT) A DESTINATION ---
        case 'save_destination':
            $id = intval($_POST['id'] ?? 0);
            $name = trim($_POST['name']);
            $province = trim($_POST['province']);
            $description = trim($_POST['description']);
            $image_url = $_POST['current_image'] ?? '';

            if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
                $upload_dir = 'destinations';
                $target_dir = UPLOAD_BASE_PATH . $upload_dir . '/';
                if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
                $target_file = $target_dir . "dest-" . uniqid() . "." . pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION);
                
                if (resizeImage($_FILES["image"]["tmp_name"], $target_file, 1200, 800)) { 
                    // Delete the old image if a new one is uploaded
                    if (!empty($image_url) && file_exists(UPLOAD_BASE_PATH . $image_url)) {
                        unlink(UPLOAD_BASE_PATH . $image_url);
                    }
                    $image_url = $upload_dir . '/' . basename($target_file); 
                }
            }

            if ($id > 0) { // Update existing destination
                $stmt = $conn->prepare("UPDATE destinations SET name=?, province=?, description=?, image_url=? WHERE id=?");
                $stmt->bind_param("ssssi", $name, $province, $description, $image_url, $id);
            } else { // Insert new destination
                $stmt = $conn->prepare("INSERT INTO destinations (name, province, description, image_url) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("ssss", $name, $province, $description, $image_url);
            }

            if ($stmt->execute()) {
                $item_id_context = $id > 0 ? $id : $conn->insert_id;
                $_SESSION['success_message'] = "Destination saved successfully.";
                header("Location: manage-destinations.php?edit=" . $item_id_context);
                exit();
            } else {
                $_SESSION['error_message'] = "Error: Could not save the destination.";
            }
            $stmt->close();
            break;

        // --- ACTION: DELETE A DESTINATION ---
        case 'delete_destination':
            $item_id_to_delete = intval($_POST['id']);
            $conn->begin_transaction();
            try {
                // First, fetch the image URL to delete the file
                $stmt_img = $conn->prepare("SELECT image_url FROM destinations WHERE id = ?");
                $stmt_img->bind_param("i", $item_id_to_delete);
                $stmt_img->execute();
                if ($img = $stmt_img->get_result()->fetch_assoc()) {
                    if (!empty($img['image_url']) && file_exists(UPLOAD_BASE_PATH . $img['image_url'])) {
                        unlink(UPLOAD_BASE_PATH . $img['image_url']);
                    }
                }
                $stmt_img->close();

                // Then, delete the database record
                $stmt_del = $conn->prepare("DELETE FROM destinations WHERE id = ?");
                $stmt_del->bind_param("i", $item_id_to_delete);
                $stmt_del->execute();
                $stmt_del->close();

                $conn->commit();
                $_SESSION['success_message'] = "Destination has been deleted.";
            } catch (mysqli_sql_exception $e) {
                $conn->rollback();
                $_SESSION['error_message'] = "Database error during deletion: " . $e->getMessage();
            }
            header("Location: manage-destinations.php");
            exit();
            break;
    }
}

// Check for session-based messages to display after redirects
if (isset($_SESSION['success_message'])) {
    $message = '<div class="alert alert-success">' . $_SESSION['success_message'] . '</div>';
    unset($_SESSION['success_message']);
}
if (isset($_SESSION['error_message'])) {
    $message = '<div class="alert alert-danger">' . $_SESSION['error_message'] . '</div>';
    unset($_SESSION['error_message']);
}

// Fetch a single item for the edit form
$edit_item = null;
if ($is_editing_or_adding && $item_id_context > 0) {
    $stmt = $conn->prepare("SELECT * FROM destinations WHERE id = ?");
    $stmt->bind_param("i", $item_id_context);
    $stmt->execute();
    $edit_item = $stmt->get_result()->fetch_assoc();
}
?>
<style>
#toast-container { position: fixed; top: 20px; right: 20px; z-index: 1055; }
.toast-notification { padding: 15px 20px; margin-bottom: 10px; color: #fff; border-radius: 5px; box-shadow: 0 2px 10px rgba(0,0,0,0.2); opacity: 0; transform: translateX(100%); transition: all 0.4s ease; }
.toast-notification.show { opacity: 1; transform: translateX(0); }
.toast-notification.success { background-color: #28a745; }
.toast-notification.error { background-color: #dc3545; }
</style>

<div id="toast-container"></div>

<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 Destinations</h1>
</div>
<?php echo $message; ?>

<ul class="nav nav-tabs" id="destTab" role="tablist">
    <li class="nav-item" role="presentation">
        <button class="nav-link <?php if (!$is_editing_or_adding) echo 'active'; ?>" data-bs-toggle="tab" data-bs-target="#list-view" type="button" role="tab">Manage Destinations</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link <?php if ($is_editing_or_adding) echo 'active'; ?>" data-bs-toggle="tab" data-bs-target="#form-view" type="button" role="tab">
            <?php echo $edit_item ? 'Edit Destination' : 'Add New Destination'; ?>
        </button>
    </li>
</ul>

<div class="tab-content" id="destTabContent">
    <div class="tab-pane fade <?php if (!$is_editing_or_adding) echo 'show active'; ?>" id="list-view" role="tabpanel">
        <div class="card shadow-sm mt-3">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Existing Destinations</h5>
                <a href="manage-destinations.php?edit=0" class="btn btn-primary"><i class="bi bi-plus-circle-fill me-1"></i> Add New Destination</a>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover align-middle">
                        <thead class="table-dark"><tr><th>Image</th><th>Name</th><th>Province</th><th class="text-end">Actions</th></tr></thead>
                        <tbody>
                        <?php $result = $conn->query("SELECT * FROM destinations ORDER BY name ASC"); while($row = $result->fetch_assoc()): ?>
                            <tr>
                                <td><img src="../uploads/<?php echo htmlspecialchars($row['image_url']); ?>" alt="<?php echo htmlspecialchars($row['name']); ?>" class="img-thumbnail" style="width: 100px; height: 60px; object-fit: cover;"></td>
                                <td><?php echo htmlspecialchars($row['name']); ?></td>
                                <td><?php echo htmlspecialchars($row['province']); ?></td>
                                <td class="text-end">
                                    <a href="?edit=<?php echo $row['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                                    <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this destination?');">
                                        <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                        <button type="submit" name="delete_destination" class="btn btn-sm btn-danger">Delete</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="tab-pane fade <?php if ($is_editing_or_adding) echo 'show active'; ?>" id="form-view" role="tabpanel">
        <div class="card shadow-sm mt-3">
            <div class="card-header">
                <h5 class="mb-0"><?php echo $edit_item ? 'Editing: ' . htmlspecialchars($edit_item['name']) : 'Add New Destination Details'; ?></h5>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data" action="manage-destinations.php?edit=<?php echo $item_id_context; ?>">
                    <input type="hidden" name="id" value="<?php echo $item_id_context; ?>">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Destination Name</label>
                            <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($edit_item['name'] ?? ''); ?>" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Province</label>
                            <input type="text" class="form-control" name="province" value="<?php echo htmlspecialchars($edit_item['province'] ?? ''); ?>" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" rows="5"><?php echo htmlspecialchars($edit_item['description'] ?? ''); ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Featured Image</label>
                        <input type="file" class="form-control" name="image" accept="image/*">
                        <input type="hidden" name="current_image" value="<?php echo htmlspecialchars($edit_item['image_url'] ?? ''); ?>">
                        <?php if (!empty($edit_item['image_url'])): ?>
                            <div class="mt-2">
                                <small>Current Image:</small><br>
                                <img src="../uploads/<?php echo htmlspecialchars($edit_item['image_url']); ?>" class="img-thumbnail" style="max-height:100px;">
                            </div>
                        <?php endif; ?>
                    </div>
                    <hr>
                    <div class="d-flex justify-content-end gap-2">
                         <a href="manage-destinations.php" class="btn btn-secondary">Cancel</a>
                         <button type="submit" name="save_destination" class="btn btn-primary"><i class="bi bi-save-fill me-1"></i> Save Destination</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// No specific JS needed for this page beyond the Bootstrap bundle, but you can add toast triggers here if needed.
</script>

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