<?php
session_start();
require_once __DIR__ . '/vendor/autoload.php';

use App\Core\Database;

$db = Database::connect();

$booking = null;
$error = '';
$payment = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $ref = trim($_POST['booking_reference']);
    $email = trim($_POST['email']);

    if ($ref && $email) {

        $stmt = $db->prepare("
            SELECT b.*, s.service_name, c.name, c.email
            FROM bookings b
            JOIN services s ON s.id = b.service_id
            JOIN customers c ON c.id = b.customer_id
            WHERE b.booking_reference = ?
            AND c.email = ?
            LIMIT 1
        ");
        $stmt->execute([$ref, $email]);
        $booking = $stmt->fetch();

        if ($booking) {

            // Fetch payment record (if exists)
            $stmt = $db->prepare("
                SELECT *
                FROM payments
                WHERE booking_id = ?
                LIMIT 1
            ");
            $stmt->execute([$booking['id']]);
            $payment = $stmt->fetch();

        } else {
            $error = "Booking not found. Please check your reference and email.";
        }

    } else {
        $error = "Please enter booking reference and email.";
    }
}
?>

<?php require_once __DIR__ . '/includes/book_header.php'; ?>

<section class="section-padding">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-8">

<div class="booking-card p-5">

<h4 class="gold-text mb-4">View / Manage Booking</h4>

<?php if (!$booking): ?>

<form method="POST">

<div class="form-group">
<label>Booking Reference</label>
<input type="text" class="form-control" name="booking_reference" required>
</div>

<div class="form-group">
<label>Email Address</label>
<input type="email" class="form-control" name="email" required>
</div>

<?php if ($error): ?>
<div class="alert alert-danger mt-3">
<?php echo $error; ?>
</div>
<?php endif; ?>

<button type="submit"
class="btn btn-gold btn-block mt-4">
Retrieve Booking
</button>

</form>

<?php else: ?>

<hr>

<h5 class="gold-text">
Booking Reference: <?php echo htmlspecialchars($booking['booking_reference']); ?>
</h5>

<p><strong>Service:</strong>
<?php echo htmlspecialchars($booking['service_name']); ?>
</p>

<p><strong>Status:</strong>
<span class="
<?php
switch ($booking['status']) {
    case 'cancelled': echo 'text-danger'; break;
    case 'completed': echo 'text-success'; break;
    case 'accepted': echo 'text-info'; break;
    default: echo 'text-light';
}
?>">
<?php echo ucfirst(str_replace('_',' ',$booking['status'])); ?>
</span>
</p>

<p><strong>Pickup:</strong>
<?php echo htmlspecialchars($booking['pickup_address']); ?>
</p>

<p><strong>Dropoff:</strong>
<?php echo htmlspecialchars($booking['dropoff_address']); ?>
</p>

<p><strong>Date & Time:</strong>
<?php echo date('d M Y H:i',
strtotime($booking['pickup_datetime'])); ?>
</p>

<?php if (!empty($booking['flight_number'])): ?>
<p><strong>Flight:</strong>
<?php echo htmlspecialchars($booking['flight_number']); ?>
</p>
<?php endif; ?>

<?php if (!empty($booking['hours'])): ?>
<p><strong>Hours:</strong>
<?php echo htmlspecialchars($booking['hours']); ?>
</p>
<?php endif; ?>

<p><strong>Total:</strong>
<span class="gold-text">
$<?php echo number_format($booking['final_price'], 2); ?>
</span>
</p>

<hr>

<!-- ========================= -->
<!-- PAYMENT SECTION -->
<!-- ========================= -->

<?php if ($booking['status'] === 'accepted'): ?>

<div class="mt-4 p-4 bg-dark rounded">

<h5 class="gold-text">Payment</h5>

<?php if ($payment && $payment['payment_status'] === 'paid'): ?>

<p class="text-success">
Payment Completed<br>
Transaction Ref: <?php echo htmlspecialchars($payment['transaction_reference']); ?>
</p>

<?php else: ?>

<p>
Your booking has been accepted.
Please proceed with payment to confirm your reservation.
</p>

<a href="payment.php?ref=<?php echo $booking['booking_reference']; ?>"
class="btn btn-gold">
Proceed to Payment
</a>

<?php endif; ?>

</div>

<hr>

<?php endif; ?>

<!-- ========================= -->
<!-- ACTION BUTTONS -->
<!-- ========================= -->
<div class="mt-4">

<?php if ($booking['status'] === 'pending'): ?>

<a href="edit_booking.php?ref=<?php echo $booking['booking_reference']; ?>"
class="btn btn-gold">
Modify Booking
</a>

<button type="button"
class="btn btn-danger ml-2"
onclick="confirmCancel('<?php echo $booking['booking_reference']; ?>')">
Cancel Booking
</button>

<?php endif; ?>

<a href="index.php"
class="btn btn-outline-light ml-2">
Back Home
</a>

</div>

<?php endif; ?>

</div>
</div>
</div>
</div>
</section>

<script>
function confirmCancel(ref) {

    if (!confirm("Are you sure you want to cancel this booking?")) {
        return;
    }

    fetch("process_cancel_booking.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            booking_reference: ref
        })
    })
    .then(res => res.json())
    .then(data => {

        if (data.status === "error") {
            alert(data.message);
            return;
        }

        alert("Booking successfully cancelled.");
        window.location.reload();
    })
    .catch(() => {
        alert("Server error. Please try again.");
    });
}
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
