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

// --- 1. FETCH DATA FOR FORM DROPDOWNS ---

// Fetch all users (customers/partners) for the dropdown
$users_result = $conn->query("SELECT id, full_name FROM users WHERE role != 'admin' ORDER BY full_name ASC");

// Fetch all tours for the dropdown
$tours_result = $conn->query("SELECT id, title, price FROM tours ORDER BY title ASC");
$tours_data = [];
if ($tours_result->num_rows > 0) {
    while($row = $tours_result->fetch_assoc()) {
        $tours_data[] = $row;
    }
}


// --- 2. HANDLE FORM SUBMISSION ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and retrieve form data
    $user_id = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);
    $tour_id = filter_input(INPUT_POST, 'tour_id', FILTER_VALIDATE_INT);
    $booking_date = $_POST['booking_date'] ?? ''; // Basic validation for date format can be added
    $adults = filter_input(INPUT_POST, 'adults', FILTER_VALIDATE_INT);
    $children = filter_input(INPUT_POST, 'children', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]); // Optional field
    $payment_status = $_POST['payment_status'] ?? 'Unpaid';
    $status = $_POST['status'] ?? 'Pending';
    $notes = trim($_POST['notes']) ?? '';

    // Server-side validation
    if (!$user_id || !$tour_id || empty($booking_date) || $adults === false || $adults <= 0) {
        $_SESSION['error_message'] = "Please fill in all required fields correctly.";
    } else {
        // Fetch the tour price from the database to prevent price tampering
        $stmt_price = $conn->prepare("SELECT price FROM tours WHERE id = ?");
        $stmt_price->bind_param("i", $tour_id);
        $stmt_price->execute();
        $tour = $stmt_price->get_result()->fetch_assoc();
        $stmt_price->close();

        if ($tour) {
            $total_price = $tour['price'] * $adults; // Simple calculation, can be expanded

            // Insert into the database
            $sql = "INSERT INTO bookings (user_id, tour_id, booking_date, num_adults, num_children, total_price, payment_status, status, admin_notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt_insert = $conn->prepare($sql);
            $stmt_insert->bind_param("iisiidsss", $user_id, $tour_id, $booking_date, $adults, $children, $total_price, $payment_status, $status, $notes);

            if ($stmt_insert->execute()) {
                $_SESSION['success_message'] = "New booking created successfully!";
                header("Location: manage-bookings.php");
                exit();
            } else {
                $_SESSION['error_message'] = "Error: Could not create the booking. " . $conn->error;
            }
            $stmt_insert->close();
        } else {
            $_SESSION['error_message'] = "Invalid Tour selected.";
        }
    }
    // If there was an error, redirect back to the form
    header("Location: add-booking.php");
    exit();
}
?>

<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">Add New Tour Booking</h1>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="manage-bookings.php">Tour Bookings</a></li>
                <li class="breadcrumb-item active" aria-current="page">Add New</li>
            </ol>
        </nav>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header">
        <h5 class="mb-0">Booking Details</h5>
    </div>
    <div class="card-body">
        <form action="add-booking.php" method="POST" id="addBookingForm">
            <div class="row g-4">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="user_id" class="form-label">Select Customer <span class="text-danger">*</span></label>
                        <select class="form-select" id="user_id" name="user_id" required>
                            <option value="" disabled selected>Choose a customer...</option>
                            <?php while ($user = $users_result->fetch_assoc()): ?>
                                <option value="<?php echo $user['id']; ?>"><?php echo htmlspecialchars($user['full_name']); ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="tour_id" class="form-label">Select Tour/Service <span class="text-danger">*</span></label>
                        <select class="form-select" id="tour_id" name="tour_id" required>
                             <option value="" data-price="0" disabled selected>Choose a tour...</option>
                            <?php foreach ($tours_data as $tour): ?>
                                <option value="<?php echo $tour['id']; ?>" data-price="<?php echo $tour['price']; ?>">
                                    <?php echo htmlspecialchars($tour['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="row">
                        <div class="col-sm-6 mb-3">
                            <label for="adults" class="form-label">Adults <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="adults" name="adults" min="1" value="1" required>
                        </div>
                        <div class="col-sm-6 mb-3">
                            <label for="children" class="form-label">Children</label>
                            <input type="number" class="form-control" id="children" name="children" min="0" value="0">
                        </div>
                    </div>

                     <div class="mb-3">
                        <label for="booking_date" class="form-label">Booking Date <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" id="booking_date" name="booking_date" required min="<?php echo date('Y-m-d'); ?>">
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="total_price" class="form-label">Calculated Total Price</label>
                        <div class="input-group">
                            <span class="input-group-text">₱</span>
                            <input type="text" class="form-control" id="total_price" name="total_price" value="0.00" readonly>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-sm-6 mb-3">
                            <label for="status" class="form-label">Booking Status</label>
                            <select class="form-select" id="status" name="status">
                                <option value="Pending" selected>Pending</option>
                                <option value="Confirmed">Confirmed</option>
                                <option value="Cancelled">Cancelled</option>
                            </select>
                        </div>
                        <div class="col-sm-6 mb-3">
                            <label for="payment_status" class="form-label">Payment Status</label>
                            <select class="form-select" id="payment_status" name="payment_status">
                                <option value="Unpaid" selected>Unpaid</option>
                                <option value="Paid">Paid</option>
                            </select>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="notes" class="form-label">Internal Notes (Optional)</label>
                        <textarea class="form-control" id="notes" name="notes" rows="4" placeholder="Add any notes for this booking..."></textarea>
                    </div>
                </div>
            </div>

            <hr class="my-4">

            <div class="d-flex justify-content-end gap-2">
                <a href="manage-bookings.php" class="btn btn-secondary">Cancel</a>
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-plus-circle-fill me-1"></i> Create Booking
                </button>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const tourSelect = document.getElementById('tour_id');
    const adultsInput = document.getElementById('adults');
    const totalPriceInput = document.getElementById('total_price');

    function calculateTotal() {
        const selectedTour = tourSelect.options[tourSelect.selectedIndex];
        const pricePerAdult = parseFloat(selectedTour.getAttribute('data-price')) || 0;
        const numAdults = parseInt(adultsInput.value) || 0;

        if (numAdults < 1 && adultsInput.value !== '') {
            adultsInput.value = 1; // Reset to minimum 1 if user enters 0 or less
        }

        const total = pricePerAdult * (numAdults > 0 ? numAdults : 0);
        totalPriceInput.value = total.toFixed(2);
    }

    // Add event listeners to trigger calculation
    tourSelect.addEventListener('change', calculateTotal);
    adultsInput.addEventListener('input', calculateTotal);

    // Initial calculation on page load
    calculateTotal();
});
</script>

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