<?php
session_start();
require_once "db.php";

/**
 * acknowledgement.php — serasi flow baru
 * --------------------------------------
 * Papar borang persetujuan potongan gaji bulanan.
 * Menyokong dua sumber:
 *   1) pending_exco (mode "pending"): bila rekod sudah wujud di pending_exco
 *   2) temp_register (mode "temp"): selepas simpan draf (flow baru), sebelum migrate
 *
 * Hantar ke ack_confirm.php bersama:
 *   - csrf
 *   - source: "pending" | "temp"
 *   - id: id rekod dalam jadual sumber
 */

/* 0) CSRF token */
if (empty($_SESSION['csrf_ack'])) {
    $_SESSION['csrf_ack'] = bin2hex(random_bytes(16));
}
$csrf = $_SESSION['csrf_ack'];

/* 1) Cuba tentukan "mode" & dapatkan rekod */
$mode       = null;      // "pending" | "temp"
$rec_id     = null;      // id bagi jadual sumber
$full_name  = null;      // untuk paparan
$alreadyAck = false;

/* 1A-0) Terima ?id= jika diberi */
if (empty($_SESSION['pending_id']) && isset($_GET['id'])) {
    $_SESSION['pending_id'] = (int)$_GET['id'];
}

/* 1A) Cuba pending_exco dahulu (mengikut versi asal),
        tetapi jika sudah ack dan ada draf semasa → utamakan draf (fix). */
if (!empty($_SESSION['pending_id'])) {
    $pid  = (int)$_SESSION['pending_id'];
    $stmt = $conn->prepare("SELECT id, full_name, ack_form FROM pending_exco WHERE id=? LIMIT 1");
    if ($stmt) {
        $stmt->bind_param("i", $pid);
        $stmt->execute();
        $stmt->bind_result($db_id, $db_name, $ack_form);
        if ($stmt->fetch()) {
            $mode       = "pending";
            $rec_id     = (int)$db_id;
            $full_name  = (string)$db_name;
            $alreadyAck = ((int)$ack_form === 1);
        }
        $stmt->close();
    }

    if ($mode === "pending") {
        if ($alreadyAck) {
            // === FIX: Jika sudah ack DAN wujud draf semasa, abaikan pending lama & terus ke draf ===
            $hasDraft = !empty($_SESSION['draft_email']) || !empty($_SESSION['draft_staff']);
            if ($hasDraft) {
                unset($_SESSION['pending_id']);
                $mode = null; // paksa ke logik 1B (temp_register)
            } else {
                // tiada draf, memang selesai → ke success
                header('Location: register-success.php');
                exit;
            }
        }
        // Jika belum ack, teruskan paparan borang ACK untuk mode "pending"
    }
}

/* 1B) Jika belum jumpa di pending_exco (atau kita paksa ke draf), cuba cari draf di temp_register */
if ($mode === null) {
    $email = $_SESSION['draft_email'] ?? '';
    $staff = $_SESSION['draft_staff'] ?? '';

    if ($email !== '' || $staff !== '') {
        $stmt = $conn->prepare("
            SELECT id, full_name
              FROM temp_register
             WHERE (email=? AND ?<>'') OR (staff_number=? AND ?<>'')
             ORDER BY id DESC
             LIMIT 1
        ");
        if ($stmt) {
            $stmt->bind_param("ssss", $email, $email, $staff, $staff);
            $stmt->execute();
            $stmt->bind_result($tid, $tname);
            if ($stmt->fetch()) {
                $mode      = "temp";
                $rec_id    = (int)$tid;
                $full_name = (string)$tname;
            }
            $stmt->close();
        }
    }
}

/* 1C) Jika masih tak jumpa apa-apa, hantar balik ke register (bersih sesi) */
if ($mode === null || !$rec_id) {
    unset($_SESSION['pending_id'], $_SESSION['draft_email'], $_SESSION['draft_staff']);
    header('Location: register.php');
    exit;
}

/* 2) Elak cache halaman borang */
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

?>
<!DOCTYPE html>
<html lang="ms">
<head>
  <meta charset="UTF-8">
  <title>Persetujuan Potongan Gaji Bulanan</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    :root{
      --bg1:#0f172a; --bg2:#1e293b;
      --card:#fff; --border:#e5e7eb;
      --text:#0f172a; --muted:#64748b;
      --brand:#0ea5e9; --ok:#22c55e; --ok-dark:#166534;
      --warn:#f59e0b; --warn-bg:#fef3c7; --warn-border:#fcd34d; --warn-text:#78350f;
    }
    *{box-sizing:border-box;}
    body,html{margin:0; height:100%;}
    body{
      font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, "Helvetica Neue", Arial;
      background:
        radial-gradient(1000px 600px at 5% -10%, rgba(14,165,233,.18), transparent 60%),
        radial-gradient(800px 400px at 120% 0%, rgba(34,197,94,.12), transparent 60%),
        linear-gradient(180deg, var(--bg1), var(--bg2));
      background-attachment: fixed;
      display:flex; align-items:center; justify-content:center;
      padding:40px 16px;
      color:var(--text);
    }
    .card{
      background:var(--card); border-radius:16px;
      box-shadow:0 10px 30px rgba(2,6,23,.35);
      border:1px solid rgba(255,255,255,.08);
      max-width:620px; width:100%;
      padding:32px 28px;
    }
    h2{
      margin-top:0; font-size: clamp(22px,2vw,28px);
      display:flex; align-items:center; gap:10px;
    }
    h2 span{ font-size:24px; }
    p{ font-size:15px; margin-top:6px; }
    .note{
      background:var(--warn-bg); border:1px solid var(--warn-border);
      color:var(--warn-text);
      padding:14px 16px; border-radius:12px; font-size:14px; margin:18px 0;
    }
    .who{
      background:#f8fafc; border:1px solid var(--border);
      padding:10px 12px; border-radius:10px; font-size:14px; color:#0f172a; margin-top:10px;
    }
    form{ margin-top:18px; }
    label.checkbox{
      display:flex; align-items:flex-start; gap:10px; font-size:15px; line-height:1.4;
      cursor:pointer; user-select:none;
    }
    input[type="checkbox"]{
      width:18px; height:18px; margin-top:2px;
    }
    .actions{ margin-top:20px; display:flex; gap:10px; align-items:center; }
    button{
      background:var(--ok); color:#fff; border:0;
      padding:12px 20px; border-radius:10px;
      font-size:15px; font-weight:700; cursor:pointer;
      transition:background .2s ease;
    }
    button:hover{ background:var(--ok-dark); }
    .muted{ font-size:13px; color:var(--muted); margin-top:16px; }
    .link a{ color:#0ea5e9; text-decoration:none; }
    .link a:hover{ text-decoration:underline; }

    @media print{
      body{ background:#fff; }
      .actions button, .link{ display:none; }
    }
  </style>
</head>
<body>
  <div class="card">
    <h2><span>📝</span> Persetujuan Potongan Gaji Bulanan</h2>
    <p>Sila baca dan fahami terma berikut sebelum menandakan kotak persetujuan:</p>

    <div class="note">
      Dengan menanda kotak di bawah, saya <strong>mengesahkan dan bersetuju</strong> bahawa kenyataan ini boleh dijadikan bukti pengesahan bertulis daripada saya,
      bahawa <strong>yuran keahlian KPPRSAJ boleh dipotong daripada gaji saya secara bulanan</strong>.
    </div>

    <div class="who">
      <strong>Nama Pemohon:</strong>
      <?php echo htmlspecialchars($full_name ?? '-', ENT_QUOTES, 'UTF-8'); ?><br>
      <strong>Mode:</strong> <?php echo htmlspecialchars(strtoupper($mode), ENT_QUOTES, 'UTF-8'); ?><br>
      <strong>ID Rekod:</strong> #<?php echo (int)$rec_id; ?>
    </div>

    <form method="post" action="ack_confirm.php" novalidate>
      <input type="hidden" name="csrf" value="<?php echo htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8'); ?>">
      <input type="hidden" name="source" value="<?php echo htmlspecialchars($mode, ENT_QUOTES, 'UTF-8'); ?>">
      <input type="hidden" name="id" value="<?php echo (int)$rec_id; ?>">

      <label class="checkbox" for="ack">
        <input id="ack" type="checkbox" name="ack" value="1" required>
        <span>Saya telah membaca, memahami dan bersetuju dengan terma di atas.</span>
      </label>

      <div class="actions">
        <button type="submit">✔️ Hantar Persetujuan</button>
        <?php if ($mode === 'pending'): ?>
          <span class="link">
            <a href="slip-permohonan.php?id=<?php echo (int)$rec_id; ?>">Lihat Slip Permohonan</a>
          </span>
        <?php endif; ?>
      </div>
    </form>

    <div class="muted">
      Tarikh pemotongan gaji akan bermula selepas <strong>kelulusan EXCO</strong> dimuktamadkan.
    </div>
  </div>
</body>
</html>
