<?php
// Company data service: all DB access lives here (moved under modules)
if (session_status() === PHP_SESSION_NONE) {
	session_start();
}

if (!defined('LUNA_APP')) {
	define('LUNA_APP', true);
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/messages.php';
$messages = load_messages();

function company_set_last_error(string $message): void
{
    if (!isset($_SESSION['company_last_error']) || !is_array($_SESSION['company_last_error'])) {
        $_SESSION['company_last_error'] = [];
    }
    $_SESSION['company_last_error'][] = $message;
}

function company_get_last_error(): string
{
    $errs = $_SESSION['company_last_error'] ?? [];
    if (is_array($errs)) {
        $errs = array_values(array_unique(array_map('strval', $errs)));
        return implode(';', $errs);
    }
    return (string)$errs;
}

function company_list(): array
{
	$results = [];
	try {
		$conn = db_connect();
		$sql = 'SELECT ID_Company, Name_Vn, Name_Eng FROM Company ORDER BY ID_Company ASC';
		$stmt = sqlsrv_query($conn, $sql);
		if ($stmt !== false) {
			while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
				$results[] = [
					'id' => (int)($row['ID_Company'] ?? 0),
					'name_vn' => (string)($row['Name_Vn'] ?? ''),
					'name_eng' => (string)($row['Name_Eng'] ?? ''),
				];
			}
			sqlsrv_free_stmt($stmt);
		}
		db_disconnect($conn);
	} catch (Throwable $e) {
	}
	return $results;
}

function company_create(string $nameVn, string $nameEng): bool
{
    unset($_SESSION['company_last_error']);
    $nameVn = trim($nameVn);
    $nameEng = trim($nameEng);
    if ($nameVn === '' || $nameEng === '') { company_set_last_error('VALIDATION:EMPTY'); return false; }
    $conn = db_connect();
    $st = sqlsrv_query($conn, "SELECT 1 FROM Company WHERE RTRIM(LTRIM(ISNULL(Name_Vn, ''))) = RTRIM(LTRIM(?))", [$nameVn]);
    if ($st && sqlsrv_has_rows($st)) { company_set_last_error('VALIDATION:DUPLICATE:VN'); }
    if ($st) sqlsrv_free_stmt($st);
    $st2 = sqlsrv_query($conn, "SELECT 1 FROM Company WHERE RTRIM(LTRIM(ISNULL(Name_Eng, ''))) = RTRIM(LTRIM(?))", [$nameEng]);
    if ($st2 && sqlsrv_has_rows($st2)) { company_set_last_error('VALIDATION:DUPLICATE:ENG'); }
    if ($st2) sqlsrv_free_stmt($st2);
    if (!empty($_SESSION['company_last_error']) && is_array($_SESSION['company_last_error'])) { return false; }
    $sql = "INSERT INTO Company (Name_Vn, Name_Eng)
            SELECT ?, ?
            WHERE NOT EXISTS (
                SELECT 1 FROM Company
                WHERE RTRIM(LTRIM(ISNULL(Name_Vn, ''))) = RTRIM(LTRIM(?))
                   OR RTRIM(LTRIM(ISNULL(Name_Eng, ''))) = RTRIM(LTRIM(?))
            )";
    $stmt = sqlsrv_query($conn, $sql, [$nameVn, $nameEng, $nameVn, $nameEng]);
    if ($stmt === false) {
        $errs = sqlsrv_errors(SQLSRV_ERR_ERRORS);
        $detail = '';
        if (is_array($errs) && count($errs)) {
            $parts = [];
            foreach ($errs as $e) { $parts[] = trim(($e['code'] ?? '') . ' ' . ($e['message'] ?? '')); }
            $detail = implode(' | ', $parts);
        }
        company_set_last_error($detail);
        db_disconnect($conn);
        return false;
    }
    $affected = sqlsrv_rows_affected($stmt);
    sqlsrv_free_stmt($stmt);
    if ($affected === 1) { db_disconnect($conn); return true; }
    db_disconnect($conn);
    return false;
}

function company_update(int $id, string $nameVn, string $nameEng): bool
{
	unset($_SESSION['company_last_error']);
    $nameVn = trim($nameVn);
    $nameEng = trim($nameEng);
    if ($nameVn === '' || $nameEng === '') { company_set_last_error('VALIDATION:EMPTY'); return false; }
    $conn = db_connect();
    $st = sqlsrv_query($conn, "SELECT 1 FROM Company WHERE ID_Company <> ? AND RTRIM(LTRIM(ISNULL(Name_Vn, ''))) = RTRIM(LTRIM(?))", [$id, $nameVn]);
    if ($st && sqlsrv_has_rows($st)) { company_set_last_error('VALIDATION:DUPLICATE:VN'); }
    if ($st) sqlsrv_free_stmt($st);
    $st2 = sqlsrv_query($conn, "SELECT 1 FROM Company WHERE ID_Company <> ? AND RTRIM(LTRIM(ISNULL(Name_Eng, ''))) = RTRIM(LTRIM(?))", [$id, $nameEng]);
    if ($st2 && sqlsrv_has_rows($st2)) { company_set_last_error('VALIDATION:DUPLICATE:ENG'); }
    if ($st2) sqlsrv_free_stmt($st2);
    if (!empty($_SESSION['company_last_error']) && is_array($_SESSION['company_last_error'])) { return false; }
    $sql = "UPDATE Company SET Name_Vn = ?, Name_Eng = ?
            WHERE ID_Company = ?
              AND NOT EXISTS (
                  SELECT 1 FROM Company c2
                  WHERE c2.ID_Company <> ? AND (
                        RTRIM(LTRIM(ISNULL(c2.Name_Vn, ''))) = RTRIM(LTRIM(?))
                     OR RTRIM(LTRIM(ISNULL(c2.Name_Eng, ''))) = RTRIM(LTRIM(?))
                  )
              )";
    $stmt = sqlsrv_query($conn, $sql, [$nameVn, $nameEng, $id, $id, $nameVn, $nameEng]);
    if ($stmt === false) {
        $errs = sqlsrv_errors(SQLSRV_ERR_ERRORS);
        $detail = '';
        if (is_array($errs) && count($errs)) {
            $parts = [];
            foreach ($errs as $e) { $parts[] = trim(($e['code'] ?? '') . ' ' . ($e['message'] ?? '')); }
            $detail = implode(' | ', $parts);
        }
        company_set_last_error($detail);
        db_disconnect($conn);
        return false;
    }
    $affected = sqlsrv_rows_affected($stmt);
    sqlsrv_free_stmt($stmt);
    if ($affected === 1) { db_disconnect($conn); return true; }
    db_disconnect($conn);
    return false;
}

function company_delete(int $id): bool
{
	$conn = db_connect();
	$sql = 'DELETE FROM Company WHERE ID_Company = ?';
	$params = [$id];
    $stmt = sqlsrv_query($conn, $sql, $params);
    $ok = $stmt !== false;
    if (!$ok) {
        $errs = sqlsrv_errors(SQLSRV_ERR_ERRORS);
        $detail = '';
        if (is_array($errs) && count($errs)) {
            $parts = [];
            foreach ($errs as $e) { $parts[] = trim(($e['code'] ?? '') . ' ' . ($e['message'] ?? '')); }
            $detail = implode(' | ', $parts);
        }
        company_set_last_error($detail);
    }
	if ($stmt) sqlsrv_free_stmt($stmt);
	db_disconnect($conn);
	return $ok;
}

// Handle direct requests only when this file is the executing script (not when included)
if (isset($_SERVER['SCRIPT_FILENAME']) && @realpath(__FILE__) === @realpath($_SERVER['SCRIPT_FILENAME'])) {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $respond = function (bool $ok, string $message) use ($messages): void {
        $accept = strtolower((string)($_SERVER['HTTP_ACCEPT'] ?? ''));
        $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strpos($accept, 'application/json') !== false;
        if ($isAjax) {
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode(['ok' => $ok, 'message' => $message], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        } else {
            // For non-AJAX POSTs, redirect back with toast parameters
            if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? '')) === 'POST') {
                $param = $ok ? 'success' : 'error';
                $loc = '../index.php?company&' . $param . '=' . rawurlencode($message);
                header('Location: ' . $loc);
            } else {
                http_response_code($ok ? 200 : 403);
                echo '<!doctype html><html lang="vi"><meta charset="utf-8"><title>Lỗi</title><body style="font-family:system-ui,Segoe UI,Arial">'
                    . '<h2 style="color:#b00020;margin:24px 0">' . htmlspecialchars($message, ENT_QUOTES, 'UTF-8') . '</h2>'
                    . '<p><a href="../index.php?company">' . htmlspecialchars(($messages['error_back_to_company'] ?? 'Quay lại trang Công ty'), ENT_QUOTES, 'UTF-8') . '</a></p>'
                    . '</body></html>';
            }
        }
        exit;
    };

    $action = isset($_POST['action']) ? strtolower(trim((string)$_POST['action'])) : '';
    $id = isset($_POST['id_company']) ? (int)$_POST['id_company'] : 0;
    $nameVn = trim((string)($_POST['name_vn'] ?? ''));
    $nameEng = trim((string)($_POST['name_eng'] ?? ''));
    $license = (string)($_POST['license'] ?? '');

    $settings = db_connection_settings();
    $expected = (string)($settings['license'] ?? '');
    if ($expected === '' || $license !== $expected) { $respond(false, 'Unauthorized request.'); }

    $ok = false; 
    switch ($action) {
        case 'create':
            $ok = company_create($nameVn, $nameEng);
            $detail = company_get_last_error();
            unset($_SESSION['company_last_error']);
            if (!$ok) {
                $codes = array_filter(array_map('trim', explode(';', $detail)));
                $hasDupVn = in_array('VALIDATION:DUPLICATE:VN', $codes, true);
                $hasDupEng = in_array('VALIDATION:DUPLICATE:ENG', $codes, true);
                $hasEmpty = in_array('VALIDATION:EMPTY', $codes, true);
                $parts = [];
                if ($hasEmpty)  { $parts[] = $messages['company_require_both']; }
                if ($hasDupVn)  { $parts[] = $messages['company_duplicate_name_vn']; }
                if ($hasDupEng) { $parts[] = $messages['company_duplicate_name_eng']; }
                if ($parts) {
                    if (count($parts) >= 2) {
                        $numbered = [];
                        foreach ($parts as $idx => $text) { $numbered[] = ($idx + 1) . '. ' . $text; }
                        $msg = implode("\n", $numbered);
                    } else { $msg = implode("\n", $parts); }
                } else { $msg = $messages['company_create_failed'] ?? 'Thêm mới thất bại.'; }
            } else { $msg = $messages['company_create_success'] ?? 'Thêm mới thành công.'; }
            if (!isset($msg)) { $msg = ''; }
            if (isset($_GET['debug']) && $_GET['debug'] === '1' && !empty($detail)) { $msg .= ' [' . (string)$detail . ']'; }
            $respond($ok, $msg);
        case 'update':
            if ($id <= 0 || $nameVn === '' || $nameEng === '') { $respond(false, $messages['company_require_both'] ?? 'Thiếu dữ liệu.'); }
            $ok = company_update($id, $nameVn, $nameEng);
            $detail = company_get_last_error();
            unset($_SESSION['company_last_error']);
            if (!$ok) {
                $codes = array_filter(array_map('trim', explode(';', $detail)));
                $hasDupVn = in_array('VALIDATION:DUPLICATE:VN', $codes, true);
                $hasDupEng = in_array('VALIDATION:DUPLICATE:ENG', $codes, true);
                $hasEmpty = in_array('VALIDATION:EMPTY', $codes, true);
                $parts = [];
                if ($hasEmpty)  { $parts[] = $messages['company_require_both']; }
                if ($hasDupVn)  { $parts[] = $messages['company_duplicate_name_vn']; }
                if ($hasDupEng) { $parts[] = $messages['company_duplicate_name_eng']; }
                if ($parts) {
                    if (count($parts) >= 2) {
                        $numbered = [];
                        foreach ($parts as $idx => $text) { $numbered[] = ($idx + 1) . '. ' . $text; }
                        $msg = implode("\n", $numbered);
                    } else { $msg = implode("\n", $parts); }
                } else { $msg = $messages['company_updat_failed'] ?? 'Cập nhật thất bại.'; }
            } else { $msg = $messages['company_update_success'] ?? 'Cập nhật thành công.'; }
            if (!isset($msg)) { $msg = ''; }
            if (isset($_GET['debug']) && $_GET['debug'] === '1' && !empty($detail)) { $msg .= ' [' . (string)$detail . ']'; }
            $respond($ok, $msg);
        case 'delete':
            if ($id <= 0) { $msg = 'Thiếu dữ liệu.'; break; }
            $ok = company_delete($id);
            $msg = $ok ? $messages['company_delete_success'] : $messages['company_delete_failed'] ?? 'Xoá thất bại.';
            $respond($ok, $msg);
        default:
            $respond(false, 'Invalid action');
    }
} else {
    http_response_code(405);
    echo '<!doctype html><html lang="vi"><meta charset="utf-8"><title>Method Not Allowed</title><body style="font-family:system-ui,Segoe UI,Arial">'
        . '<h2 style="color:#b00020;margin:24px 0">' . htmlspecialchars($messages['error_invalid_access'] ?? 'Truy cập không hợp lệ.', ENT_QUOTES, 'UTF-8') . '</h2>'
        . '<p>' . htmlspecialchars($messages['error_use_interface'] ?? 'Vui lòng thao tác từ giao diện hệ thống.', ENT_QUOTES, 'UTF-8') . '</p>'
        . '<p><a href="../index.php?company=1">' . htmlspecialchars($messages['error_back_to_company'] ?? 'Quay lại trang Công ty', ENT_QUOTES, 'UTF-8') . '</a></p>'
        . '</body></html>';
}
}


