<?php
require 'db.php';
require 'functions.php';

$orderid = cleanInput($_GET['order'] ?? '');

$stmt = $pdo->prepare("SELECT po.*, v.fullname, v.phone FROM paymentorder po
    JOIN villager v ON v.id = po.villagerid WHERE po.razorpayorderid = ? AND po.isdeleted = 0");
$stmt->execute([$orderid]);
$order = $stmt->fetch();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pay Ferry Pass Fee - Divar Ferry Pass App</title>
<link rel="icon" href="logo.png" type="image/png">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="dfpToastWrap"><div class="dfp-toast" id="dfpToastBox"></div></div>

<div class="dfp-loginwrap" style="max-width:400px;">
  <img src="logo.png" class="logo" alt="logo">

  <?php if (!$order): ?>
    <p>This payment link is invalid or has expired.</p>
  <?php elseif ($order['status'] === 'paid'): ?>
    <h3>Already Paid</h3>
    <p>This registration fee has already been paid. Thank you.</p>
  <?php else: ?>
    <h3>Ferry Pass Registration Fee</h3>
    <p><b><?php echo safeOut($order['fullname']); ?></b></p>
    <p style="font-size:22px;font-weight:700;"><?php echo formatINR($order['amount']); ?></p>
    <button class="btn" id="btnPay" style="width:100%;">Pay Now</button>
  <?php endif; ?>
</div>

<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
<?php if ($order && $order['status'] !== 'paid'): ?>
document.getElementById('btnPay').addEventListener('click', function () {
  var btn = this;
  if (btn.disabled) { return; }
  btn.disabled = true;

  var options = {
    key: '<?php echo RAZORPAYKEYID; ?>',
    amount: <?php echo (int)bcmul(moneyStr($order['amount']), '100', 0); ?>,
    currency: 'INR',
    name: 'Divar Ferry Pass App',
    description: 'Ferry Pass Registration Fee',
    order_id: '<?php echo safeOut($order['razorpayorderid']); ?>',
    prefill: { name: '<?php echo safeOut($order['fullname']); ?>', contact: '<?php echo safeOut($order['phone']); ?>' },
    handler: function (response) {
      $.post('ajax_payment_verify.php', {
        razorpay_order_id: response.razorpay_order_id,
        razorpay_payment_id: response.razorpay_payment_id,
        razorpay_signature: response.razorpay_signature
      }, function (resp) {
        if (resp.success) {
          window.location.href = 'payment_success.php?order=' + encodeURIComponent(response.razorpay_order_id);
        } else {
          alert(resp.message);
          btn.disabled = false;
        }
      }, 'json');
    },
    modal: { ondismiss: function () { btn.disabled = false; } }
  };
  var rzp = new Razorpay(options);
  rzp.open();
});
<?php endif; ?>
</script>
</body>
</html>
