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

use App\Core\Database;

$db = Database::connect();

$ref = $_GET['ref'] ?? '';

if (!$ref) {
    die('Invalid booking reference.');
}

$stmt = $db->prepare("
    SELECT b.*, s.service_name, pr.pricing_type,
           pr.base_price, pr.hourly_rate, pr.minimum_hours
    FROM bookings b
    JOIN services s ON s.id = b.service_id
    JOIN price_rules pr ON pr.service_id = b.service_id
    WHERE b.booking_reference = ?
    LIMIT 1
");
$stmt->execute([$ref]);
$booking = $stmt->fetch();

if (!$booking) {
    die('Booking not found.');
}

if ($booking['status'] !== 'pending') {
    die('This booking can no longer be modified.');
}

$zones = $db->query("SELECT * FROM zones ORDER BY id ASC")->fetchAll();

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>

<?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">
Modify Booking – <?php echo htmlspecialchars($booking['booking_reference']); ?>
</h4>

<form id="editBookingForm">

<input type="hidden" name="booking_reference"
value="<?php echo htmlspecialchars($booking['booking_reference']); ?>">

<input type="hidden" name="csrf_token"
value="<?php echo $_SESSION['csrf_token']; ?>">

<!-- Pickup -->
<div class="form-group">
<label>Pickup Address</label>
<input type="text"
class="form-control"
name="pickup_address"
value="<?php echo htmlspecialchars($booking['pickup_address']); ?>"
required>
</div>

<!-- Dropoff -->
<div class="form-group">
<label>Drop-off Address</label>
<input type="text"
class="form-control"
name="dropoff_address"
value="<?php echo htmlspecialchars($booking['dropoff_address']); ?>">
</div>

<!-- Pickup Date -->
<div class="form-group">
<label>Pickup Date & Time</label>
<input type="datetime-local"
class="form-control"
name="pickup_datetime"
value="<?php echo date('Y-m-d\TH:i', strtotime($booking['pickup_datetime'])); ?>"
required>
</div>

<!-- Flight -->
<?php if (!empty($booking['flight_number'])): ?>
<div class="form-group">
<label>Flight Number</label>
<input type="text"
class="form-control"
name="flight_number"
value="<?php echo htmlspecialchars($booking['flight_number']); ?>">
</div>
<?php endif; ?>

<!-- Zone -->
<?php if ($booking['pricing_type'] === 'zone'): ?>
<div class="form-group">
<label>Pickup Zone</label>
<select name="zone_id" class="form-control" required>
<?php foreach ($zones as $zone): ?>
<option value="<?php echo $zone['id']; ?>"
<?php if ($zone['id'] == $booking['zone_id']) echo 'selected'; ?>>
<?php echo htmlspecialchars($zone['zone_name']); ?>
($<?php echo number_format($zone['price_modifier'],2); ?>)
</option>
<?php endforeach; ?>
</select>
</div>
<?php endif; ?>

<!-- Hourly -->
<?php if ($booking['pricing_type'] === 'hourly'): ?>
<div class="form-group">
<label>Number of Hours (Minimum <?php echo $booking['minimum_hours']; ?>)</label>
<input type="number"
class="form-control"
name="hours"
min="<?php echo $booking['minimum_hours']; ?>"
value="<?php echo $booking['hours']; ?>"
required>
</div>
<?php endif; ?>

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

</form>

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

<script>
document.getElementById("editBookingForm")
.addEventListener("submit", function(e){

e.preventDefault();

fetch("process_edit_booking.php", {
method: "POST",
body: new FormData(this)
})
.then(res => res.json())
.then(data => {

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

window.location.href = "booking_success.php?ref=" + data.ref;

})
.catch(() => {
alert("Server error. Please try again.");
});

});
</script>

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