<?php
// slip-permohonan.php (bebas login)
require_once 'db.php';

// ===== Guard: ID wajib =====
if (!isset($_GET['id'])) {
    http_response_code(400);
    die('ID tidak sah.');
}
$id = (int)$_GET['id'];

// ===== Helper =====
function fetch_application(mysqli $conn, string $table, int $id): ?array {
    $sql = "
        SELECT
          id, full_name, staff_number, ic_number, email, job_title, home_phone, phone, race, location,
          address, postcode, created_at, waris_name, waris_phone
        FROM `$table`
        WHERE id = ?
        LIMIT 1
    ";
    if (!$stmt = $conn->prepare($sql)) return null;
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt->close();
    return $row ?: null;
}
function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

// 1) Cuba pending_exco dahulu
$source = 'pending_exco';
$row = fetch_application($conn, $source, $id);

// 2) Jika tiada, fallback ke pending_ajk
if (!$row) {
    $source = 'pending_ajk';
    $row = fetch_application($conn, $source, $id);
}

// 3) Jika masih tiada, fallback ke temp_register (draf)
if (!$row) {
    $source = 'temp_register';
    $row = fetch_application($conn, $source, $id);
}

// 4) Jika masih tiada, tamatkan
if (!$row) {
    http_response_code(404);
    die('Rekod tidak ditemui.');
}

// Alihkan ke pembolehubah
$full_name   = $row['full_name']      ?? '';
$staff_no    = $row['staff_number']   ?? '';
$ic_no       = $row['ic_number']      ?? '';
$email       = $row['email']          ?? '';
$job_title   = $row['job_title']      ?? '';
$home_phone  = $row['home_phone']     ?? '';
$phone       = $row['phone']          ?? '';
$race        = $row['race']           ?? '';
$location    = $row['location']       ?? '';
$address     = $row['address']        ?? '';
$postcode    = $row['postcode']       ?? '';
$created_at  = $row['created_at']     ?? '';
$waris_name  = $row['waris_name']     ?? '';
$waris_phone = $row['waris_phone']    ?? '';

$created_at_fmt = $created_at ? date("d-m-Y H:i", strtotime($created_at)) : '-';

// Label peringkat (EXCO/AJK/Draf) + warna badge
if ($source === 'pending_ajk') {
    $stage_label = 'AJK';
    $stage_class = 'badge-ajk';
} elseif ($source === 'pending_exco') {
    $stage_label = 'EXCO';
    $stage_class = 'badge-exco';
} else {
    $stage_label = 'Draf';
    $stage_class = 'badge-draf';
}

// Tentukan URL tindakan “Teruskan ke Pengesahan”
// - Jika sumber DRAF (temp_register): hantar ke acknowledge.php dengan flag temp=1
// - Jika sumber PENDING (exco/ajk): hantar ke acknowledge.php biasa
$ack_url = ($source === 'temp_register')
    ? "acknowledge.php?temp=1&id=" . urlencode($id)
    : "acknowledge.php?id=" . urlencode($id);
?>
<!DOCTYPE html>
<html lang="ms">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Slip Permohonan — KPPRSAJ</title>
<style>
  :root{
    --bg1:#0f172a; /* slate-900 */
    --bg2:#1e293b; /* slate-800 */
    --card:#ffffff;
    --muted:#64748b; /* slate-500 */
    --text:#0f172a;
    --brand:#0ea5e9; /* sky-500 */
    --ok:#22c55e;    /* green-500 */
    --pri:#2563eb;   /* blue-600 */
    --pri-dark:#1e40af;
    --ok-dark:#166534;
    --border:#e5e7eb;
    --table-head:#f8fafc;
    --warning:#f59e0b;
  }
  *{ box-sizing:border-box; }
  html,body{ height:100%; margin:0; }
  body{
    font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, "Helvetica Neue", Arial, "Noto Sans", "Liberation Sans", sans-serif;
    color:var(--text);
    background:
      radial-gradient(1200px 600px at 10% -10%, rgba(14,165,233,.18), transparent 60%),
      radial-gradient(900px 500px at 110% 0%, rgba(34,197,94,.12), transparent 60%),
      linear-gradient(180deg, var(--bg1), var(--bg2));
    background-attachment: fixed;
    display:flex; align-items: flex-start; justify-content:center; padding:40px 16px;
  }
  .wrap{
    width: min(1100px, 100%);
    position:relative;
  }
  .brand{
    display:flex; align-items:center; gap:12px; color:#e2e8f0; margin-bottom:16px;
  }
  .brand-dot{ width:12px; height:12px; border-radius:50%; background:var(--brand); box-shadow:0 0 0 6px rgba(14,165,233,.15); }
  .card{
    background:var(--card);
    border-radius:16px;
    box-shadow: 0 10px 30px rgba(2,6,23,.35);
    overflow:hidden;
    border:1px solid rgba(255,255,255,.08);
  }
  .card-head{
    padding:24px;
    border-bottom:1px solid var(--border);
    display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap;
  }
  .title{
    margin:0; line-height:1.25;
    font-size: clamp(20px, 2.2vw, 28px);
  }
  .subtitle{
    margin:4px 0 0; color:var(--muted); font-size:14px;
  }
  .badge{
    display:inline-flex; gap:8px; align-items:center; font-weight:700; letter-spacing:.3px;
    padding:6px 12px; border-radius:999px; font-size:12px; border:1px solid transparent;
  }
  .badge-exco{ background:#eef2ff; color:#4338ca; border-color:#c7d2fe; }
  .badge-ajk{  background:#ecfeff; color:#0e7490; border-color:#a5f3fc; }
  .badge-draf{ background:#fff7ed; color:#b45309; border-color:#fed7aa; }

  .card-body{ padding:24px; }
  .grid{
    display:grid; gap:16px;
    grid-template-columns: 1fr;
  }
  @media (min-width: 980px){
    .grid{ grid-template-columns: 1.1fr .9fr; }
  }

  .pane{
    background:#fff; border:1px solid var(--border); border-radius:12px; overflow:hidden;
  }
  .pane-head{
    padding:14px 16px; background:var(--table-head); border-bottom:1px solid var(--border);
    font-weight:700; font-size:14px;
  }
  .pane-body{ padding:8px 16px 16px; }

  .table-wrap{ width:100%; overflow:auto; }
  table{ width:100%; border-collapse:separate; border-spacing:0; }
  th, td{ padding:12px 14px; text-align:left; vertical-align: top; font-size:14px; }
  th{
    width: 260px; white-space: nowrap;
    background:#fafafa; color:#111827; font-weight:700; border-top:1px solid var(--border); border-bottom:1px solid var(--border);
    position:relative;
  }
  td{
    background:#fff; border-top:1px solid var(--border); border-bottom:1px solid var(--border);
  }
  tr:first-child th, tr:first-child td{ border-top:0; }
  tr:last-child th, tr:last-child td{ border-bottom:0; }

  .actions{
    display:flex; flex-wrap:wrap; gap:10px; margin-top:16px;
  }
  .btn{
    display:inline-flex; align-items:center; gap:8px;
    padding:10px 14px; border-radius:10px; font-weight:700; text-decoration:none; border:1px solid transparent;
    color:#fff; background:var(--pri);
    transition: transform .05s ease, background .2s ease;
    will-change: transform;
  }
  .btn:hover{ background:var(--pri-dark); transform: translateY(-1px); }
  .btn.ok{ background:var(--ok); } .btn.ok:hover{ background:var(--ok-dark); }
  .btn.ghost{ background:#0b1220; border-color:#0b1220; } .btn.ghost:hover{ background:#060b16; }
  .btn-icon{ font-size:18px; line-height:1; }

  .note-box{
    background:#f8fafc; border:1px solid var(--border); color:#0f172a;
    padding:14px 16px; border-radius:12px; font-size:14px; margin-top:16px;
  }
  .muted{ color:var(--muted); font-size:13px; }

  .pdf-embed{
    width:100%; height:600px; border:0; display:block;
    background:linear-gradient(180deg,#f8fafc,#ffffff);
  }
  .embed-fallback{
    padding:12px; font-size:14px; background:#fff7ed; border:1px dashed #fdba74; color:#7c2d12; border-radius:10px; margin-top:8px;
  }

  /* Print */
  @media print{
    body{ background:#fff; padding:0; }
    .brand, .actions{ display:none !important; }
    .card{ box-shadow:none; border:0; border-radius:0; }
    .pane, .pane-head{ border-color:#ddd !important; }
    .pdf-embed{ height:900px; }
  }
</style>
</head>
<body>
  <div class="wrap">
    <div class="brand">
      <span class="brand-dot"></span>
      <div>
        <div style="font-weight:800; letter-spacing:.3px;">KPPRSAJ — Database Information System</div>
        <div class="muted">Slip Permohonan (bebas log masuk)</div>
      </div>
    </div>

    <div class="card">
      <div class="card-head">
        <div>
          <h1 class="title">Slip Permohonan KPPRSAJ</h1>
          <p class="subtitle">Tarikh Permohonan: <strong><?= esc($created_at_fmt) ?></strong></p>
        </div>
        <span class="badge <?= esc($stage_class) ?>">Peringkat Semasa: <?= esc($stage_label) ?></span>
      </div>

      <div class="card-body">
        <div class="grid">
          <!-- Maklumat Pemohon -->
          <div class="pane">
            <div class="pane-head">Maklumat Pemohon</div>
            <div class="pane-body">
              <div class="table-wrap">
                <table role="table" aria-label="Maklumat Pemohon">
                  <tr><th>Nama Penuh</th><td><?= esc($full_name) ?></td></tr>
                  <tr><th>No. Staf</th><td><?= esc($staff_no) ?></td></tr>
                  <tr><th>No. KP</th><td><?= esc($ic_no) ?></td></tr>
                  <tr><th>Email</th><td><?= esc($email) ?></td></tr>
                  <tr><th>Jawatan</th><td><?= esc($job_title ?: '-') ?></td></tr>
                  <tr><th>No. Tel Kediaman</th><td><?= esc($home_phone ?: '-') ?></td></tr>
                  <tr><th>No. Tel Bimbit</th><td><?= esc($phone) ?></td></tr>
                  <tr><th>Kaum</th><td><?= esc($race ?: '-') ?></td></tr>
                  <tr><th>Daerah/Lokasi Bertugas</th><td><?= esc($location) ?></td></tr>
                  <tr><th>Alamat Kediaman</th><td><?= esc($address ?: '-') ?></td></tr>
                  <tr><th>Poskod</th><td><?= esc($postcode ?: '-') ?></td></tr>
                  <tr><th>Nama Waris</th><td><?= esc($waris_name ?: '-') ?></td></tr>
                  <tr><th>No. Telefon Waris</th><td><?= esc($waris_phone ?: '-') ?></td></tr>
                </table>
              </div>

              <div class="actions">
                <a class="btn" href="slip-permohonan-pdf.php?id=<?= urlencode($id) ?>&download=1" target="_blank" rel="noopener">
                  <span class="btn-icon">⬇️</span> Muat Turun PDF
                </a>

                <?php if ($source === 'pending_ajk'): ?>
                  <!-- Sudah di peringkat AJK: tidak perlu ke acknowledge -->
                  <a class="btn ok" href="index.php">
                    <span class="btn-icon">🔑</span> Pergi ke Log Masuk
                  </a>
                <?php else: ?>
                  <!-- temp_register atau pending_exco -->
                  <a class="btn ok" href="<?= esc($ack_url) ?>">
                    <span class="btn-icon">➡️</span> Teruskan ke Pengesahan
                  </a>
                <?php endif; ?>

                <button class="btn ghost" type="button" onclick="window.print()">
                  <span class="btn-icon">🖨️</span> Cetak
                </button>
              </div>

              <div class="note-box">
                <strong>Nota:</strong>
                <?php if ($source === 'temp_register'): ?>
                  Ini adalah <strong>salinan draf</strong>. Sila tekan “Teruskan ke Pengesahan” untuk menandakan persetujuan potongan gaji bulanan. Selepas pengesahan, permohonan anda akan dihantar ke <strong>peringkat EXCO</strong>.
                <?php elseif ($source === 'pending_exco'): ?>
                  Permohonan anda sedang menunggu <strong>kelulusan EXCO</strong>. Tarikh pemotongan gaji hanya akan bermula selepas <strong>kelulusan AJK</strong> dimuktamadkan.
                <?php else: ?>
                  Permohonan anda berada di <strong>peringkat AJK</strong>. Sila tunggu keputusan muktamad.
                <?php endif; ?>
                <div class="muted" style="margin-top:6px;">Sila simpan salinan PDF ini untuk rujukan anda.</div>
              </div>
            </div>
          </div>

          <!-- Pratonton PDF -->
          <div class="pane">
            <div class="pane-head">Pratonton Slip (PDF)</div>
            <div class="pane-body">
              <iframe
                class="pdf-embed"
                src="slip-permohonan-pdf.php?id=<?= urlencode($id) ?>"
                title="Slip Permohonan PDF"
              ></iframe>
              <div class="embed-fallback" aria-live="polite">
                Jika PDF tidak dipaparkan, klik <a href="slip-permohonan-pdf.php?id=<?= urlencode($id) ?>" target="_blank" rel="noopener">di sini</a> untuk buka dalam tab baharu.
              </div>
              <p class="muted" style="margin-top:10px;">
                ID Permohonan: <strong>#<?= esc($id) ?></strong>
                <br> Sumber: <em><?= esc($source) ?></em>
              </p>
            </div>
          </div>
          <!-- /Pratonton PDF -->
        </div>
      </div>
    </div>
  </div>
</body>
</html>
