<?php
// --- LOGIC BLOCK: All PHP processing must happen before any HTML is sent ---
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 FROM WALLET
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 {
            // 1. Process the payment
            $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')");

            // --- AWARD AFFILIATE COMMISSION LOGIC ---
            $first_booking_check_sql = "SELECT ((SELECT COUNT(*) FROM bookings WHERE user_id = ? AND payment_status = 'Paid') + (SELECT COUNT(*) FROM hotel_bookings WHERE user_id = ? AND payment_status = 'Paid') + (SELECT COUNT(*) FROM flight_bookings WHERE user_id = ? AND payment_status = 'Paid') + (SELECT COUNT(*) FROM ferry_bookings WHERE user_id = ? AND payment_status = 'Paid')) as total_paid_bookings";
            $stmt_first_check = $conn->prepare($first_booking_check_sql);
            $stmt_first_check->bind_param("iiii", $user_id, $user_id, $user_id, $user_id);
            $stmt_first_check->execute();
            $first_booking_count = $stmt_first_check->get_result()->fetch_assoc()['total_paid_bookings'];
            
            if ($first_booking_count === 1) {
                $referrer_check_stmt = $conn->prepare("SELECT referred_by FROM users WHERE id = ?");
                $referrer_check_stmt->bind_param("i", $user_id);
                $referrer_check_stmt->execute();
                $referrer_check = $referrer_check_stmt->get_result()->fetch_assoc();
                
                if ($referrer_check && !empty($referrer_check['referred_by'])) {
                    $referrer_id = $referrer_check['referred_by'];
                    $affiliate_settings_res = $conn->query("SELECT * FROM site_settings WHERE setting_name LIKE 'affiliate_reward_%'");
                    $affiliate_settings = array_column($affiliate_settings_res->fetch_all(MYSQLI_ASSOC), 'setting_value', 'setting_name');
                    $reward_type = $affiliate_settings['affiliate_reward_type'] ?? 'fixed';
                    $reward_value = floatval($affiliate_settings['affiliate_reward_value'] ?? 0);
                    $commission = ($reward_type == 'fixed') ? $reward_value : ($total_price * ($reward_value / 100));
                    if ($commission > 0) {
                        $conn->query("UPDATE users SET affiliate_earnings = affiliate_earnings + $commission WHERE id = $referrer_id");
                        $trans_note = "Commission from user #$user_id first booking";
                        $conn->query("INSERT INTO transactions (user_id, transaction_type, amount, status, admin_notes) VALUES ($referrer_id, 'Affiliate Commission', $commission, 'Completed', '$trans_note')");
                    }
                }
            }
            
            $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! An agent will find the best deal 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.</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-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-dark"><tr><th>Itinerary</th><th>Departure Date</th><th>Status</th><th class="text-center">Action</th></tr></thead>
                <tbody>
                    <?php
                    $sql = "SELECT b.*, orig.city as origin_city, dest.city as dest_city,
                                   (SELECT COUNT(*) FROM messages m WHERE m.booking_id = b.id AND m.booking_type = 'flight' AND m.is_read = 0 AND m.recipient_id = ?) as unread_messages
                            FROM flight_bookings b
                            JOIN airports orig ON b.origin_id = orig.id
                            JOIN airports dest ON b.destination_id = dest.id
                            WHERE b.user_id = ? ORDER BY b.departure_date DESC";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("ii", $user_id, $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">Ref: <?php echo htmlspecialchars($row['booking_ref']); ?> • <?php echo htmlspecialchars($row['trip_type']); ?></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'; ?> ms-1"><?php echo $row['payment_status']; ?></span><?php endif; ?>
                        </td>
                        <td class="text-center">
                            <div class="btn-group">
                                <a href="view-messages.php?type=flight&booking_id=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-secondary position-relative">Messages <?php if($row['unread_messages'] > 0) echo '<span class="badge bg-danger rounded-pill">'.$row['unread_messages'].'</span>'; ?></a>
                                <?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>Pending Quote</button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <div class="modal fade" id="quoteModal<?php echo $row['id']; ?>"><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['booking_ref']; ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                        <div class="modal-body">
                            <h6>Itinerary 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 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('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' : '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 not requested any flights yet. <a href="../flights.php">Request a flight now!</a></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div></div></div>
<?php include 'footer.php'; ?>
