<?php
// --- LOGIC BLOCK: All PHP processing must happen before any HTML is sent ---
require_once '../includes/db.php';

// Check if a user is logged in before anything else
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}
$user_id = $_SESSION['user_id'];

// ACTION HANDLING: PAY FOR TOUR BOOKING FROM WALLET
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['pay_tour_from_wallet'])) {
    
    // Fetch required data within the logic block
    $wallet_balance_for_payment = $conn->query("SELECT wallet_balance FROM users WHERE id = $user_id")->fetch_assoc()['wallet_balance'];
    $site_settings_res = $conn->query("SELECT * FROM site_settings WHERE setting_name LIKE 'affiliate_reward_%'");
    $site_settings = array_column($site_settings_res->fetch_all(MYSQLI_ASSOC), 'setting_value', 'setting_name');

    $booking_id = intval($_POST['booking_id']);
    $total_price = floatval($_POST['total_price']);

    if ($wallet_balance_for_payment >= $total_price) {
        $conn->begin_transaction();
        try {
            // 1. Deduct from user's wallet
            $stmt1 = $conn->prepare("UPDATE users SET wallet_balance = wallet_balance - ? WHERE id = ?");
            $stmt1->bind_param("di", $total_price, $user_id);
            $stmt1->execute();

            // 2. Update booking payment status to 'Paid'
            $stmt2 = $conn->prepare("UPDATE bookings SET payment_status = 'Paid' WHERE id = ? AND user_id = ?");
            $stmt2->bind_param("ii", $booking_id, $user_id);
            $stmt2->execute();

            // 3. Create a transaction record for the payment
            $stmt3 = $conn->prepare("INSERT INTO transactions (user_id, transaction_type, amount, payment_method, status) VALUES (?, 'Booking Payment', ?, 'Wallet', 'Completed')");
            $stmt3->bind_param("id", $user_id, $total_price);
            $stmt3->execute();

            // --- AWARD AFFILIATE COMMISSION LOGIC ---
            // 1. Check if this is the user's VERY FIRST paid booking of any kind
            $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')) as total";
            $stmt_first_check = $conn->prepare($first_booking_check_sql);
            $stmt_first_check->bind_param("iii", $user_id, $user_id, $user_id);
            $stmt_first_check->execute();
            $first_booking_count = $stmt_first_check->get_result()->fetch_assoc()['total'];
            
            if ($first_booking_count === 1) { // It's 1 because the current transaction is now complete
                // 2. Check if this user was referred by someone
                $referrer_check = $conn->query("SELECT referred_by FROM users WHERE id = $user_id")->fetch_assoc();
                if ($referrer_check && !empty($referrer_check['referred_by'])) {
                    $referrer_id = $referrer_check['referred_by'];
                    // 3. Get reward settings
                    $reward_type = $site_settings['affiliate_reward_type'] ?? 'fixed';
                    $reward_value = floatval($site_settings['affiliate_reward_value'] ?? 0);
                    $commission = ($reward_type == 'fixed') ? $reward_value : ($total_price * ($reward_value / 100));
                    
                    // 4. Award the commission to the referrer
                    if ($commission > 0) {
                        $stmt_award = $conn->prepare("UPDATE users SET affiliate_earnings = affiliate_earnings + ? WHERE id = ?");
                        $stmt_award->bind_param("di", $commission, $referrer_id);
                        $stmt_award->execute();
                        
                        $stmt_trans = $conn->prepare("INSERT INTO transactions (user_id, transaction_type, amount, status, admin_notes) VALUES (?, 'Affiliate Commission', ?, 'Completed', ?)");
                        $trans_note = "Commission from user #$user_id first booking";
                        $stmt_trans->bind_param("ids", $referrer_id, $commission, $trans_note);
                        $stmt_trans->execute();
                    }
                }
            }
            
            $conn->commit();
            header("Location: my-tour-bookings.php?payment=success");
            exit();
        } catch (mysqli_sql_exception $exception) {
            $conn->rollback();
            header("Location: my-tour-bookings.php?payment=error&msg=" . urlencode($exception->getMessage()));
            exit();
        }
    } else {
        header("Location: my-tour-bookings.php?payment=insufficient");
        exit();
    }
}

// --- PRESENTATION BLOCK: Now we include the header and display the page ---
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 Tour Bookings</h1>
</div>

<?php 
// Display status messages from redirects
if(isset($_GET['payment'])) {
    if ($_GET['payment'] == 'success') echo '<div class="alert alert-success">Payment successful! Your tour booking is confirmed.</div>';
    if ($_GET['payment'] == 'error') echo '<div class="alert alert-danger">An error occurred during payment. Please try again or contact support.</div>';
    if ($_GET['payment'] == 'insufficient') echo '<div class="alert alert-warning">Insufficient wallet balance. Please <a href="top-up.php">top-up your wallet</a> first.</div>';
}
if(isset($_GET['review']) && $_GET['review'] == 'success') echo '<div class="alert alert-success">Thank you! Your review has been published.</div>';
if(isset($_GET['error']) && $_GET['error'] == 'already_reviewed') echo '<div class="alert alert-warning">You have already submitted a review for this booking.</div>';
?>

<div class="card shadow-sm">
    <div class="card-header">Your Booked Tours</div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th>Tour Name</th>
                        <th>Tour Date</th>
                        <th>Status</th>
                        <th class="text-center">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $sql = "SELECT b.*, t.title as tour_title, (SELECT COUNT(*) FROM reviews r WHERE r.booking_id = b.id) as review_count 
                            FROM bookings b 
                            JOIN tours t ON b.tour_id = t.id 
                            WHERE b.user_id = ? 
                            ORDER BY b.booking_date DESC";
                    
                    $stmt = $conn->prepare($sql);
                    $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['tour_title']); ?></strong>
                            <br><small class="text-muted"><?php echo $row['num_travelers']; ?> traveler(s) • ₱<?php echo number_format($row['total_price'], 2); ?></small>
                        </td>
                        <td><?php echo date("F j, Y", strtotime($row['booking_date'])); ?></td>
                        <td>
                            <span class="badge <?php echo $row['payment_status'] == 'Paid' ? 'bg-success' : 'bg-warning text-dark'; ?>"><?php echo $row['payment_status']; ?></span>
                            <span class="badge bg-info text-dark"><?php echo htmlspecialchars($row['status']); ?></span>
                        </td>
                        <td class="text-center">
                            <?php if ($row['payment_status'] == 'Unpaid'): ?>
                                <form method="POST" class="d-inline" 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="submit" name="pay_tour_from_wallet" class="btn btn-sm btn-success">Pay from Wallet</button>
                                </form>
                            <?php elseif ($row['payment_status'] == 'Paid' && $row['status'] == 'Completed' && $row['review_count'] == 0): ?>
                                <a href="leave-review.php?booking_id=<?php echo $row['id']; ?>&tour_id=<?php echo $row['tour_id']; ?>" class="btn btn-sm btn-primary">Leave a Review</a>
                            <?php elseif ($row['payment_status'] == 'Paid' && $row['status'] == 'Completed' && $row['review_count'] > 0): ?>
                                <span class="badge bg-light text-success border border-success"><i class="bi bi-patch-check-fill"></i> Reviewed</span>
                            <?php elseif ($row['payment_status'] == 'Paid'): ?>
                                <a href="generate-ticket.php?type=tour&id=<?php echo $row['id']; ?>" target="_blank" class="btn btn-sm btn-info"><i class="bi bi-ticket-perforated-fill"></i> Download Ticket</a>
                            <?php else: ?>
                                <button class="btn btn-sm btn-secondary" disabled>No Action</button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endwhile; else: ?>
                        <tr><td colspan="4" class="text-center text-muted p-4">You have not booked any tours yet. <a href="../services.php">Explore our tours & services now!</a></td></tr>
                    <?php endif; $stmt->close(); ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
