<?php
// --- LOGIC BLOCK: All PHP processing must happen before any HTML is sent ---
require_once 'includes/db.php';
require_once 'includes/email-sender.php';

// Fetch all airports once for the form dropdowns
$airports_result = $conn->query("SELECT * FROM airports ORDER BY city ASC");
$airports = [];
if ($airports_result) {
    while ($row = $airports_result->fetch_assoc()) {
        $airports[] = $row;
    }
}

$message = '';
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // A user MUST be logged in to submit a flight request
    if (!isset($_SESSION['user_id'])) {
        header("Location: login.php?redirect=flights.php");
        exit();
    }

    // Use null coalescing operator (??) to provide safe defaults
    $user_id = $_SESSION['user_id'];
    $trip_type = $_POST['trip_type'] ?? 'One-way';
    $origin_id = intval($_POST['origin_id'] ?? 0);
    $destination_id = intval($_POST['destination_id'] ?? 0);
    $departure_date = $_POST['departure_date'] ?? '';
    $return_date = ($trip_type == 'Round-trip') ? ($_POST['return_date'] ?? '') : NULL;
    $num_adults = intval($_POST['num_adults'] ?? 1);
    $num_children = intval($_POST['num_children'] ?? 0);
    $num_infants = intval($_POST['num_infants'] ?? 0);
    $notes = trim($_POST['notes'] ?? '');

    // Server-side Validation
    if ($origin_id === 0 || $destination_id === 0) {
        $message = '<div class="alert alert-danger">Please select both an origin and destination.</div>';
    } elseif ($origin_id === $destination_id) {
        $message = '<div class="alert alert-danger">Origin and Destination cannot be the same.</div>';
    } elseif (empty($departure_date)) {
        $message = '<div class="alert alert-danger">Please select a departure date.</div>';
    } elseif ($trip_type == 'Round-trip' && empty($return_date)) {
        $message = '<div class="alert alert-danger">Please select a return date for a round-trip booking.</div>';
    } elseif ($trip_type == 'Round-trip' && strtotime($return_date) < strtotime($departure_date)) {
        $message = '<div class="alert alert-danger">Return date cannot be before the departure date.</div>';
    } else {
        // All validation passed, proceed to insert into database
        $stmt = $conn->prepare("INSERT INTO flight_bookings (user_id, trip_type, origin_id, destination_id, departure_date, return_date, num_adults, num_children, num_infants, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("isiissiiis", $user_id, $trip_type, $origin_id, $destination_id, $departure_date, $return_date, $num_adults, $num_children, $num_infants, $notes);
        
        if ($stmt->execute()) {
            $booking_id = $stmt->insert_id;
            
            // Send email notification to admin
            $subject = "New Flight Booking Request (#" . $booking_id . ")";
            $message_body = "A new flight booking request has been submitted by <strong>" . htmlspecialchars($_SESSION['user_name']) . "</strong>."
                        . "<br><br>Please log in to the admin panel to find flights and provide a quote."
                        . "<br><br><a href='http://" . $_SERVER['HTTP_HOST'] . "/admin/flight-bookings.php' style='padding:10px 15px; background-color:#0d6efd; color:white; text-decoration:none; border-radius:5px;'>View Flight Bookings</a>";
            sendAdminNotification($conn, $subject, $message_body);
            
            // Redirect to the user's dashboard to see the new request
            header("Location: dashboard/my-flight-bookings.php?request=success");
            exit();
        } else {
            $message = '<div class="alert alert-danger">A server error occurred while submitting your request. Please try again.</div>';
        }
    }
}

// --- PRESENTATION BLOCK: This HTML only runs if the script did not redirect ---
include 'includes/header.php'; 
?>

<div class="hero-section" style="background: url('https://images.unsplash.com/photo-1570715722304-3611a5b1c5a3?q=80&w=2070') no-repeat center center; background-size: cover; padding: 80px 0;">
    <div class="container text-center">
        <h1 class="display-4">Search for Flights</h1>
        <p class="lead">Submit your travel request and our agents will find the best deal for you!</p>
    </div>
</div>

<main class="container my-5">
    <div class="row justify-content-center">
        <div class="col-lg-10">
            <div class="card shadow-lg">
                <div class="card-body p-4 p-md-5">
                    <?php echo $message; ?>
                    <form method="POST" id="flightSearchForm" action="flights.php" novalidate>
                        <div class="mb-4">
                            <div class="form-check form-check-inline fs-5">
                                <input class="form-check-input" type="radio" name="trip_type" id="roundTrip" value="Round-trip" checked>
                                <label class="form-check-label" for="roundTrip">Round-trip</label>
                            </div>
                            <div class="form-check form-check-inline fs-5">
                                <input class="form-check-input" type="radio" name="trip_type" id="oneWay" value="One-way">
                                <label class="form-check-label" for="oneWay">One-way</label>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">From</label>
                                <select name="origin_id" class="form-select form-select-lg" required>
                                    <option value="" disabled selected>Select Origin</option>
                                    <?php foreach ($airports as $airport): ?>
                                    <option value="<?php echo $airport['id']; ?>"><?php echo htmlspecialchars($airport['city'] . ' (' . $airport['airport_code'] . ')'); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">To</label>
                                <select name="destination_id" class="form-select form-select-lg" required>
                                    <option value="" disabled selected>Select Destination</option>
                                    <?php foreach ($airports as $airport): ?>
                                    <option value="<?php echo $airport['id']; ?>"><?php echo htmlspecialchars($airport['city'] . ' (' . $airport['airport_code'] . ')'); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Departure Date</label>
                                <input type="date" name="departure_date" class="form-control form-control-lg" required min="<?php echo date('Y-m-d'); ?>">
                            </div>
                            <div class="col-md-6 mb-3" id="returnDateContainer">
                                <label class="form-label fw-bold">Return Date</label>
                                <input type="date" name="return_date" class="form-control form-control-lg" required min="<?php echo date('Y-m-d'); ?>">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3"><label>Adults (12+)</label><input type="number" name="num_adults" class="form-control" min="1" value="1" required></div>
                            <div class="col-md-4 mb-3"><label>Children (2-11)</label><input type="number" name="num_children" class="form-control" min="0" value="0"></div>
                            <div class="col-md-4 mb-3"><label>Infants (under 2)</label><input type="number" name="num_infants" class="form-control" min="0" value="0"></div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label">Notes (Optional)</label>
                            <textarea name="notes" class="form-control" rows="2" placeholder="e.g., Prefer morning flight, specific airline, etc."></textarea>
                        </div>
                        
                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary btn-lg fw-bold">Submit Flight Request</button>
                        </div>
                        <p class="text-center text-muted mt-2"><small>You must be logged in to submit a request. Our agents will contact you with a quote.</small></p>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
// JavaScript to toggle the return date field based on trip type
document.addEventListener('DOMContentLoaded', function() {
    const tripTypeRadios = document.querySelectorAll('input[name="trip_type"]');
    const returnDateContainer = document.getElementById('returnDateContainer');
    const returnDateInput = returnDateContainer.querySelector('input');

    function toggleReturnDate() {
        if (document.getElementById('oneWay').checked) {
            returnDateContainer.style.display = 'none';
            returnDateInput.required = false;
            returnDateInput.value = ''; // Clear value when hidden
        } else {
            returnDateContainer.style.display = 'block';
            returnDateInput.required = true;
        }
    }

    tripTypeRadios.forEach(radio => {
        radio.addEventListener('change', toggleReturnDate);
    });
    
    // Run on page load to set the initial correct state
    toggleReturnDate();
});
</script>

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