<?php require "../includes/header.php"; ?>
<?php require "../config/config.php"; ?>

<?php
// Redirect if not logged in
if(!isset($_SESSION['username'])){
    echo "<script>window.location.href='". APPURL . "/auth/login.php'</script>";
    exit;
}

// Only process if data was POSTed from room-single.php
if(!isset($_POST['submit'])){
    echo "<script>window.location.href='". APPURL . "'</script>";
    exit;
}

// Validate fields
if(empty($_POST['email']) || empty($_POST['phone_number']) || empty($_POST['full_name']) || empty($_POST['check_in']) || empty($_POST['check_out'])){
    echo "<script>alert('One or more fields are empty'); window.history.back();</script>";
    exit;
}

$check_in_raw  = trim($_POST['check_in']  ?? '');
$check_out_raw = trim($_POST['check_out'] ?? '');
$email         = trim($_POST['email']       ?? '');
$phone_number  = trim($_POST['phone_number'] ?? '');
$full_name     = trim($_POST['full_name']   ?? '');
$hotel_name    = trim($_POST['hotel_name']  ?? '');
$room_name     = trim($_POST['room_name']   ?? '');
$room_id       = (int)($_POST['room_id']   ?? 0);
$user_id       = $_SESSION['id'];
$price         = (float)($_POST['price']   ?? 0);

// â”€â”€ Date normalizer â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
// HTML5 type="date" always submits YYYY-MM-DD, but we normalise
// with strtotime() as a safety net in case of any browser quirk.
$ts_in  = strtotime($check_in_raw);
$ts_out = strtotime($check_out_raw);

if (!$ts_in || !$ts_out) {
    echo "<script>alert('Invalid check-in or check-out date. Please go back and select valid dates.'); window.history.back();</script>";
    exit;
}

$check_in  = date('Y-m-d', $ts_in);   // guaranteed YYYY-MM-DD
$check_out = date('Y-m-d', $ts_out);  // guaranteed YYYY-MM-DD

if ($check_out <= $check_in) {
    echo "<script>alert('Check-out date must be at least one day after check-in. Please go back and correct the dates.'); window.history.back();</script>";
    exit;
}
// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

// Calculate total amount (price Ã— nights)
$nights = ($ts_out - $ts_in) / (60 * 60 * 24);
if ($nights < 1) $nights = 1;
$total_amount   = $price * $nights;          // in GHS (Ghana Cedis)
$amount_pesewas = $total_amount * 100;        // Paystack uses pesewas

// Generate unique transaction reference
$ref = 'HB-' . strtoupper(uniqid());

// Store booking as pending in DB
$booking = $conn->prepare("INSERT INTO bookings (check_in, check_out, email, phone_number, full_name, hotel_name, room_name, user_id, price, payment_status, transaction_ref) 
   VALUES (:check_in, :check_out, :email, :phone_number, :full_name, :hotel_name, :room_name, :user_id, :price, 'pending', :transaction_ref)");

$booking->execute([
    "check_in"        => $check_in,
    "check_out"       => $check_out,
    "email"           => $email,
    "phone_number"    => $phone_number,
    "full_name"       => $full_name,
    "hotel_name"      => $hotel_name,
    "room_name"       => $room_name,
    "user_id"         => $user_id,
    "price"           => $total_amount,
    "transaction_ref" => $ref,
]);
$booking_id = $conn->lastInsertId();
?>

    <div class="hero-wrap js-fullheight" style="background-image: url('<?php echo APPURL; ?>/images/hotel-bg.jpg');" data-stellar-background-ratio="0.5">
      <div class="overlay"></div>
      <div class="container">
        <div class="row no-gutters slider-text js-fullheight align-items-center justify-content-start" data-scrollax-parent="true">
          <div class="col-md-7 ftco-animate">
            <h2 class="subheading">Secure Payment</h2>
            <h1 class="mb-4">Complete Your Booking</h1>
          </div>
        </div>
      </div>
    </div>

    <section class="ftco-section ftco-book ftco-no-pt ftco-no-pb">
      <div class="container">
        <div class="row justify-content-center">
          <div class="col-lg-6 mt-5 mb-5">
            <div class="appointment-form p-4 p-md-5">
              <h3 class="mb-4">Booking Summary</h3>

              <table class="table table-bordered mb-4">
                <tr><th>Hotel</th><td><?php echo htmlspecialchars($hotel_name); ?></td></tr>
                <tr><th>Room</th><td><?php echo htmlspecialchars($room_name); ?></td></tr>
                <tr><th>Guest</th><td><?php echo htmlspecialchars($full_name); ?></td></tr>
                <tr><th>Email</th><td><?php echo htmlspecialchars($email); ?></td></tr>
                <tr><th>Phone</th><td><?php echo htmlspecialchars($phone_number); ?></td></tr>
                <tr><th>Check-In</th><td><?php echo htmlspecialchars($check_in); ?></td></tr>
                <tr><th>Check-Out</th><td><?php echo htmlspecialchars($check_out); ?></td></tr>
                <tr><th>Nights</th><td><?php echo $nights; ?></td></tr>
                <tr><th>Price/Night</th><td>GH&#8373;<?php echo number_format($price, 2); ?></td></tr>
                <tr class="table-success"><th><strong>Total</strong></th><td><strong>GH&#8373;<?php echo number_format($total_amount, 2); ?></strong></td></tr>
              </table>

              <button onclick="payWithPaystack()" class="btn btn-primary py-3 px-5 w-100">
                <i class="fa fa-credit-card mr-2"></i> Pay GH&#8373;<?php echo number_format($total_amount, 2); ?> with Paystack
              </button>

              <p class="mt-3 text-center text-muted small">
                <i class="fa fa-lock"></i> Secured by Paystack &mdash; SSL Encrypted
              </p>
            </div>
          </div>
        </div>
      </div>
    </section>

<?php require "../includes/footer.php"; ?>

<!-- Paystack Inline Script -->
<script src="https://js.paystack.co/v1/inline.js"></script>
<script>
  function payWithPaystack() {
    var handler = PaystackPop.setup({
      key: '<?php echo PAYSTACK_PUBLIC_KEY; ?>',
      email: '<?php echo htmlspecialchars($email); ?>',
      amount: <?php echo $amount_pesewas; ?>,
      currency: 'GHS',
      ref: '<?php echo $ref; ?>',
      metadata: {
        custom_fields: [
          { display_name: "Full Name", variable_name: "full_name", value: "<?php echo htmlspecialchars($full_name); ?>" },
          { display_name: "Hotel",     variable_name: "hotel_name", value: "<?php echo htmlspecialchars($hotel_name); ?>" },
          { display_name: "Room",      variable_name: "room_name",  value: "<?php echo htmlspecialchars($room_name); ?>" }
        ]
      },
      callback: function(response) {
        // On successful payment, redirect to verify
        window.location.href = '<?php echo APPURL; ?>/bookings/verify-payment.php?reference=' + response.reference + '&booking_id=<?php echo $booking_id; ?>';
      },
      onClose: function() {
        alert('Payment window closed. Your booking is saved as pending â€” you can pay later from My Bookings.');
        window.location.href = '<?php echo APPURL; ?>/bookings/my-bookings.php';
      }
    });
    handler.openIframe();
  }
</script>

