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

$id = (int)($_GET['id'] ?? 0);
$panchayatid = currentPanchayatId();

$stmt = $pdo->prepare("SELECT v.*, p.name AS panchayatname FROM villager v
    LEFT JOIN panchayat p ON p.id = v.panchayatid
    WHERE v.id = ? AND v.isdeleted = 0 AND v.panchayatid = ?");
$stmt->execute([$id, $panchayatid]);
$v = $stmt->fetch();

$pagetitle = 'Registration Detail';
$activemenu = 'registrations';
require 'header.php';

if (!$v) {
    echo '<div class="dfp-card">Registration not found or does not belong to your panchayat.</div>';
    require 'footer.php';
    require 'footer2.php';
    exit;
}

$vehiclestmt = $pdo->prepare("SELECT vehiclenumber FROM villagervehicle WHERE villagerid = ? AND isdeleted = 0");
$vehiclestmt->execute([$id]);
$vehicles = $vehiclestmt->fetchAll();
?>

<div class="dfp-card">
  <?php if ($v['verifymethod'] === 'house'): ?>
    <div class="dfp-manualbanner">⚠ Verified via House Number - this needs manual address confirmation (no Aadhaar on file).</div>
  <?php endif; ?>
  <h3><?php echo safeOut($v['fullname']); ?>
    <span class="badge <?php echo $v['status'] === 'approved' ? 'badge-approved' : ($v['status'] === 'rejected' ? 'badge-rejected' : 'badge-pending'); ?>" style="float:right;">
      <?php echo safeOut($v['status']); ?>
    </span>
  </h3>
  <div style="display:flex;gap:20px;flex-wrap:wrap;">
    <div style="flex:0 0 120px;">
      <?php if ($v['photo']): ?>
        <img src="uploads/photos/<?php echo safeOut($v['photo']); ?>"
             style="width:110px;height:110px;object-fit:cover;border:1px solid var(--clr-border);border-radius:4px;"
             onerror="this.style.display='none';this.nextElementSibling.style.display='flex';">
        <div style="display:none;width:110px;height:110px;border:1px dashed var(--clr-border);border-radius:4px;align-items:center;justify-content:center;text-align:center;font-size:var(--fontsize-sm);color:var(--clr-gray-mid);">Photo not found</div>
      <?php else: ?>
        <div style="width:110px;height:110px;border:1px dashed var(--clr-border);border-radius:4px;display:flex;align-items:center;justify-content:center;text-align:center;font-size:var(--fontsize-sm);color:var(--clr-gray-mid);">No Photo</div>
      <?php endif; ?>
    </div>
    <div style="flex:1;min-width:220px;">
      <p><b>Phone:</b> <?php echo safeOut($v['phone']); ?></p>
      <p><b>Address:</b> <?php echo safeOut($v['address']); ?> <?php echo $v['houseno'] ? '(House No: ' . safeOut($v['houseno']) . ')' : ''; ?></p>
      <p><b>DOB / Age:</b> <?php echo safeOut($v['dob']); ?> / <?php echo safeOut($v['age']); ?></p>
      <p><b>Verification Method:</b> <?php echo safeOut($v['verifymethod']); ?>
        <?php echo $v['hasaadhaar'] == 1 ? '(Aadhaar: ' . safeOut(substr($v['aadhaarnumber'], -4)) . '-masked)' : ''; ?></p>
    </div>
    <div style="flex:1;min-width:220px;">
      <p><b>Payment Status:</b> <?php echo safeOut($v['paymentstatus']); ?></p>
      <p><b>Pass Active:</b> <?php echo $v['passactive'] == 1 ? 'Yes' : 'No'; ?></p>
      <p><b>Pass Validity:</b> <?php echo safeOut($v['passstartdate']) . ' to ' . safeOut($v['passenddate']); ?></p>
      <p><b>Vehicles:</b> <?php echo $vehicles ? implode(', ', array_map(fn($x) => safeOut($x['vehiclenumber']), $vehicles)) : '-'; ?></p>
    </div>
  </div>

  <div style="margin-top:10px;">
    <?php if ($v['status'] === 'pending'): ?>
      <button class="btn btn-sm" onclick="doAction('approve')">Approve</button>
      <button class="btn btn-danger btn-sm" onclick="promptReject()">Reject</button>
    <?php elseif ($v['status'] === 'approved' && $v['passactive'] == 1): ?>
      <button class="btn btn-danger btn-sm" onclick="promptDeactivate()">Deactivate Pass</button>
    <?php endif; ?>
  </div>
</div>

<?php require 'footer.php'; ?>
<script>
function doAction(action, extra) {
  var payload = { action: action, id: <?php echo (int)$id; ?> };
  if (extra) { Object.assign(payload, extra); }
  $.post('ajax_panchayat_registration.php', payload, function (resp) {
    dfpToast(resp.message, resp.success ? 'success' : 'error');
    if (resp.success) {
      setTimeout(function () { window.location.reload(); }, 900);
    }
  }, 'json');
}

function promptReject() {
  var reason = prompt('Reason for rejection (shown to the applicant):');
  if (reason === null || reason.trim() === '') { return; }
  doAction('reject', { reason: reason });
}

function promptDeactivate() {
  var reason = prompt('Reason for deactivation:');
  if (reason === null || reason.trim() === '') { return; }
  doAction('deactivate', { reason: reason });
}
</script>
<?php require 'footer2.php'; ?>
