<?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 HOTEL BOOKING
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['pay_hotel_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 hotel_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')");
            $conn->commit();
            header("Location: my-hotel-bookings.php?payment=success");
            exit();
        } catch (mysqli_sql_exception $exception) {
            $conn->rollback();
            header("Location: my-hotel-bookings.php?payment=error");
            exit();
        }
    } else {
        header("Location: my-hotel-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 Hotel Bookings</h1>
</div>

<?php 
if(isset($_GET['request']) && $_GET['request'] == 'success') echo '<div class="alert alert-success">Your booking request has been sent! You will be notified once it is confirmed by an admin.</div>';
if(isset($_GET['payment'])) {
    if ($_GET['payment'] == 'success') echo '<div class="alert alert-success">Payment successful! Your hotel 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 your wallet</a> first.</div>';
}
?>

<div class="card shadow-sm">
    <div class="card-header">Your Hotel Booking Requests</div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead><tr><th>Hotel & Room</th><th>Dates</th><th>Price</th><th>Status</th><th class="text-center">Action</th></tr></thead>
                <tbody>
                    <?php
                    $stmt = $conn->prepare("SELECT b.*, h.name as hotel_name, r.room_type_name FROM hotel_bookings b JOIN hotels h ON b.hotel_id = h.id JOIN hotel_rooms r ON b.room_id = r.id WHERE b.user_id = ? ORDER BY b.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><strong><?php echo htmlspecialchars($row['hotel_name']); ?></strong><br><small class="text-muted"><?php echo htmlspecialchars($row['room_type_name']); ?></small></td>
                        <td><?php echo date("M d, Y", strtotime($row['check_in_date'])); ?> - <?php echo date("M d, Y", strtotime($row['check_out_date'])); ?></td>
                        <td><?php echo $row['total_price'] ? '₱'.number_format($row['total_price'], 2) : '<span class="text-muted">N/A</span>'; ?></td>
                        <td>
                            <?php $status_class = ['Pending Confirmation' => 'bg-secondary', 'Confirmed' => 'bg-warning text-dark', 'Cancelled' => 'bg-danger', 'Completed' => 'bg-info']; ?>
                            <span class="badge <?php echo $status_class[$row['status']]; ?>"><?php echo $row['status']; ?></span>
                            <?php if ($row['status'] == 'Confirmed' || $row['status'] == 'Completed'): ?>
                                <span class="badge <?php echo $row['payment_status'] == 'Paid' ? 'bg-success' : 'bg-warning text-dark'; ?>"><?php echo $row['payment_status']; ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center">
                            <?php if ($row['status'] == 'Confirmed' && $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_hotel_from_wallet" class="btn btn-sm btn-primary">Pay from Wallet</button>
                                </form>
                            <?php elseif ($row['payment_status'] == 'Paid'): ?>
                                <a href="generate-ticket.php?type=hotel&id=<?php echo $row['id']; ?>" target="_blank" class="btn btn-sm btn-info"><i class="bi bi-ticket-perforated-fill"></i> View Voucher</a>
                            <?php else: ?>
                                <button class="btn btn-sm btn-secondary" disabled>No Action</button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endwhile; else: ?>
                        <tr><td colspan="5" class="text-center text-muted p-4">You have no hotel bookings. <a href="../hotels.php">Find a hotel now!</a></td></tr>
                    <?php endif; $stmt->close(); ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
