<?php
// --- LOGIC BLOCK ---
require_once 'includes/db.php';
require_once 'includes/email-handler.php';
require_once 'includes/helpers.php'; // For generating booking ref

if (!isset($_SESSION['user_id'])) { header("Location: login.php?redirect=" . urlencode($_SERVER['REQUEST_URI'])); exit(); }
$user_id = $_SESSION['user_id'];

$route_id = intval($_GET['route_id'] ?? 0);
if ($route_id <= 0) { header("Location: ferries.php"); exit(); }

$stmt_route = $conn->prepare("SELECT fr.*, orig.city as origin_city, dest.city as dest_city FROM ferry_routes fr JOIN ferry_ports orig ON fr.origin_port_id = orig.id JOIN ferry_ports dest ON fr.destination_port_id = dest.id WHERE fr.id = ?");
$stmt_route->bind_param("i", $route_id);
$stmt_route->execute();
$route = $stmt_route->get_result()->fetch_assoc();
if (!$route) { header("Location: ferries.php"); exit(); }

$message = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_ferry_request'])) {
    $departure_date = $_POST['departure_date'];
    $num_passengers = intval($_POST['num_passengers']);
    $notes = trim(strip_tags($_POST['notes']));

    if (empty($departure_date) || $num_passengers <= 0) {
        $message = '<div class="alert alert-danger">Please fill in all required fields.</div>';
    } else {
        $stmt = $conn->prepare("INSERT INTO ferry_bookings (user_id, route_id, departure_date, num_passengers, notes) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("iisis", $user_id, $route_id, $departure_date, $num_passengers, $notes);
        if ($stmt->execute()) {
            $booking_id = $stmt->insert_id;
            $booking_ref = generate_booking_ref($conn, 'DXFE'); // DXFE for Ferry
            $conn->query("UPDATE ferry_bookings SET booking_ref = '$booking_ref' WHERE id = $booking_id");
            
            $subject = "New Ferry Booking Request (#" . $booking_ref . ")";
            $body = "A new ferry request was submitted by " . htmlspecialchars($_SESSION['user_name']) . ". Please log in to provide a quote.";
            send_email($conn, $site_settings['recipient_email'], $subject, $body);
            header("Location: dashboard/my-ferry-bookings.php?request=success");
            exit();
        } else {
            $message = '<div class="alert alert-danger">An error occurred. Please try again.</div>';
        }
    }
}
// --- PRESENTATION BLOCK ---
include 'includes/header.php'; 
?>
<main class="container my-5"><div class="row justify-content-center"><div class="col-md-8">
    <div class="card shadow-lg">
        <div class="card-header"><h3 class="mb-0">Request to Book a Ferry Trip</h3></div>
        <div class="card-body p-4">
            <?php echo $message; ?>
            <h5 class="card-title"><?php echo htmlspecialchars($route['origin_city'] . ' → ' . $route['dest_city']); ?></h5>
            <p class="card-text mb-1"><strong>Operator:</strong> <?php echo htmlspecialchars($route['ferry_company']); ?></p>
            <p class="card-text text-muted"><?php echo htmlspecialchars($route['description']); ?></p>
            <hr>
            <form method="POST" action="ferry-booking.php?route_id=<?php echo $route_id; ?>">
                <input type="hidden" name="submit_ferry_request" value="1">
                <div class="row">
                    <div class="col-md-6 mb-3"><label class="form-label">Preferred Departure Date</label><input type="date" name="departure_date" class="form-control" required min="<?php echo date('Y-m-d'); ?>"></div>
                    <div class="col-md-6 mb-3"><label class="form-label">Number of Passengers</label><input type="number" name="num_passengers" class="form-control" min="1" value="1" required></div>
                </div>
                <div class="mb-3"><label class="form-label">Notes (Optional)</label><textarea name="notes" class="form-control" rows="3" placeholder="e.g., traveling with seniors, etc."></textarea></div>
                <div class="d-grid"><button type="submit" class="btn btn-primary btn-lg">Submit Booking Request</button></div>
            </form>
        </div>
    </div>
</div></div></main>
<?php include 'includes/footer.php'; ?>
