<?php
include 'header.php'; // Includes partner session check and all necessary variables

// Security: This page is for TOUR partners only
if ($partner_role !== 'tour_partner') { 
    header("Location: index.php");
    exit(); 
}

$tour_id = intval($_GET['tour_id'] ?? 0);

// Security Check: Ensure the tour belongs to this partner
$stmt_tour = $conn->prepare("SELECT title FROM tours WHERE id = ? AND partner_id = ?");
$stmt_tour->bind_param("ii", $tour_id, $partner_id);
$stmt_tour->execute();
$tour = $stmt_tour->get_result()->fetch_assoc();

if (!$tour) {
    // If the tour ID is invalid or doesn't belong to the partner, redirect them.
    header("Location: manage-tours.php");
    exit();
}
$tour_name = $tour['title'];
$message = '';

// --- ACTION HANDLING: SET/UPDATE AVAILABILITY ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['set_availability'])) {
    $start_date_str = $_POST['start_date'];
    $end_date_str = $_POST['end_date'];
    $slots = intval($_POST['slots']);

    if (empty($start_date_str) || empty($end_date_str) || $slots < 0) {
        $message = '<div class="alert alert-danger">Please fill in all fields correctly.</div>';
    } elseif (strtotime($end_date_str) < strtotime($start_date_str)) {
        $message = '<div class="alert alert-danger">End date cannot be before the start date.</div>';
    } else {
        $start_date = new DateTime($start_date_str);
        $end_date = new DateTime($end_date_str);
        $end_date->modify('+1 day'); // Include the end date in the loop

        $interval = new DateInterval('P1D');
        $date_range = new DatePeriod($start_date, $interval, $end_date);

        // Prepare the efficient INSERT...ON DUPLICATE KEY UPDATE query
        $stmt = $conn->prepare("
            INSERT INTO tour_availability (tour_id, available_date, slots_available) 
            VALUES (?, ?, ?) 
            ON DUPLICATE KEY UPDATE slots_available = VALUES(slots_available)
        ");
        
        $dates_updated = 0;
        foreach ($date_range as $date) {
            $current_date = $date->format('Y-m-d');
            $stmt->bind_param("isi", $tour_id, $current_date, $slots);
            $stmt->execute();
            $dates_updated++;
        }
        $stmt->close();
        $message = '<div class="alert alert-success">Successfully set availability for ' . $dates_updated . ' day(s).</div>';
    }
}

// Fetch existing availability for display
$availability_result = $conn->query("SELECT * FROM tour_availability WHERE tour_id = $tour_id AND available_date >= CURDATE() ORDER BY available_date ASC");

?>
<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">Manage Availability</h1>
        <p class="text-muted">For Tour: <strong><?php echo htmlspecialchars($tour_name); ?></strong></p>
    </div>
    <a href="manage-tours.php" class="btn btn-secondary">← Back to Tours List</a>
</div>
<?php echo $message; ?>

<div class="row">
    <div class="col-lg-5 mb-4">
        <div class="card shadow-sm">
            <div class="card-header fw-bold">Set Available Slots</div>
            <div class="card-body">
                <p>Set the number of available slots for a specific date or a range of dates.</p>
                <form method="POST">
                    <div class="mb-3">
                        <label>Start Date</label>
                        <input type="date" name="start_date" class="form-control" required value="<?php echo date('Y-m-d'); ?>">
                    </div>
                    <div class="mb-3">
                        <label>End Date</label>
                        <input type="date" name="end_date" class="form-control" required value="<?php echo date('Y-m-d'); ?>">
                    </div>
                    <div class="mb-3">
                        <label>Number of Slots per Day</label>
                        <input type="number" name="slots" class="form-control" min="0" required placeholder="e.g., 20">
                        <small class="text-muted">Enter 0 to mark dates as unavailable/fully booked.</small>
                    </div>
                    <button type="submit" name="set_availability" class="btn btn-primary">Set Availability</button>
                </form>
            </div>
        </div>
    </div>
    <div class="col-lg-7 mb-4">
        <div class="card shadow-sm">
            <div class="card-header fw-bold">Current Availability Schedule</div>
            <div class="table-responsive" style="max-height: 400px;">
                <table class="table table-striped table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Slots Available</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($availability_result && $availability_result->num_rows > 0): ?>
                            <?php while($row = $availability_result->fetch_assoc()): ?>
                            <tr>
                                <td><?php echo date("F j, Y (l)", strtotime($row['available_date'])); ?></td>
                                <td>
                                    <?php if($row['slots_available'] > 0): ?>
                                        <span class="badge bg-success"><?php echo $row['slots_available']; ?> Slots</span>
                                    <?php else: ?>
                                        <span class="badge bg-danger">Fully Booked / Unavailable</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="2" class="text-center text-muted p-4">No availability has been set for future dates.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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