<?php
// admin-print-application.php

require_once __DIR__ . '/vendor/autoload.php';
use Dompdf\Dompdf;
require_once __DIR__ . '/db.php';
session_start();

// 1) Pastikan hanya admin, exco, atau ajk boleh akses
if (!isset($_SESSION['user'])
    || !in_array($_SESSION['user']['role'], ['admin','exco','ajk'])
) {
    header('Location: dashboard.php');
    exit;
}

// 2) Dapatkan ID pengguna (pending_exco)
if (!isset($_GET['user_id'])) {
    die('User ID tidak disertakan.');
}
$userId = (int) $_GET['user_id'];

// 3) Fetch data anggota dari tabel pending_exco
$stmt = $conn->prepare("
    SELECT full_name,
           staff_number,
           ic_number,
           email,
		   job_title,
		   home_phone,
           phone,
           race,
           location,
           address,
           created_at,
           exco_auto,
           exco_select,
           postcode
      FROM pending_exco
     WHERE id = ?
");
$stmt->bind_param('i', $userId);
$stmt->execute();
$stmt->bind_result(
    $full_name,
    $staff_number,
    $ic_number,
    $email,
	$job_title,
	$home_phone,
    $phone,
    $race,
    $location,
    $address,
    $created_at,
    $excoId,
    $ajkId,
    $postcode
);
if (!$stmt->fetch()) {
    die('Rekod anggota tidak ditemui.');
}
$stmt->close();

// 4) Hitung Tarikh Lahir dari IC Number (YYMMDD)
$dob = '';
if (preg_match('/^(\d{2})(\d{2})(\d{2})/', $ic_number, $m)) {
    $yy = intval($m[1]);
    $mm = intval($m[2]);
    $dd = intval($m[3]);
    $currentYY = intval(date('y'));
    $year = ($yy > $currentYY) ? 1900 + $yy : 2000 + $yy;
    if (checkdate($mm, $dd, $year)) {
        $dob = sprintf('%02d/%02d/%04d', $dd, $mm, $year);
    }
}

// 5) Dapatkan nama Pencadang (EXCO)
$proposer = 'N/A';
if (!empty($excoId)) {
    $t = $conn->prepare("SELECT full_name FROM pending_exco WHERE id = ?");
    $t->bind_param('i', $excoId);
    $t->execute();
    $t->bind_result($tmpName);
    if ($t->fetch()) {
        $proposer = $tmpName;
    }
    $t->close();
}

// 6) Dapatkan nama Penyokong (AJK)
$supporter = 'N/A';
if (!empty($ajkId)) {
    $u = $conn->prepare("SELECT full_name FROM pending_exco WHERE id = ?");
    $u->bind_param('i', $ajkId);
    $u->execute();
    $u->bind_result($tmpName2);
    if ($u->fetch()) {
        $supporter = $tmpName2;
    }
    $u->close();
}

// 7) Format tarikh dan alamat
$date         = date('d/m/Y', strtotime($created_at));
$address_html = nl2br(htmlspecialchars($address));

// 8) Build HTML borang
$html = <<<HTML
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size:10px; margin:0; padding:0; }
    table { width:100%; border-collapse: collapse; }
    td, th { vertical-align: top; padding:4px; }
    .header-table td { border:none; }
    .fields-table td { border:1px solid #000; padding:4px; }
    .no-border td { border:none; }
    .sig-line { display:inline-block; width:150px; border-bottom:1px dotted #000; margin:0 20px; }
    .sig-label { display:inline-block; width:150px; text-align:center; margin-top:5px; }
  </style>
</head>
<body>

<table class="header-table" style="margin-bottom:5px;"><tr>
  <td style="width:60px; text-align:center;">
    <img src="/assets/img/kpprsaj-logo.png" width="50" height="50" alt="Logo KPPSAJ"/>
  </td>
  <td style="text-align:center;">
    <div style="font-weight:bold; font-size:12px;">KESATUAN PEKERJA-PEKERJA RANHILL SAJ SDN. BHD.</div>
    <div style="font-size:10px;">BANGUNAN RANHILL SAJ SDN. BHD., JALAN IBRAHIM, 84000 MUAR, JOHOR</div>
  </td>
  <td style="width:60px; text-align:right; font-size:10px;"><b>KPPSAJ 1</b></td>
</tr></table>

<div style="text-align:center; font-weight:bold; margin-bottom:5px; font-size:11px;">
  BORANG PERMOHONAN KEMASUKAN AHLI BARU
</div>

<table class="fields-table">
<tr>
  <td colspan="3"><b>NAMA PENUH (SEPERTI KP / PASPORT)</b><br><br>{$full_name}</td>
</tr>
<tr>
  <td style="width:40%;"><b>NO KAD PENGENALAN</b><br><br>{$ic_number}</td>
  <td style="width:30%;"><b>TARIKH LAHIR</b><br><br>{$dob}</td>
  <td style="width:30%;"><b>JAWATAN</b><br><br>$job_title<div class="sig-line"></div></td>
</tr>
<tr>
  <td><b>NO ANGGOTA</b><br><br>{$staff_number}</td>
  <td colspan="2"><b>ALAMAT KEDIAMAN</b><br><br>{$address_html}</td>
</tr>
<tr>
  <td><b>POSKOD</b><br><br>{$postcode}</td>
  <td><b>E-MAIL</b><br><br>{$email}</td>
  <td><b>NO TELEFON KEDIAMATAN</b><br><br>$home_phone<div class="sig-line"></div></td>
</tr>
<tr>
  <td colspan="2"><b>NO TELEFON BIMBIT</b><br><br>{$phone}</td>
  <td><b>KAUM</b><br><br>{$race}</td>
</tr>
</table>

<p>&nbsp;</p><p>&nbsp;</p>

<table class="no-border" style="width:100%; margin-top:20px;"><tr>
  <td style="text-align:center;">.....................<br>TARIKH</td>
  <td style="text-align:center;">.....................<br>TANDATANGAN PEMOHON</td>
  <td style="text-align:center;">.....................<br>TANDATANGAN PENCADANG</td>
</tr></table>

<table class="fields-table" style="margin-top:10px;">
<tr>
  <td><b>PENCADANG (EXCO)</b><br><br>{$excoId}</td>
  <td><b>PENYOKONG (AJK)</b><br><br>{$ajkId}</td>
</tr>
</table>

</body>
</html>
HTML;

// 9) Generate dan tampilkan PDF
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
// Stream PDF inline (Attachment=false)
$dompdf->stream("borang_pendaftaran_{$userId}.pdf", ['Attachment' => false]);
exit;
