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

/**
 * ack_confirm.php
 * ----------------
 * Terima POST dari acknowledgement.php dan:
 *  - Mode "pending": update pending_exco.ack_form=1, ack_date=NOW()
 *  - Mode "temp":    migrate rekod daripada temp_register → pending_exco dengan ack_form=1, padam temp
 *
 * Input (POST):
 *  - csrf:   token CSRF (wajib & mesti padan)
 *  - ack:    "1" (wajib ditanda)
 *  - source: "pending" | "temp"
 *  - id:     id rekod dalam jadual sumber
 */

// Helper ringkas untuk kembali ke borang ack
function back_to_ack(): void {
    header("Location: acknowledgement.php");
    exit;
}

// 0) Validasi asas POST & CSRF
if (empty($_POST['ack']) || $_POST['ack'] !== '1') {
    back_to_ack();
}
if (empty($_POST['csrf']) || empty($_SESSION['csrf_ack']) || !hash_equals($_SESSION['csrf_ack'], (string)$_POST['csrf'])) {
    back_to_ack();
}

// Setelah digunakan, matikan token CSRF lama (optional harden)
unset($_SESSION['csrf_ack']);

// 1) Dapatkan sumber & ID
$source = isset($_POST['source']) ? strtolower(trim((string)$_POST['source'])) : '';
$rec_id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

// Fallback: jika source "pending" tapi tiada id, cuba dari session
if ($source === 'pending' && $rec_id <= 0 && !empty($_SESSION['pending_id'])) {
    $rec_id = (int)$_SESSION['pending_id'];
}

// Mode tidak sah?
if (!in_array($source, ['pending','temp'], true) || $rec_id <= 0) {
    back_to_ack();
}

/* ============================================================
 * MODE: pending
 * - Hanya kemaskini ack_form & ack_date pada pending_exco
 * ============================================================ */
if ($source === 'pending') {
    // Pastikan rekod wujud
    $stmt = $conn->prepare("SELECT id FROM pending_exco WHERE id=? LIMIT 1");
    if (!$stmt) { back_to_ack(); }
    $stmt->bind_param("i", $rec_id);
    $stmt->execute();
    $stmt->store_result();
    $exists = ($stmt->num_rows > 0);
    $stmt->close();

    if (!$exists) {
        // Bersih session dan kembali
        unset($_SESSION['pending_id']);
        back_to_ack();
    }

    // Update ack
    $up = $conn->prepare("UPDATE pending_exco SET ack_form=1, ack_date=NOW() WHERE id=?");
    if (!$up) { back_to_ack(); }
    $up->bind_param("i", $rec_id);
    $up->execute();
    $up->close();

    // Pastikan session pending_id terkini
    $_SESSION['pending_id'] = $rec_id;

    $conn->close();
    header("Location: register-success.php");
    exit;
}

/* ============================================================
 * MODE: temp
 * - Migrasi rekod dari temp_register → pending_exco dengan ack_form=1
 * - Padam rekod dari temp_register selepas berjaya
 * ============================================================ */

// 2) Ambil rekod draf daripada temp_register
$sqlSel = "
    SELECT
      full_name, staff_number, ic_number, email, job_title, home_phone, phone, race,
      district_id, location,
      assigned_exco_id, assigned_ajk_id,
      exco_auto, exco_select, password_hash, address, postcode, receipt,
      waris_name, waris_phone
    FROM temp_register
    WHERE id = ?
    LIMIT 1
";
$st = $conn->prepare($sqlSel);
if (!$st) { back_to_ack(); }
$st->bind_param("i", $rec_id);
$st->execute();
$res = $st->get_result();
$draft = $res ? $res->fetch_assoc() : null;
$st->close();

if (!$draft) {
    // Tiada draf — kemungkinan sudah dipadam/invalid
    back_to_ack();
}

// Pastikan resit wujud (flow: resit wajib semasa draf)
if (empty($draft['receipt'])) {
    back_to_ack();
}

// 3) Migrasi → pending_exco
$conn->begin_transaction();

$sqlIns = "
    INSERT INTO pending_exco
      (full_name, staff_number, ic_number, email, job_title, home_phone, phone, race,
       district_id, location,
       assigned_exco_id, assigned_ajk_id,
       exco_auto, exco_select, password_hash, address, postcode, receipt,
       waris_name, waris_phone,
       ack_form, ack_date, role, status, created_at)
    VALUES
      (?, ?, ?, ?, ?, ?, ?, ?,
       ?, ?,
       ?, ?,
       ?, ?, ?, ?, ?, ?,
       ?, ?,
       1, NOW(), 'member', 0, NOW())
";
$ins = $conn->prepare($sqlIns);
if (!$ins) {
    $conn->rollback();
    back_to_ack();
}

$ins->bind_param(
    "ssssssssisiissssssss",
    $draft['full_name'],
    $draft['staff_number'],
    $draft['ic_number'],
    $draft['email'],
    $draft['job_title'],
    $draft['home_phone'],
    $draft['phone'],
    $draft['race'],
    $draft['district_id'],
    $draft['location'],
    $draft['assigned_exco_id'],
    $draft['assigned_ajk_id'],
    $draft['exco_auto'],
    $draft['exco_select'],
    $draft['password_hash'],
    $draft['address'],
    $draft['postcode'],
    $draft['receipt'],
    $draft['waris_name'],
    $draft['waris_phone']
);

if (!$ins->execute()) {
    $ins->close();
    $conn->rollback();
    back_to_ack();
}
$newPendingId = $conn->insert_id;
$ins->close();

// 4) Padam rekod dari temp_register
$del = $conn->prepare("DELETE FROM temp_register WHERE id=?");
if ($del) {
    $del->bind_param("i", $rec_id);
    $del->execute();
    $del->close();
}

// 5) Commit migrasi
$conn->commit();

// 6) Kemas sesi untuk navigasi seterusnya
$_SESSION['pending_id'] = (int)$newPendingId;
// Draf ini dah selamat dimigrasi — buang jejak e-mel/staf (optional)
unset($_SESSION['draft_email'], $_SESSION['draft_staff']);

$conn->close();

// Siap — ke halaman kejayaan
header("Location: register-success.php");
exit;
