<?php
// auth.php — Login handler KPPRSAJ DIS (staff_number + password)
// - Error: sentiasa generic ("Invalid username or password.")
// - Flash session untuk error (tiada ?error=... dalam URL)
declare(strict_types=1);

session_start();
require_once __DIR__ . '/db.php';

/**
 * Auto-detect base path (folder URL app ini).
 * Contoh:
 *  - Jika app di root:    $_SERVER['SCRIPT_NAME'] = /auth.php  → BASE_URL = '/'
 *  - Jika app dalam /dis: $_SERVER['SCRIPT_NAME'] = /dis/auth.php → BASE_URL = '/dis'
 */
(function () {
    $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
    if ($dir === '' || $dir === '.') { $dir = '/'; }
    define('BASE_URL', $dir === '/' ? '/' : $dir);
})();

function app_url(string $path = ''): string {
    $base = BASE_URL;
    $prefix = ($base === '/') ? '' : $base;
    return $prefix . '/' . ltrim($path, '/');
}
function flash_redirect(string $msg, ?string $lastStaff = null, string $target = 'index.php'): void {
    $_SESSION['flash_error'] = $msg;
    if ($lastStaff !== null) {
        $_SESSION['flash_last'] = $lastStaff;
    }
    header('Location: ' . app_url($target));
    exit;
}
function redirect_to(string $path): void {
    header('Location: ' . app_url($path));
    exit;
}

// Dummy bcrypt hash (untuk seragamkan masa verify bila user tak wujud)
const DUMMY_HASH = '$2y$10$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    flash_redirect('Invalid request.');
}

$staff_number = trim($_POST['staff_number'] ?? '');
$password     = $_POST['password'] ?? '';

if ($staff_number === '' || $password === '') {
    flash_redirect('Invalid username or password.', $staff_number);
}

// ===== 1) Cuba login melalui jadual members =====
// CHANGED: tambah must_change_password dalam SELECT
$sqlMembers = "SELECT id, password_hash, full_name, role, status, must_change_password
               FROM members
               WHERE staff_number = ?
               LIMIT 1";
$user = null;
if ($stmt = $conn->prepare($sqlMembers)) {
    $stmt->bind_param("s", $staff_number);
    if ($stmt->execute()) {
        $stmt->store_result();
        if ($stmt->num_rows === 1) {
            $stmt->bind_result($mid, $mhash, $mname, $mrole, $mstatus, $mmust);
            $stmt->fetch();
            $user = [
                'id'                   => (int)$mid,
                'password_hash'        => $mhash,
                'full_name'            => $mname,
                'role'                 => $mrole,
                'status'               => (int)$mstatus,
                'must_change_password' => (int)$mmust,
            ];
        }
    } else {
        error_log('auth.php execute(members) failed: ' . $stmt->error);
    }
    $stmt->close();
} else {
    error_log('auth.php prepare(members) failed: ' . $conn->error);
}

// Verify password tanpa dedahkan mana salah
$hashToVerify = $user['password_hash'] ?? DUMMY_HASH;
$passOk = password_verify($password, $hashToVerify);

if ($user && $passOk) {
    // Pastikan akaun aktif (anggap 1 = aktif). Mesej tetap generic jika tak aktif.
    if (isset($user['status']) && $user['status'] !== 1) {
        flash_redirect('Invalid username or password.', $staff_number);
    }

    session_regenerate_id(true);
    $_SESSION['user'] = [
        'id'           => $user['id'],
        'staff_number' => $staff_number,
        'name'         => $user['full_name'],
        'role'         => $user['role'],
    ];

    // >>> Paksa tukar password jika flag = 1
    if (!empty($user['must_change_password'])) {
        $_SESSION['force_change'] = 1; // digunakan oleh change-password.php
        redirect_to('change-password.php');
    }

    // kalau tak perlu tukar, terus ke dashboard
    redirect_to('dashboard.php');
}

// ===== 2) Fallback: cuba jadual users (jika wujud) =====
$user2 = null;
$sqlUsers = "SELECT id, password_hash, role
             FROM users
             WHERE staff_number = ? AND status = 1
             LIMIT 1";
if ($stmt2 = $conn->prepare($sqlUsers)) {
    $stmt2->bind_param("s", $staff_number);
    if ($stmt2->execute()) {
        $stmt2->store_result();
        if ($stmt2->num_rows === 1) {
            $stmt2->bind_result($uid, $uhash, $urole);
            $stmt2->fetch();
            $user2 = [
                'id'            => (int)$uid,
                'password_hash' => $uhash,
                'role'          => $urole,
            ];
        }
    } else {
        error_log('auth.php execute(users) failed: ' . $stmt2->error);
    }
    $stmt2->close();
}

$hashToVerify2 = $user2['password_hash'] ?? DUMMY_HASH;
$passOk2 = password_verify($password, $hashToVerify2);

if ($user2 && $passOk2) {
    session_regenerate_id(true);
    $_SESSION['user'] = [
        'id'           => $user2['id'],
        'staff_number' => $staff_number,
        'name'         => 'System Administrator',
        'role'         => $user2['role']
    ];
    // (tiada must_change_password untuk jadual users; terus masuk)
    redirect_to('dashboard.php');
}

// ===== 3) Gagal login — mesej generic =====
flash_redirect('Invalid username or password.', $staff_number);
