<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';


// --- Page-Specific Logic Starts Here ---

// 2. INITIALIZE VARIABLES & DETERMINE MODE (ADD/EDIT)
$edit_mode = false;
$tour = []; // Initialize empty array to prevent errors in 'add' mode
$page_error = '';

$item_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($item_id) {
    $edit_mode = true;
}

// 3. FETCH DATA FOR FORM (PARTNERS & EXISTING TOUR IF EDITING)
// Fetch partners for the dropdown
$partners_result = $conn->query("SELECT id, full_name FROM users WHERE role LIKE '%_partner' ORDER BY full_name ASC");

if ($edit_mode) {
    // We also check for category='Tour' to ensure we're editing the right item type
    $stmt = $conn->prepare("SELECT * FROM tours WHERE id = ? AND category = 'Tour'");
    $stmt->bind_param("i", $item_id);
    $stmt->execute();
    $tour = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if (!$tour) {
        $page_error = "The requested tour could not be found.";
    }
}

// 4. HANDLE FORM SUBMISSION (CREATE OR UPDATE)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect and sanitize data
    $title = trim($_POST['title']);
    $location = trim($_POST['location']);
    $price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);
    $duration_days = filter_input(INPUT_POST, 'duration_days', FILTER_VALIDATE_INT);
    $partner_id = filter_input(INPUT_POST, 'partner_id', FILTER_VALIDATE_INT);
    $is_featured = isset($_POST['is_featured']) ? 1 : 0;
    $status = isset($_POST['status']) ? 'published' : 'draft';
    $description = $_POST['description']; // Assuming TinyMCE cleans its own output
    
    // Handle file upload
    $image_url = $_POST['current_image_url'] ?? ''; // Keep old image by default
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/tours/';
        if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); }
        $filename = uniqid() . '-' . basename($_FILES['image']['name']);
        $target_path = $upload_dir . $filename;
        if (move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
            $image_url = 'uploads/tours/' . $filename;
        } else {
            $_SESSION['error_message'] = "Error uploading file.";
        }
    }

    if (empty($title) || empty($location)) {
        $_SESSION['error_message'] = "Tour Title and Location are required.";
    } else {
        if ($edit_mode) { // UPDATE
            $stmt = $conn->prepare("UPDATE tours SET title=?, location=?, price=?, duration_days=?, partner_id=?, is_featured=?, status=?, description=?, image_url=? WHERE id=? AND category = 'Tour'");
            $stmt->bind_param("ssdiissssi", $title, $location, $price, $duration_days, $partner_id, $is_featured, $status, $description, $image_url, $item_id);
            if($stmt->execute()) $_SESSION['success_message'] = "Tour updated successfully."; else $_SESSION['error_message'] = "Error updating tour.";
            $stmt->close();
        } else { // INSERT
            $category = 'Tour';
            $stmt = $conn->prepare("INSERT INTO tours (category, title, location, price, duration_days, partner_id, is_featured, status, description, image_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssdiissss", $category, $title, $location, $price, $duration_days, $partner_id, $is_featured, $status, $description, $image_url);
            if($stmt->execute()) $_SESSION['success_message'] = "Tour created successfully."; else $_SESSION['error_message'] = "Error creating tour.";
            $stmt->close();
        }
        header("Location: manage-tours.php");
        exit();
    }
}


// 5. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<script src="https://cdn.tiny.cloud/1/<?php echo htmlspecialchars($settings['api_tinymce'] ?? 'no-api-key'); ?>/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
  tinymce.init({
    selector: 'textarea#description',
    plugins: 'code table lists link autoresize',
    toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright | bullist numlist | code | table | link',
    skin: (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'oxide-dark' : 'oxide'),
    content_css: (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default'),
    height: 400
  });
</script>

<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<?php if ($page_error): ?>
    <div class="alert alert-danger mt-4"><h4 class="alert-heading">Error</h4><p><?php echo $page_error; ?></p><hr><a href="manage-tours.php" class="btn btn-outline-danger">Return to Tours List</a></div>
<?php else: ?>
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <div>
            <h1 class="h2"><?php echo $edit_mode ? 'Edit Tour' : 'Add New Tour'; ?></h1>
            <nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="manage-tours.php">Tours</a></li><li class="breadcrumb-item active"><?php echo $edit_mode ? htmlspecialchars($tour['title']) : 'New'; ?></li></ol></nav>
        </div>
    </div>
    
    <form method="POST" action="edit-tour.php<?php echo $edit_mode ? '?id=' . $item_id : ''; ?>" enctype="multipart/form-data">
        <div class="row g-4">
            <div class="col-lg-8">
                <div class="card shadow-sm">
                    <div class="card-header"><strong>Tour Details</strong></div>
                    <div class="card-body">
                        <div class="mb-3"><label class="form-label">Tour Title <span class="text-danger">*</span></label><input type="text" class="form-control" name="title" value="<?php echo htmlspecialchars($tour['title'] ?? ''); ?>" required></div>
                        <div class="mb-3"><label class="form-label">Description</label><textarea id="description" name="description" rows="12"><?php echo htmlspecialchars($tour['description'] ?? ''); ?></textarea></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="card shadow-sm mb-4">
                    <div class="card-header"><strong>Publishing</strong></div>
                    <div class="card-body">
                        <div class="form-check form-switch mb-3"><input class="form-check-input" type="checkbox" role="switch" id="status" name="status" <?php if(isset($tour['status']) && $tour['status'] == 'published') echo 'checked'; ?>><label class="form-check-label" for="status">Published (Visible on site)</label></div>
                        <div class="form-check form-switch"><input class="form-check-input" type="checkbox" role="switch" id="is_featured" name="is_featured" <?php if(isset($tour['is_featured']) && $tour['is_featured']) echo 'checked'; ?>><label class="form-check-label" for="is_featured">Featured Tour</label></div>
                    </div>
                </div>
                <div class="card shadow-sm mb-4">
                    <div class="card-header"><strong>Attributes</strong></div>
                    <div class="card-body">
                        <div class="mb-3"><label class="form-label">Location <span class="text-danger">*</span></label><input type="text" class="form-control" name="location" value="<?php echo htmlspecialchars($tour['location'] ?? ''); ?>" required></div>
                        <div class="mb-3"><label class="form-label">Price</label><div class="input-group"><span class="input-group-text">₱</span><input type="number" step="0.01" class="form-control" name="price" value="<?php echo htmlspecialchars($tour['price'] ?? '0.00'); ?>"></div></div>
                        <div class="mb-3"><label class="form-label">Duration</label><div class="input-group"><input type="number" class="form-control" name="duration_days" min="1" value="<?php echo htmlspecialchars($tour['duration_days'] ?? '1'); ?>"><span class="input-group-text">Days</span></div></div>
                        <div class="mb-3"><label class="form-label">Partner (Optional)</label><select name="partner_id" class="form-select"><option value="0">Admin (No Partner)</option><?php while($p = $partners_result->fetch_assoc()): ?><option value="<?php echo $p['id']; ?>" <?php if(isset($tour['partner_id']) && $tour['partner_id'] == $p['id']) echo 'selected'; ?>><?php echo htmlspecialchars($p['full_name']); ?></option><?php endwhile; ?></select></div>
                    </div>
                </div>
                <div class="card shadow-sm">
                    <div class="card-header"><strong>Featured Image</strong></div>
                    <div class="card-body">
                        <input class="form-control" type="file" name="image" id="main-image-input">
                        <input type="hidden" name="current_image_url" value="<?php echo htmlspecialchars($tour['image_url'] ?? ''); ?>">
                        <?php $image_src = !empty($tour['image_url']) ? '../' . htmlspecialchars($tour['image_url']) : 'https://via.placeholder.com/300x200.png?text=No+Image'; ?>
                        <img id="image-preview" src="<?php echo $image_src; ?>" class="img-fluid rounded border mt-2" alt="Image Preview">
                    </div>
                </div>
            </div>
        </div>
        <div class="mt-4 d-flex justify-content-end gap-2">
            <a href="manage-tours.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle-fill me-1"></i> <?php echo $edit_mode ? 'Update Tour' : 'Save Tour'; ?></button>
        </div>
    </form>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const imageInput = document.getElementById('main-image-input');
    const imagePreview = document.getElementById('image-preview');
    if (imageInput) {
        imageInput.addEventListener('change', function(e) {
            if (e.target.files && e.target.files[0]) {
                const reader = new FileReader();
                reader.onload = function(event) { imagePreview.src = event.target.result; }
                reader.readAsDataURL(e.target.files[0]);
            }
        });
    }
});
</script>

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