<?php
// Prevent direct access outside of app context
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function redirect(string $path): void {
	// Ensure absolute path relative to project root
	header('Location: ' . $path);
	exit;
}

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

function json_response(bool $success, string $message, string $redirect = ''): void {
	header('Content-Type: application/json; charset=utf-8');
	echo json_encode([
		'success' => $success,
		'message' => $message,
		'redirect' => $redirect
	], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
	exit;
}

function is_ajax_request(): bool {
	return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
	       strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}

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

$messages = load_messages();
$isAjax = is_ajax_request();

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

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

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

try {
	$conn = db_connect();
} catch (Throwable $exception) {
	error_log('SQL Server connection failed: ' . $exception->getMessage());
	if ($isAjax) {
		json_response(false, $messages['database_connection_failed']);
	}
	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));
	if ($isAjax) {
		json_response(false, $messages['database_query_failed']);
	}
	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) {
	if ($isAjax) {
		json_response(false, $messages['invalid_credentials']);
	}
	set_flash('error', $messages['invalid_credentials']);
	redirect('../../index.php');
}

$dbPassword = (string)$row['Password'];
if (!hash_equals($dbPassword, $password)) {
	if ($isAjax) {
		json_response(false, $messages['invalid_credentials']);
	}
	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'] ?? '',
];

if ($isAjax) {
	json_response(true, $messages['login_success'], 'index.php');
}

set_flash('success', $messages['login_success']);
// Redirect to app shell (index), which will render dashboard by default
redirect('../../index.php');

