<?php
// --- LOGIC BLOCK ---
require_once '../includes/db.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}
$user_id = $_SESSION['user_id'];

// ACTION HANDLING: PAY FOR FERRY BOOKING
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['pay_ferry_from_wallet'])) {
    $wallet_balance_for_payment = $conn->query("SELECT wallet_balance FROM users WHERE id = $user_id")->fetch_assoc()['wallet_balance'];
    $booking_id = intval($_POST['booking_id']);
    $total_price = floatval($_POST['total_price']);

    if ($wallet_balance_for_payment >= $total_price) {
        $conn->begin_transaction();
        try {
            $conn->query("UPDATE users SET wallet_balance = wallet_balance - $total_price WHERE id = $user_id");
            $conn->query("UPDATE ferry_bookings SET payment_status = 'Paid', status = 'Confirmed' WHERE id = $booking_id AND user_id = $user_id");
            $conn->query("INSERT INTO transactions (user_id, transaction_type, amount, payment_method, status) VALUES ($user_id, 'Booking Payment', $total_price, 'Wallet', 'Completed')");
            $conn->commit();
            header("Location: my-ferry-bookings.php?payment=success");
            exit();
        } catch (mysqli_sql_exception $exception) {
            $conn->rollback();
            header("Location: my-ferry-bookings.php?payment=error");
            exit();
        }
    } else {
        header("Location: my-ferry-bookings.php?payment=insufficient");
        exit();
    }
}

// --- PRESENTATION BLOCK ---
include 'header.php';
?>
<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">My Ferry Bookings</h1>
</div>

<?php 
if(isset($_GET['request']) && $_GET['request'] == 'success') echo '<div class="alert alert-success">Your booking request has been sent! An agent will provide a quote shortly.</div>';
if(isset($_GET['payment'])) {
    if ($_GET['payment'] == 'success') echo '<div class="alert alert-success">Payment successful! Your ferry booking is confirmed.</div>';
    if ($_GET['payment'] == 'error') echo '<div class="alert alert-danger">An error occurred during payment. Please try again.</div>';
    if ($_GET['payment'] == 'insufficient') echo '<div class="alert alert-warning">Insufficient wallet balance. Please <a href="top-up.php">top-up</a> to proceed.</div>';
}
?>

<div class="card shadow-sm">
    <div class="card-header">Your Ferry Booking Requests</div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-dark"><tr><th>Route</th><th>Departure Date</th><th>Status</th><th class="text-center">Action</th></tr></thead>
                <tbody>
                    <?php
                    $stmt = $conn->prepare("
                        SELECT b.*, r.ferry_company, orig.city as origin_city, dest.city as dest_city 
                        FROM ferry_bookings b
                        JOIN ferry_routes r ON b.route_id = r.id
                        JOIN ferry_ports orig ON r.origin_port_id = orig.id 
                        JOIN ferry_ports dest ON r.destination_port_id = dest.id
                        WHERE b.user_id = ? ORDER BY b.created_at DESC
                    ");
                    $stmt->bind_param("i", $user_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    if ($result->num_rows > 0): while($row = $result->fetch_assoc()):
                    ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($row['origin_city'] . ' → ' . $row['dest_city']); ?></strong><br><small class="text-muted"><?php echo htmlspecialchars($row['ferry_company']); ?></small></td>
                        <td><?php echo date('M d, Y', strtotime($row['departure_date'])); ?></td>
                        <td>
                            <?php $status_class = ['Pending' => 'secondary', 'Quoted' => 'warning text-dark', 'Confirmed' => 'success', 'Cancelled' => 'danger']; ?>
                            <span class="badge bg-<?php echo $status_class[$row['status']]; ?>"><?php echo htmlspecialchars($row['status']); ?></span>
                            <?php if($row['status'] == 'Quoted' || $row['status'] == 'Confirmed'): ?>
                                <span class="badge <?php echo $row['payment_status'] == 'Paid' ? 'bg-success' : 'bg-warning text-dark'; ?>"><?php echo $row['payment_status']; ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center">
                            <?php if($row['status'] == 'Quoted' && $row['payment_status'] == 'Unpaid'): ?>
                                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#quoteModal<?php echo $row['id']; ?>">View Quote & Pay</button>
                            <?php elseif($row['payment_status'] == 'Paid'): ?>
                                <a href="generate-ticket.php?type=ferry&id=<?php echo $row['id']; ?>" target="_blank" class="btn btn-sm btn-info"><i class="bi bi-ticket-perforated-fill"></i> View Voucher</a>
                            <?php else: ?>
                                <button class="btn btn-sm btn-secondary" disabled>Pending Quote</button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <div class="modal fade" id="quoteModal<?php echo $row['id']; ?>" tabindex="-1">
                        <div class="modal-dialog"><div class="modal-content">
                            <div class="modal-header"><h5 class="modal-title">Ferry Quote for Request #<?php echo $row['id']; ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                            <div class="modal-body">
                                <h6>Ferry Details from Admin:</h6>
                                <div class="p-3 bg-light rounded mb-3"><pre style="white-space: pre-wrap; font-family: inherit; font-size: 1rem;"><?php echo htmlspecialchars($row['admin_notes']); ?></pre></div>
                                <hr>
                                <div class="text-end">
                                    <p class="mb-1">Your current wallet balance: <strong>₱<?php echo number_format($wallet_balance, 2); ?></strong></p>
                                    <h4 class="mb-3">Total Price: <strong class="text-success">₱<?php echo number_format($row['total_price'], 2); ?></strong></h4>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <form method="POST" onsubmit="return confirm('Confirm payment of ₱<?php echo number_format($row['total_price'], 2); ?> from your wallet?');">
                                    <input type="hidden" name="booking_id" value="<?php echo $row['id']; ?>"><input type="hidden" name="total_price" value="<?php echo $row['total_price']; ?>">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                    <button type="submit" name="pay_ferry_from_wallet" class="btn btn-primary" <?php if($wallet_balance < $row['total_price']) echo 'disabled'; ?>><?php echo ($wallet_balance < $row['total_price']) ? 'Insufficient Funds' : 'Pay from Wallet'; ?></button>
                                </form>
                            </div>
                        </div></div>
                    </div>
                    <?php endwhile; else: ?>
                    <tr><td colspan="4" class="text-center text-muted p-4">You have no ferry bookings. <a href="../ferries.php">Book a ferry now!</a></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
