<?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 TOUR BOOKING FROM WALLET
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['pay_tour_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 bookings SET payment_status = 'Paid' 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-tour-bookings.php?payment=success");
            exit();
        } catch (mysqli_sql_exception $exception) {
            $conn->rollback();
            header("Location: my-tour-bookings.php?payment=error");
            exit();
        }
    } else {
        header("Location: my-tour-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 Tours & Service 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 booking is confirmed.</div>';
    if ($_GET['payment'] == 'error') echo '<div class="alert alert-danger">An error occurred during payment. Please 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 submitted.</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-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-dark">
                    <tr><th>Tour/Service Name</th><th>Booking Date</th><th>Status</th><th class="text-center">Actions</th></tr>
                </thead>
                <tbody>
                    <?php
                    $sql = "SELECT b.*, t.title as tour_title, 
                                   (SELECT COUNT(*) FROM reviews r WHERE r.booking_id = b.id AND r.item_type = 'tour') as review_count,
                                   (SELECT COUNT(*) FROM messages m WHERE m.booking_id = b.id AND m.booking_type = 'tour' AND m.is_read = 0 AND m.recipient_id = ?) as unread_messages
                            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("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['tour_title']); ?></strong>
                            <br><small class="text-muted">Ref: <?php echo htmlspecialchars($row['booking_ref']); ?> • <?php echo $row['num_travelers']; ?> traveler(s)</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 ms-1"><?php echo htmlspecialchars($row['status']); ?></span></td>
                        <td class="text-center">
                            <div class="btn-group">
                                <a href="view-messages.php?type=tour&booking_id=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-secondary position-relative">
                                    Messages
                                    <?php if($row['unread_messages'] > 0): ?>
                                    <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"><?php echo $row['unread_messages']; ?></span>
                                    <?php endif; ?>
                                </a>
                                <?php if ($row['payment_status'] == 'Unpaid'): ?>
                                    <form method="POST" class="d-inline" 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="submit" name="pay_tour_from_wallet" class="btn btn-sm btn-success">Pay</button></form>
                                <?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">Ticket</a>
                                <?php endif; ?>
                                <?php if ($row['status'] == 'Completed' && $row['review_count'] == 0): ?>
                                    <a href="leave-review.php?booking_id=<?php echo $row['id']; ?>&item_id=<?php echo $row['tour_id']; ?>&item_type=tour" class="btn btn-sm btn-primary">Review</a>
                                <?php elseif ($row['status'] == 'Completed' && $row['review_count'] > 0): ?>
                                    <button class="btn btn-sm btn-light border" disabled>Reviewed</button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; else: ?>
                        <tr><td colspan="4" class="text-center text-muted p-4">You have not booked any tours or services yet. <a href="../services.php">Explore now!</a></td></tr>
                    <?php endif; $stmt->close(); ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
