<?php
include 'header.php'; // Includes partner session check and $partner_id
require_once '../includes/image-resizer.php'; 

// Security: This page is for TOUR partners only
if ($partner_role !== 'tour_partner') { die("Access Denied. You are not a tour partner."); }
require_once '../includes/image-resizer.php'; 
// The full CRUD logic and HTML form from the previous correct `partner/manage-tours.php` version goes here.
// No changes are needed from the last version I provided.



$message = '';
// --- ACTION HANDLING (scoped to the logged-in partner) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // --- SAVE (ADD/EDIT) A TOUR ---
    if (isset($_POST['save_tour'])) {
        $id = intval($_POST['id'] ?? 0);
        $title = trim($_POST['title']);
        $location = trim($_POST['location']);
        $description = trim($_POST['description']);
        $price = floatval($_POST['price']);
        $duration_days = intval($_POST['duration_days']);
        $image_url = $_POST['current_image'] ?? '';

        // Handle MAIN image upload
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $target_dir = "../uploads/tours/";
            if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
            $target_file = $target_dir . "tour-partner" . $partner_id . "-" . uniqid() . basename($_FILES["image"]["name"]);
            if (resizeImage($_FILES["image"]["tmp_name"], $target_file, 1200, 800)) {
                $image_url = str_replace('../', '', $target_file);
            }
        }

        if ($id > 0) { // Update existing tour (check ownership)
            $stmt = $conn->prepare("UPDATE tours SET title=?, location=?, description=?, price=?, duration_days=?, image_url=? WHERE id=? AND partner_id=?");
            $stmt->bind_param("sssdisii", $title, $location, $description, $price, $duration_days, $image_url, $id, $partner_id);
            $message = '<div class="alert alert-success">Tour updated successfully.</div>';
        } else { // Insert new tour (assign ownership)
            $stmt = $conn->prepare("INSERT INTO tours (partner_id, title, location, description, price, duration_days, image_url) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("isssdis", $partner_id, $title, $location, $description, $price, $duration_days, $image_url);
            $message = '<div class="alert alert-success">New tour added successfully.</div>';
        }
        $stmt->execute();
        $stmt->close();
        // Redirect or clear form to prevent re-submission might be needed here. For now, a message is shown.
    }
}

// Fetch tour for editing if an ID is provided
$edit_tour = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM tours WHERE id = ? AND partner_id = ?");
    $stmt->bind_param("ii", $id, $partner_id);
    $stmt->execute();
    $edit_tour = $stmt->get_result()->fetch_assoc(); // Will be null if tour doesn't belong to partner
}
?>

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

<div class="card shadow-sm mb-4">
    <div class="card-header"><?php echo $edit_tour ? 'Edit Tour Details' : 'Add a New Tour'; ?></div>
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="id" value="<?php echo $edit_tour['id'] ?? 0; ?>">
            <div class="mb-3"><label>Title</label><input type="text" class="form-control" name="title" value="<?php echo htmlspecialchars($edit_tour['title'] ?? ''); ?>" required></div>
            <div class="mb-3"><label>Location</label><input type="text" class="form-control" name="location" value="<?php echo htmlspecialchars($edit_tour['location'] ?? ''); ?>" required></div>
            <div class="mb-3"><label>Description</label><textarea class="form-control" name="description" rows="5" required><?php echo htmlspecialchars($edit_tour['description'] ?? ''); ?></textarea></div>
            <div class="row">
                <div class="col-md-6 mb-3"><label>Price (per person) ₱</label><input type="number" step="0.01" class="form-control" name="price" value="<?php echo $edit_tour['price'] ?? ''; ?>" required></div>
                <div class="col-md-6 mb-3"><label>Duration (Days)</label><input type="number" class="form-control" name="duration_days" value="<?php echo $edit_tour['duration_days'] ?? ''; ?>" required></div>
            </div>
            <div class="mb-3">
                <label>Main Tour Image</label><input type="file" class="form-control" name="image" accept="image/*">
                <input type="hidden" name="current_image" value="<?php echo htmlspecialchars($edit_tour['image_url'] ?? ''); ?>">
                <?php if (!empty($edit_tour['image_url'])): ?><div class="mt-2"><img src="../<?php echo htmlspecialchars($edit_tour['image_url']); ?>" height="100" class="img-thumbnail"></div><?php endif; ?>
            </div>
            <button type="submit" name="save_tour" class="btn btn-primary"><?php echo $edit_tour ? 'Save Changes' : 'Add Tour'; ?></button>
            <?php if ($edit_tour): ?><a href="manage-tours.php" class="btn btn-secondary">Cancel Edit</a><?php endif; ?>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header">My Tour Listings</div>
    <div class="table-responsive">
        <table class="table table-hover">
            <thead><tr><th>Title</th><th>Location</th><th>Price</th><th>Actions</th></tr></thead>
            <tbody>
                <?php
                $stmt_list = $conn->prepare("SELECT id, title, location, price FROM tours WHERE partner_id = ? ORDER BY id DESC");
                $stmt_list->bind_param("i", $partner_id);
                $stmt_list->execute();
                $result = $stmt_list->get_result();
                while($row = $result->fetch_assoc()):
                ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['title']); ?></td>
                    <td><?php echo htmlspecialchars($row['location']); ?></td>
                    <td>₱<?php echo number_format($row['price'], 2); ?></td>
                    <td><a href="?edit=<?php echo $row['id']; ?>" class="btn btn-sm btn-primary">Edit</a></td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>
<?php include 'footer.php'; ?>
manage-tours.php