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

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

$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");
$stmt->execute([$id]);
$v = $stmt->fetch();

$pagetitle = 'Villager Detail';
$activemenu = 'villagers';
require 'header.php';

if (!$v) {
    echo '<div class="dfp-card">Villager record not found.</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();

$paymentstmt = $pdo->prepare("SELECT * FROM paymentorder WHERE villagerid = ? AND isdeleted = 0 ORDER BY id DESC");
$paymentstmt->execute([$id]);
$payments = $paymentstmt->fetchAll();

$ridestmt = $pdo->prepare("SELECT scandatetime, result FROM ridelog WHERE villagerid = ? AND isdeleted = 0 ORDER BY scandatetime DESC LIMIT 20");
$ridestmt->execute([$id]);
$rides = $ridestmt->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>Panchayat:</b> <?php echo safeOut($v['panchayatname']); ?></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']); ?></p>
    </div>
    <div style="flex:1;min-width:220px;">
      <p><b>Payment Status:</b> <?php echo safeOut($v['paymentstatus']); ?> <?php echo $v['paidat'] ? '(' . safeOut($v['paidat']) . ')' : ''; ?></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>Barcode:</b> <?php echo safeOut($v['barcodetext']); ?></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['passactive'] == 1): ?>
      <button class="btn btn-danger btn-sm" onclick="doAction('deactivate')">Deactivate Pass</button>
    <?php elseif ($v['status'] === 'approved' && $v['paymentstatus'] === 'paid'): ?>
      <button class="btn btn-sm" onclick="doAction('activate')">Activate Pass</button>
    <?php endif; ?>
    <button class="btn btn-outline btn-sm" onclick="doAction('delete')">Delete Record</button>
  </div>
</div>

<div class="dfp-card">
  <h3>Payment Orders</h3>
  <table class="dfp-table" style="width:100%;">
    <thead><tr><th>Order ID</th><th>Payment ID</th><th>Amount</th><th>Status</th><th>Created By</th><th>Paid At</th></tr></thead>
    <tbody>
      <?php foreach ($payments as $p): ?>
        <tr>
          <td><?php echo safeOut($p['razorpayorderid']); ?></td>
          <td><?php echo safeOut($p['razorpaypaymentid']); ?></td>
          <td><?php echo formatINR($p['amount']); ?></td>
          <td><?php echo safeOut($p['status']); ?></td>
          <td><?php echo safeOut($p['createdbytype']); ?></td>
          <td><?php echo safeOut($p['paidat']); ?></td>
        </tr>
      <?php endforeach; ?>
      <?php if (!$payments): ?><tr><td colspan="6">No payment orders yet.</td></tr><?php endif; ?>
    </tbody>
  </table>
</div>

<div class="dfp-card">
  <h3>Recent Ride Scans</h3>
  <table class="dfp-table" style="width:100%;">
    <thead><tr><th>Date/Time</th><th>Result</th></tr></thead>
    <tbody>
      <?php foreach ($rides as $r): ?>
        <tr><td><?php echo safeOut($r['scandatetime']); ?></td><td><?php echo safeOut($r['result']); ?></td></tr>
      <?php endforeach; ?>
      <?php if (!$rides): ?><tr><td colspan="2">No scans recorded yet.</td></tr><?php endif; ?>
    </tbody>
  </table>
</div>

<?php require 'footer.php'; ?>
<script>
function doAction(action) {
  if (action === 'delete' && !confirm('Are you sure you want to delete this record?')) { return; }
  $.post('ajax_admin_villager.php', { action: action, id: <?php echo (int)$id; ?> }, function (resp) {
    dfpToast(resp.message, resp.success ? 'success' : 'error');
    if (resp.success) {
      setTimeout(function () {
        window.location.href = action === 'delete' ? 'admin_villagers.php' : 'admin_villagerview.php?id=<?php echo (int)$id; ?>';
      }, 1000);
    }
  }, 'json');
}
</script>
<?php require 'footer2.php'; ?>
