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

$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 AND v.status = 'approved' AND v.paymentstatus = 'paid'");
$stmt->execute([$id]);
$v = $stmt->fetch();

if (!$v) {
    die('Registration not found or not yet completed.');
}

$vehiclestmt = $pdo->prepare("SELECT vehiclenumber FROM villagervehicle WHERE villagerid = ? AND isdeleted = 0");
$vehiclestmt->execute([$id]);
$vehicles = $vehiclestmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Printable Pass - <?php echo safeOut($v['fullname']); ?></title>
<link rel="stylesheet" href="style.css">
<style>
  body { padding: 20px; }
  .passcard {
    max-width: 380px; border: 2px solid #111; border-radius: 8px; padding: 16px; margin: 0 auto;
  }
  .passcard h2 { margin: 0 0 4px 0; font-size: 16px; text-align: center; }
  .passcard .photo { width: 90px; height: 90px; object-fit: cover; border: 1px solid #ccc; border-radius: 4px; float: left; margin-right: 12px; }
  .passcard p { margin: 4px 0; font-size: 13px; }
  @media print {
    .noprint { display: none; }
  }
</style>
</head>
<body>

<div class="noprint" style="text-align:center;margin-bottom:14px;">
  <button class="btn" onclick="window.print()">Print</button>
</div>

<div class="passcard">
  <h2>Divar Ferry Pass</h2>
  <?php if ($v['photo']): ?>
    <img class="photo" src="uploads/photos/<?php echo safeOut($v['photo']); ?>">
  <?php endif; ?>
  <p><b><?php echo safeOut($v['fullname']); ?></b></p>
  <p><?php echo safeOut($v['panchayatname']); ?>, Divar</p>
  <p>Valid: <?php echo safeOut($v['passstartdate']); ?> to <?php echo safeOut($v['passenddate']); ?></p>
  <?php if ($vehicles): ?>
    <p>Vehicle: <?php echo implode(', ', array_map(fn($x) => safeOut($x['vehiclenumber']), $vehicles)); ?></p>
  <?php endif; ?>
  <div style="clear:both;"></div>
  <svg id="barcode" style="width:100%;margin-top:8px;"></svg>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jsbarcode/3.11.6/JsBarcode.all.min.js"></script>
<script>
JsBarcode("#barcode", "<?php echo safeOut($v['barcodetext']); ?>", { format: "CODE128", displayValue: true, height: 50 });
</script>
</body>
</html>
