<?php
require_once 'auth.php';
include 'db.php'; // Sambungan database di root folder

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // 1. Tangkap data dari borang
    $fullname   = trim((string) ($_POST['fullname'] ?? ''));
    $short_name = trim((string) ($_POST['short_name'] ?? ''));
    $ic_number  = trim((string) ($_POST['ic_number'] ?? ''));
    $email      = normalizeEmailAddress($_POST['email'] ?? '');
    $dept       = trim((string) ($_POST['department'] ?? ''));
    $position   = trim((string) ($_POST['position'] ?? ''));
    $password   = (string) ($_POST['password'] ?? '');
    $confirm_password = (string) ($_POST['confirm_pass'] ?? '');

    if (!isMainppEmailAddress($email)) {
        echo "<script>alert('Emel rasmi mestilah menggunakan domain @mainpp.gov.my.'); window.history.back();</script>";
        exit();
    }

    if ($password !== $confirm_password) {
        echo "<script>alert('Kata laluan dan pengesahan kata laluan tidak sepadan.'); window.history.back();</script>";
        exit();
    }

    if ($fullname === '' || $short_name === '') {
        echo "<script>alert('Sila isi nama penuh dan nama pendek.'); window.history.back();</script>";
        exit();
    }

    if (!preg_match('/^\d{12}$/', $ic_number)) {
        echo "<script>alert('No. Kad Pengenalan mesti mengandungi 12 digit nombor.'); window.history.back();</script>";
        exit();
    }

    if (!in_array($dept, getDepartmentList(), true) || !isValidDepartmentPosition($dept, $position)) {
        echo "<script>alert('Sila pilih bahagian dan jawatan yang sah.'); window.history.back();</script>";
        exit();
    }

    // 2. Semak jika IC sudah wujud
    $check_sql = "SELECT id FROM users WHERE ic_number = ?";
    $stmt = mysqli_prepare($conn, $check_sql);
    mysqli_stmt_bind_param($stmt, "s", $ic_number);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);

    if (mysqli_stmt_num_rows($stmt) > 0) {
        echo "<script>alert('❌ Gagal: No. IC ini sudah berdaftar!'); window.history.back();</script>";
        exit();
    }

    // 3. Semak jika Email sudah wujud
    $check_email = "SELECT id FROM users WHERE LOWER(email) = ?";
    $stmt_email = mysqli_prepare($conn, $check_email);
    mysqli_stmt_bind_param($stmt_email, "s", $email);
    mysqli_stmt_execute($stmt_email);
    mysqli_stmt_store_result($stmt_email);

    if (mysqli_stmt_num_rows($stmt_email) > 0) {
        echo "<script>alert('❌ Gagal: Emel ini sudah berdaftar!'); window.history.back();</script>";
        exit();
    }

    // 4. Hash password (Keamanan)
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // 5. Masukkan ke database DENGAN status 'pending'
    // ✅ TAMBAH 'status' dalam senarai kolum dan nilai
    $insert_sql = "INSERT INTO users (fullname, short_name, ic_number, email, department, position, password, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')";
    $stmt_insert = mysqli_prepare($conn, $insert_sql);
    
    mysqli_stmt_bind_param($stmt_insert, "sssssss", $fullname, $short_name, $ic_number, $email, $dept, $position, $hashed_password);

    if (mysqli_stmt_execute($stmt_insert)) {
        logActivityGuest($conn, 'create_user_pending', 'Permohonan daftar akaun baharu: ' . $fullname . ' (' . $email . ') - ' . $dept . ', ' . $position);
        // ✅ REDIRECT DENGAN PARAMETER pending_approval
        header('Location: login.php?success=pending_approval');
        /*
            alert('✅ Pendaftaran Berjaya Dihantar!\\n\\n⏳ Akaun anda sedang menunggu kelulusan Admin.\\nSila cuba log masuk semula setelah diluluskan.');
            window.location='login.php?success=pending_approval';
        */
        exit();
    } else {
        echo "<script>alert('❌ Ralat Sistem: " . mysqli_error($conn) . "'); window.history.back();</script>";
    }
}
?>
