<?php
include 'admin-header.php';
require_once '../includes/user-email-sender.php'; // For notifying users

$message = '';
// --- ACTION HANDLING ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['booking_id'])) {
    $booking_id = intval($_POST['booking_id']);

    if (isset($_POST['save_quote'])) {
        $total_price = floatval($_POST['total_price']);
        $admin_notes = trim($_POST['admin_notes']);
        if ($total_price > 0) {
            $stmt = $conn->prepare("UPDATE ferry_bookings SET status = 'Quoted', total_price = ?, admin_notes = ? WHERE id = ?");
            $stmt->bind_param("dsi", $total_price, $admin_notes, $booking_id);
            if ($stmt->execute()) {
                $message = '<div class="alert alert-success">Quote sent for booking #'.$booking_id.'.</div>';
                // Send notification to user
                $user_id_to_notify = $conn->query("SELECT user_id FROM ferry_bookings WHERE id = $booking_id")->fetch_assoc()['user_id'];
                $email_subject = "Your Ferry Booking Quote is Ready!";
                $email_body = "Your quote for ferry booking request #".$booking_id." is now available. Please log in to your dashboard to view the details and complete your payment.";
                sendUserNotification($conn, $user_id_to_notify, $email_subject, $email_body);
            }
        }
    }
}

// --- DATA FETCHING ---
$sql = "SELECT fb.*, u.full_name, u.email, 
               orig.city as origin_city, 
               dest.city as dest_city,
               fr.ferry_company
        FROM ferry_bookings fb 
        JOIN users u ON fb.user_id = u.id 
        JOIN ferry_routes fr ON fb.route_id = fr.id
        JOIN ferry_ports orig ON fr.origin_port_id = orig.id 
        JOIN ferry_ports dest ON fr.destination_port_id = dest.id
        WHERE fb.status = 'Pending' 
        ORDER BY fb.created_at DESC";
$result = $conn->query($sql);
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Manage Ferry Bookings</h1>
</div>
<?php echo $message; ?>

<div class="card shadow-sm">
    <div class="card-header fw-bold">Pending Ferry Requests</div>
    <div class="table-responsive">
        <table class="table table-hover align-middle">
            <thead class="table-dark">
                <tr>
                    <th>Customer</th>
                    <th>Route</th>
                    <th>Departure Date</th>
                    <th>Passengers</th>
                    <th class="text-center">Action</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($result && $result->num_rows > 0): while($booking = $result->fetch_assoc()): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($booking['full_name']); ?></strong><br><small class="text-muted">ID: #<?php echo $booking['id']; ?></small></td>
                    <td>
                        <strong><?php echo htmlspecialchars($booking['origin_city']); ?> → <?php echo htmlspecialchars($booking['dest_city']); ?></strong><br>
                        <small class="text-muted"><?php echo htmlspecialchars($booking['ferry_company']); ?></small>
                    </td>
                    <td><?php echo date('M d, Y', strtotime($booking['departure_date'])); ?></td>
                    <td><?php echo $booking['num_passengers']; ?></td>
                    <td class="text-center">
                        <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#quoteModal<?php echo $booking['id']; ?>">Provide Quote</button>
                    </td>
                </tr>
                <div class="modal fade" id="quoteModal<?php echo $booking['id']; ?>" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <form method="POST">
                                <div class="modal-header">
                                    <h5 class="modal-title">Provide Quote for Request #<?php echo $booking['id']; ?></h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                 undermining
                                <div class="modal-body">
                                    <input type="hidden" name="booking_id" value="<?php echo $booking['id']; ?>">
                                    <div class="mb-3">
                                        <label class="form-label">Total Price (PHP)</label>
                                        <input type="number" name="total_price" class="form-control" step="0.01" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Ferry Details & Notes</label>
                                        <textarea name="admin_notes" class="form-control" rows="5" placeholder="e.g., Vessel: St. Michael the Archangel&#10;Schedule: 08:00 AM - 10:00 AM&#10;Notes: Please present valid ID."></textarea>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                    <button type="submit" name="save_quote" class="btn btn-primary">Save Quote & Notify User</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            <?php endwhile; else: ?>
                <tr><td colspan="5" class="text-center text-muted p-4">No pending ferry requests.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php include 'admin-footer.php'; ?>
