<?php
require 'db.php';
require 'functions.php';
requireRole(['admin']);

$pagetitle = 'Create Payment Order';
$activemenu = 'payments';
require 'header.php';
?>

<div class="dfp-card" style="max-width:600px;">
  <h3>Create Payment Order (Incomplete Payment)</h3>
  <p style="color:var(--clr-gray-mid);font-size:var(--fontsize-sm);">
    Select an approved villager whose payment is still unpaid. This generates a Razorpay order and a payment
    link that can be sent to the villager via SMS/WhatsApp to complete the payment on their phone.
  </p>
  <div class="dfp-formgroup">
    <label>Villager (Approved, Unpaid)</label>
    <select id="selVillager" style="width:100%;"></select>
  </div>
  <button class="btn" id="btnCreateOrder">Create Order &amp; Generate Link</button>

  <div id="orderResult" style="display:none;margin-top:14px;" class="dfp-card">
    <p><b>Order ID:</b> <span id="resOrderId"></span></p>
    <p><b>Payment Link:</b> <a id="resPayLink" href="#" target="_blank"></a></p>
    <button class="btn btn-sm" id="btnSendSms">Send via SMS</button>
    <button class="btn btn-sm" id="btnSendWhatsapp">Send via WhatsApp</button>
  </div>
</div>

<?php require 'footer.php'; ?>
<script>
var lastVillagerId = null;

function loadUnpaidVillagers() {
  $.getJSON('ajax_admin_payment.php', { action: 'listunpaid' }, function (resp) {
    var sel = $('#selVillager').empty();
    (resp.data || []).forEach(function (v) {
      sel.append('<option value="' + v.id + '">' + v.fullname + ' (' + v.phone + ')</option>');
    });
  });
}

$(function () {
  loadUnpaidVillagers();

  $('#btnCreateOrder').on('click', function () {
    var btn = $(this);
    var villagerid = $('#selVillager').val();
    if (!villagerid) { dfpToast('Please select a villager', 'error'); return; }
    if (btn.prop('disabled')) { return; }
    btn.prop('disabled', true);

    $.post('ajax_admin_payment.php', { action: 'createorder', villagerid: villagerid }, function (resp) {
      btn.prop('disabled', false);
      dfpToast(resp.message, resp.success ? 'success' : 'error');
      if (resp.success) {
        lastVillagerId = villagerid;
        $('#resOrderId').text(resp.data.orderid);
        $('#resPayLink').attr('href', resp.data.paylink).text(resp.data.paylink);
        $('#orderResult').show();
        loadUnpaidVillagers();
      }
    }, 'json').fail(function () { btn.prop('disabled', false); });
  });

  $('#btnSendSms').on('click', function () {
    $.post('ajax_admin_payment.php', { action: 'sendlink', villagerid: lastVillagerId, via: 'sms' }, function (resp) {
      dfpToast(resp.message, resp.success ? 'success' : 'error');
    }, 'json');
  });

  $('#btnSendWhatsapp').on('click', function () {
    $.post('ajax_admin_payment.php', { action: 'sendlink', villagerid: lastVillagerId, via: 'whatsapp' }, function (resp) {
      dfpToast(resp.message, resp.success ? 'success' : 'error');
    }, 'json');
  });
});
</script>
<?php require 'footer2.php'; ?>
