<?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 FLIGHT BOOKING
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['pay_flight_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 flight_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-flight-bookings.php?payment=success");
            exit();
        } catch (mysqli_sql_exception $exception) {
            $conn->rollback();
            header("Location: my-flight-bookings.php?payment=error");
            exit();
        }
    } else {
        header("Location: my-flight-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 Flight Bookings</h1>
</div>
<?php 
if(isset($_GET['request']) && $_GET['request'] == 'success') echo '<div class="alert alert-success">Your flight request has been sent! Our agents will review it and provide a quote shortly.</div>';
if(isset($_GET['payment'])) {
    if ($_GET['payment'] == 'success') echo '<div class="alert alert-success">Payment successful! Your flight booking is confirmed. We will send your e-ticket shortly.</div>';
    if ($_GET['payment'] == 'error') echo '<div class="alert alert-danger">An error occurred during payment.</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 Flight Requests</div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
            <thead><tr><th>Request Date</th><th>Itinerary</th><th>Passengers</th><th>Status</th><th class="text-center">Action</th></tr></thead>
            <tbody>
                <?php 
                $stmt = $conn->prepare("SELECT fb.*, orig.city as origin_city, dest.city as dest_city FROM flight_bookings fb JOIN airports orig ON fb.origin_id = orig.id JOIN airports dest ON fb.destination_id = dest.id WHERE fb.user_id = ? ORDER BY fb.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><?php echo date('M d, Y', strtotime($row['created_at'])); ?></td>
                    <td><strong><?php echo htmlspecialchars($row['origin_city'] . ' → ' . $row['dest_city']); ?></strong><br><small class="text-muted"><?php echo date('M d, Y', strtotime($row['departure_date'])); ?><?php if($row['return_date']) echo ' - ' . date('M d, Y', strtotime($row['return_date'])); ?></small></td>
                    <td><?php echo $row['num_adults'] + $row['num_children'] + $row['num_infants']; ?></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 bg-<?php echo $row['payment_status'] == 'Paid' ? 'success' : '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=flight&id=<?php echo $row['id']; ?>" target="_blank" class="btn btn-sm btn-info"><i class="bi bi-ticket-perforated-fill"></i> View E-Ticket</a>
                        <?php else: ?>
                            <button class="btn btn-sm btn-secondary" disabled>No Action</button>
                        <?php endif; ?>
                    </td>
                </tr>
                
                <div class="modal fade" id="quoteModal<?php echo $row['id']; ?>" tabindex="-1">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header"><h5 class="modal-title">Flight 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>Itinerary 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('Are you sure you want to pay ₱<?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_flight_from_wallet" class="btn btn-primary" <?php if($wallet_balance < $row['total_price']) echo 'disabled'; ?>><?php echo ($wallet_balance < $row['total_price']) ? 'Insufficient Funds' : 'Confirm & Pay from Wallet'; ?></button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endwhile; else: ?>
                    <tr><td colspan="5" class="text-center text-muted p-4">You have not requested any flights yet. <a href="../flights.php">Find a flight now!</a></td></tr>
                <?php endif; ?>
            </tbody>
            </table>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
