<?php
if (session_status() === PHP_SESSION_NONE) {
	session_start();
}

function redirect(string $path): void {
	header('Location: ' . $path);
	exit;
}

function set_flash(string $key, string $message): void {
	$_SESSION['flash'][$key] = $message;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
	redirect('index.php');
}
require_once __DIR__ . '/config/messages.php';
require_once __DIR__ . '/config/database.php';

$messages = load_messages();


$csrf = $_POST['csrf_token'] ?? '';
if (!hash_equals($_SESSION['csrf_token'] ?? '', $csrf)) {
	set_flash('error', $messages['session_invalid']);
	redirect('index.php');
}

$username = trim((string)($_POST['employee_code'] ?? ''));
$password = (string)($_POST['password'] ?? '');

if ($username === '' || $password === '') {
	set_flash('error', $messages['credentials_required']);
	redirect('index.php');
}

try {
	$conn = db_connect();
} catch (Throwable $exception) {
	error_log('SQL Server connection failed: ' . $exception->getMessage());
	set_flash('error', $messages['database_connection_failed']);
	redirect('index.php');
}

$sql = 'SELECT TOP 1 d.Password, d.Hoten, d.Name, d.Permisson, p.Name_VN, p.Name_ENG 
        FROM DataWork d 
        LEFT JOIN Permisson p ON d.Permisson = p.ID 
        WHERE d.Maso_NV = ?';
$params = [$username];
$stmt = sqlsrv_query($conn, $sql, $params);

if ($stmt === false) {
	error_log('SQL query failed: ' . print_r(sqlsrv_errors(), true));
	set_flash('error', $messages['database_query_failed']);
	db_disconnect($conn);
	redirect('index.php');
}

$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
sqlsrv_free_stmt($stmt);
db_disconnect($conn);

if ($row === null) {
	set_flash('error', $messages['invalid_credentials']);
	redirect('index.php');
}

$dbPassword = (string)$row['Password'];
if (!hash_equals($dbPassword, $password)) {
	set_flash('error', $messages['invalid_credentials']);
	redirect('index.php');
}

$_SESSION['user'] = [
	'username' => $username,
	'login_time' => time(),
	'hoten' => $row['Hoten'] ?? '',
	'name' => $row['Name'] ?? '',
	'permisson' => $row['Permisson'] ?? '',
	'permisson_name_vn' => $row['Name_VN'] ?? '',
	'permisson_name_eng' => $row['Name_ENG'] ?? '',
];
set_flash('success', $messages['login_success']);
redirect('dashboard.php');




