<?php
require_once __DIR__ . '/db.php';

$emel = trim($_POST['emel'] ?? '');
$password = $_POST['password'] ?? '';
$rememberMe = isset($_POST['remember_me']) && $_POST['remember_me'] === '1';

$stmt = $conn->prepare("
    SELECT id, nama, ic, emel, role, jabatan, approval_status, account_status, password
    FROM users
    WHERE emel = ?
    LIMIT 1
");
$stmt->bind_param('s', $emel);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user || !password_verify($password, $user['password'])) {
    header('Location: login.php?error=invalid');
    exit();
}

if (($user['approval_status'] ?? 'pending') === 'pending') {
    header('Location: login.php?error=pending');
    exit();
}

if (($user['approval_status'] ?? '') === 'rejected') {
    header('Location: login.php?error=rejected');
    exit();
}

if (($user['account_status'] ?? 'inactive') !== 'active') {
    header('Location: login.php?error=inactive_account');
    exit();
}

$_SESSION['user_id'] = (int) $user['id'];
$_SESSION['user_nama'] = $user['nama'];
$_SESSION['user_ic'] = $user['ic'];
$_SESSION['user_emel'] = $user['emel'];
$_SESSION['user_role'] = $user['role'];
$_SESSION['user_jabatan'] = $user['jabatan'];
$_SESSION['last_activity'] = time();

add_user_log(
    $conn,
    (int) $user['id'],
    $user['nama'],
    $user['jabatan'],
    $user['role'],
    'Login ke dalam sistem'
);

if ($rememberMe) {
    setcookie('remembered_email', $user['emel'], time() + (86400 * 30), '/');
} else {
    setcookie('remembered_email', '', time() - 3600, '/');
}

header('Location: dashboard.php');
exit();
