<?php
// INCLUDES: Replaced old includes with the new logic file
require_once 'admin-logic.php';

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

$tour_id = filter_input(INPUT_GET, 'tour_id', FILTER_VALIDATE_INT);
if (!$tour_id) {
    die("Invalid Tour ID.");
}

// DATABASE: Switched from PDO ($pdo) to MySQLi ($conn)
$stmt = $conn->prepare("SELECT title FROM tours WHERE id = ?");
$stmt->bind_param("i", $tour_id);
$stmt->execute();
$result = $stmt->get_result();
$tour = $result->fetch_assoc();
$stmt->close();

if (!$tour) {
    die("Tour not found.");
}

$page_title = "Manage Availability: " . htmlspecialchars($tour['title']);
$current_page = 'manage-tours.php'; 
$active_category = 'contentMenu';

// --- CRUD LOGIC ---
$feedback = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    try {
        if ($action === 'add_availability') {
            $date = $_POST['available_date'];
            $slots = filter_input(INPUT_POST, 'slots_available', FILTER_VALIDATE_INT);
            if ($date && $slots > 0) {
                $stmt = $conn->prepare("INSERT INTO tour_availability (tour_id, available_date, slots_available) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE slots_available = ?");
                $stmt->bind_param("isis", $tour_id, $date, $slots, $slots);
                $stmt->execute();
                $stmt->close();
                $feedback = ['type' => 'success', 'message' => 'Availability has been added/updated successfully.'];
            } else {
                $feedback = ['type' => 'danger', 'message' => 'Please provide a valid date and number of slots.'];
            }
        } elseif ($action === 'update_availability') {
            $availability_id = filter_input(INPUT_POST, 'availability_id', FILTER_VALIDATE_INT);
            $slots = filter_input(INPUT_POST, 'slots_available', FILTER_VALIDATE_INT);
            if ($availability_id && $slots > 0) {
                $stmt = $conn->prepare("UPDATE tour_availability SET slots_available = ? WHERE id = ? AND tour_id = ?");
                $stmt->bind_param("iii", $slots, $availability_id, $tour_id);
                $stmt->execute();
                $stmt->close();
                $feedback = ['type' => 'success', 'message' => 'Slots have been updated successfully.'];
            } else {
                $feedback = ['type' => 'danger', 'message' => 'Invalid data provided for update.'];
            }
        } elseif ($action === 'delete_availability') {
            $availability_id = filter_input(INPUT_POST, 'availability_id', FILTER_VALIDATE_INT);
            if ($availability_id) {
                $stmt = $conn->prepare("DELETE FROM tour_availability WHERE id = ? AND tour_id = ?");
                $stmt->bind_param("ii", $availability_id, $tour_id);
                $stmt->execute();
                $stmt->close();
                $feedback = ['type' => 'success', 'message' => 'Availability entry has been deleted.'];
            }
        }
    } catch (Exception $e) {
        $feedback = ['type' => 'danger', 'message' => 'An error occurred: ' . $e->getMessage()];
    }
}


// Fetch all existing availability for this tour
$stmt = $conn->prepare("SELECT * FROM tour_availability WHERE tour_id = ? ORDER BY available_date ASC");
$stmt->bind_param("i", $tour_id);
$stmt->execute();
$result = $stmt->get_result();
$availabilities = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

include 'admin-header.php';
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3">
    <h1 class="h2"><?php echo $page_title; ?></h1>
    <a href="manage-tours.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> Back to Tours</a>
</div>

<?php if (!empty($feedback)): ?>
<div class="alert alert-<?php echo htmlspecialchars($feedback['type']); ?>" role="alert">
    <?php echo htmlspecialchars($feedback['message']); ?>
</div>
<?php endif; ?>

<div class="row">
    <div class="col-lg-4 mb-4">
        <div class="card">
            <div class="card-header">
                <strong>Add New / Update Existing Date</strong>
            </div>
            <div class="card-body">
                <p class="small text-muted">If you enter a date that already exists, this form will update its available slots.</p>
                <form method="POST" action="manage-tour-availability.php?tour_id=<?php echo $tour_id; ?>">
                    <input type="hidden" name="action" value="add_availability">
                    <div class="mb-3">
                        <label for="available_date" class="form-label">Date</label>
                        <input type="date" class="form-control" id="available_date" name="available_date" required>
                    </div>
                    <div class="mb-3">
                        <label for="slots_available" class="form-label">Available Slots</label>
                        <input type="number" class="form-control" id="slots_available" name="slots_available" min="1" required>
                    </div>
                    <button type="submit" class="btn btn-primary w-100">Save Availability</button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">
                <strong>Existing Availability</strong>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Slots Available</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($availabilities)): ?>
                                <tr>
                                    <td colspan="3" class="text-center text-muted">No availability has been set for this tour yet.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($availabilities as $avail): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars(date('F j, Y', strtotime($avail['available_date']))); ?></td>
                                    <td><?php echo htmlspecialchars($avail['slots_available']); ?></td>
                                    <td class="text-end">
                                        <button class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editModal-<?php echo $avail['id']; ?>"><i class="bi bi-pencil-fill"></i></button>
                                        <form method="POST" action="manage-tour-availability.php?tour_id=<?php echo $tour_id; ?>" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this date?');">
                                            <input type="hidden" name="action" value="delete_availability">
                                            <input type="hidden" name="availability_id" value="<?php echo $avail['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-danger"><i class="bi bi-trash-fill"></i></button>
                                        </form>
                                    </td>
                                </tr>

                                <div class="modal fade" id="editModal-<?php echo $avail['id']; ?>" tabindex="-1" aria-labelledby="editModalLabel-<?php echo $avail['id']; ?>" aria-hidden="true">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <form method="POST" action="manage-tour-availability.php?tour_id=<?php echo $tour_id; ?>">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="editModalLabel-<?php echo $avail['id']; ?>">Edit Availability</h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <div class="modal-body">
                                                    <input type="hidden" name="action" value="update_availability">
                                                    <input type="hidden" name="availability_id" value="<?php echo $avail['id']; ?>">
                                                    <div class="mb-3">
                                                        <label class="form-label">Date</label>
                                                        <input type="text" class="form-control" value="<?php echo htmlspecialchars(date('F j, Y', strtotime($avail['available_date']))); ?>" disabled>
                                                    </div>
                                                    <div class="mb-3">
                                                        <label for="slots-<?php echo $avail['id']; ?>" class="form-label">Available Slots</label>
                                                        <input type="number" class="form-control" id="slots-<?php echo $avail['id']; ?>" name="slots_available" value="<?php echo htmlspecialchars($avail['slots_available']); ?>" min="1" required>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                    <button type="submit" class="btn btn-primary">Save Changes</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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