<?php include 'header.php'; 

// Handle payment from wallet
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['pay_from_wallet'])) {
    $booking_id = intval($_POST['booking_id']);
    $total_price = floatval($_POST['total_price']);

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

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

            // Create transaction record
            $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();

            $conn->commit();
            header("Location: my-bookings.php?payment=success");
            exit();
        } catch (mysqli_sql_exception $exception) {
            $conn->rollback();
            header("Location: my-bookings.php?payment=error");
            exit();
        }
    } else {
        header("Location: my-bookings.php?payment=insufficient");
        exit();
    }
}
?>

<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 Bookings</h1>
</div>

<?php 
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 try again.</div>';
    if ($_GET['payment'] == 'insufficient') echo '<div class="alert alert-warning">Insufficient wallet balance. Please top-up first.</div>';
}
?>

<div class="table-responsive">
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Tour</th>
                <th>Booking Date</th>
                <th>Travelers</th>
                <th>Total Price</th>
                <th>Status</th>
                <th>Payment Status</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $stmt = $conn->prepare("SELECT b.*, t.title as tour_title FROM bookings b JOIN tours t ON b.tour_id = t.id WHERE b.user_id = ? ORDER BY b.created_at DESC");
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            while($row = $result->fetch_assoc()):
            ?>
            <tr>
                <td><?php echo htmlspecialchars($row['tour_title']); ?></td>
                <td><?php echo date("F j, Y", strtotime($row['booking_date'])); ?></td>
                <td><?php echo $row['num_travelers']; ?></td>
                <td>₱<?php echo number_format($row['total_price'], 2); ?></td>
                <td><span class="badge bg-info"><?php echo $row['status']; ?></span></td>
                <td><span class="badge <?php echo $row['payment_status'] == 'Paid' ? 'bg-success' : 'bg-warning'; ?>"><?php echo $row['payment_status']; ?></span></td>
                <td>
                    <?php if ($row['payment_status'] == 'Unpaid'): ?>
                        <form method="POST" action="my-bookings.php" 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_from_wallet" class="btn btn-sm btn-primary">Pay from Wallet</button>
                        </form>
                    <?php else: ?>
                        -
                    <?php endif; ?>
                </td>
            </tr>
            <?php endwhile; $stmt->close(); ?>
        </tbody>
    </table>
</div>

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