<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect('../pages/login.php');
}

ensure_post_csrf_or_redirect('login', '../pages/login.php');

$username = trim((string) ($_POST['username'] ?? ''));
$password = (string) ($_POST['password'] ?? '');
$displayMode = remember_display_mode((string) ($_POST['display_mode'] ?? current_display_mode()));
$loginIpAddress = client_ip_address();

if ($username === '' || $password === '') {
    redirect_with_flash(
        '../pages/login.php',
        'error',
        localized_flash_message('กรุณากรอกชื่อผู้ใช้และรหัสผ่าน', 'Username and password are required.')
    );
}

$throttleStatus = login_throttle_status($username, $loginIpAddress);
if (!empty($throttleStatus['is_locked'])) {
    redirect_with_flash('../pages/login.php', 'error', login_throttle_message($throttleStatus));
}

$stmt = db_prepare($conn, "
    SELECT employee_id, password_hash, is_active
    FROM employees
    WHERE username = ?
    LIMIT 1
");
$stmt->bind_param('s', $username);
$stmt->execute();
$employee = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$employee || (int) ($employee['is_active'] ?? 0) !== 1 || !password_verify($password, (string) ($employee['password_hash'] ?? ''))) {
    $throttleStatus = login_throttle_register_failure($username, $loginIpAddress);
    $failureMessage = !empty($throttleStatus['is_locked'])
        ? login_throttle_message($throttleStatus)
        : localized_flash_message(
            'เข้าสู่ระบบไม่สำเร็จ กรุณาตรวจสอบชื่อผู้ใช้และรหัสผ่าน',
            'Login failed. Please check your username and password.'
        );
    redirect_with_flash('../pages/login.php', 'error', $failureMessage);
}

login_throttle_clear($username, $loginIpAddress);
session_regenerate_id(true);
$_SESSION['employee_id'] = (int) $employee['employee_id'];
$_SESSION['display_mode'] = $displayMode;

$updateStmt = db_prepare($conn, "
    UPDATE employees
    SET last_login_at = NOW()
    WHERE employee_id = ?
");
$employeeId = (int) $employee['employee_id'];
$updateStmt->bind_param('i', $employeeId);
$updateStmt->execute();
$updateStmt->close();

$intendedUrl = (string) ($_SESSION['intended_url'] ?? '');
unset($_SESSION['intended_url']);

if ($intendedUrl !== '' && strpos($intendedUrl, 'login.php') === false) {
    redirect($intendedUrl);
}

redirect('../pages/' . auth_preferred_landing_page($conn));
