<?php
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 category_set_last_error(string $message): void {
    if (!isset($_SESSION['category_last_error']) || !is_array($_SESSION['category_last_error'])) {
        $_SESSION['category_last_error'] = [];
    }
    $_SESSION['category_last_error'][] = $message;
}
function category_get_last_error(): string {
    $errs = $_SESSION['category_last_error'] ?? [];
    if (is_array($errs)) {
        $errs = array_values(array_unique(array_map('strval', $errs)));
        return implode(';', $errs);
    }
    return (string)$errs;
}

function category_list(): array {
    $results = [];
    try {
        $conn = db_connect();
        $sql = 'SELECT ID_Category, Name_Vn, Name_Eng FROM Category ORDER BY ID_Category ASC';
        $stmt = sqlsrv_query($conn, $sql);
        if ($stmt !== false) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $results[] = [
                    'id' => (int)($row['ID_Category'] ?? 0),
                    'name_vn' => (string)($row['Name_Vn'] ?? ''),
                    'name_eng' => (string)($row['Name_Eng'] ?? ''),
                ];
            }
            sqlsrv_free_stmt($stmt);
        }
        db_disconnect($conn);
    } catch (Throwable $e) {
        error_log("Category list error: " . $e->getMessage());
    }
    return $results;
}

function category_list_paginated(int $page = 1, int $itemsPerPage = 5): array {
    $results = [];
    try {
        $conn = db_connect();
        $offset = ($page - 1) * $itemsPerPage;
        $sql = 'SELECT * FROM (
                    SELECT ID_Category, Name_Vn, Name_Eng, 
                           ROW_NUMBER() OVER (ORDER BY ID_Category ASC) as RowNum
                    FROM Category
                ) AS NumberedRows 
                WHERE RowNum > ? AND RowNum <= ?';
        $stmt = sqlsrv_query($conn, $sql, [$offset, $offset + $itemsPerPage]);
        if ($stmt !== false) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $results[] = [
                    'id' => (int)($row['ID_Category'] ?? 0),
                    'name_vn' => (string)($row['Name_Vn'] ?? ''),
                    'name_eng' => (string)($row['Name_Eng'] ?? ''),
                ];
            }
            sqlsrv_free_stmt($stmt);
        }
        db_disconnect($conn);
    } catch (Throwable $e) {
        // Fallback to regular category_list if pagination fails
        $allCategories = category_list();
        $offset = ($page - 1) * $itemsPerPage;
        $results = array_slice($allCategories, $offset, $itemsPerPage);
    }
    return $results;
}

function category_count(): int {
    $count = 0;
    try {
        $conn = db_connect();
        $sql = 'SELECT COUNT(*) as total FROM Category';
        $stmt = sqlsrv_query($conn, $sql);
        if ($stmt !== false) {
            $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
            $count = (int)($row['total'] ?? 0);
            sqlsrv_free_stmt($stmt);
        }
        db_disconnect($conn);
    } catch (Throwable $e) {}
    return $count;
}

function category_create(string $nameVn, string $nameEng): bool {
    unset($_SESSION['category_last_error']);
    $nameVn = trim($nameVn);
    $nameEng = trim($nameEng);
    if ($nameVn === '' || $nameEng === '') { category_set_last_error('VALIDATION:EMPTY'); return false; }
    $conn = db_connect();
    $st = sqlsrv_query($conn, "SELECT 1 FROM Category WHERE RTRIM(LTRIM(ISNULL(Name_Vn, ''))) = RTRIM(LTRIM(?))", [$nameVn]);
    if ($st && sqlsrv_has_rows($st)) { category_set_last_error('VALIDATION:DUPLICATE:VN'); }
    if ($st) sqlsrv_free_stmt($st);
    $st2 = sqlsrv_query($conn, "SELECT 1 FROM Category WHERE RTRIM(LTRIM(ISNULL(Name_Eng, ''))) = RTRIM(LTRIM(?))", [$nameEng]);
    if ($st2 && sqlsrv_has_rows($st2)) { category_set_last_error('VALIDATION:DUPLICATE:ENG'); }
    if ($st2) sqlsrv_free_stmt($st2);
    if (!empty($_SESSION['category_last_error']) && is_array($_SESSION['category_last_error'])) { return false; }
    $sql = "INSERT INTO Category (Name_Vn, Name_Eng)
            SELECT ?, ?
            WHERE NOT EXISTS (
                SELECT 1 FROM Category
                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) { db_disconnect($conn); return false; }
    $affected = sqlsrv_rows_affected($stmt);
    if ($stmt) sqlsrv_free_stmt($stmt);
    db_disconnect($conn);
    return $affected === 1;
}

function category_update(int $id, string $nameVn, string $nameEng): bool {
    unset($_SESSION['category_last_error']);
    $nameVn = trim($nameVn);
    $nameEng = trim($nameEng);
    if ($nameVn === '' || $nameEng === '') { category_set_last_error('VALIDATION:EMPTY'); return false; }
    $conn = db_connect();
    $st = sqlsrv_query($conn, "SELECT 1 FROM Category WHERE ID_Category <> ? AND RTRIM(LTRIM(ISNULL(Name_Vn, ''))) = RTRIM(LTRIM(?))", [$id, $nameVn]);
    if ($st && sqlsrv_has_rows($st)) { category_set_last_error('VALIDATION:DUPLICATE:VN'); }
    if ($st) sqlsrv_free_stmt($st);
    $st2 = sqlsrv_query($conn, "SELECT 1 FROM Category WHERE ID_Category <> ? AND RTRIM(LTRIM(ISNULL(Name_Eng, ''))) = RTRIM(LTRIM(?))", [$id, $nameEng]);
    if ($st2 && sqlsrv_has_rows($st2)) { category_set_last_error('VALIDATION:DUPLICATE:ENG'); }
    if ($st2) sqlsrv_free_stmt($st2);
    if (!empty($_SESSION['category_last_error']) && is_array($_SESSION['category_last_error'])) { return false; }
    $sql = "UPDATE Category SET Name_Vn = ?, Name_Eng = ? WHERE ID_Category = ?
            AND NOT EXISTS (
                SELECT 1 FROM Category c2
                WHERE c2.ID_Category <> ? 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) { db_disconnect($conn); return false; }
    $affected = sqlsrv_rows_affected($stmt);
    if ($stmt) sqlsrv_free_stmt($stmt);
    db_disconnect($conn);
    return $affected === 1;
}

function category_delete(int $id): bool {
    $conn = db_connect();
    $stmt = sqlsrv_query($conn, 'DELETE FROM Category WHERE ID_Category = ?', [$id]);
    $ok = $stmt !== false;
    if ($stmt) sqlsrv_free_stmt($stmt);
    db_disconnect($conn);
    return $ok;
}

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 {
            if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? '')) === 'POST') {
                $param = $ok ? 'success' : 'error';
                $loc = '../index.php?category=1&' . $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?category=1">' . htmlspecialchars(($messages['error_back_to_company'] ?? 'Quay lại trang'), ENT_QUOTES, 'UTF-8') . '</a></p>'
                    . '</body></html>';
            }
        }
        exit;
    };

    $action = isset($_POST['action']) ? strtolower(trim((string)$_POST['action'])) : '';
    $id = isset($_POST['id_category']) ? (int)$_POST['id_category'] : 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.'); }

    switch ($action) {
        case 'create':
            $ok = category_create($nameVn, $nameEng);
            $detail = category_get_last_error();
            unset($_SESSION['category_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['category_require_name']; }
                if ($hasDupVn)  { $parts[] = $messages['category_duplicate_name_vn']; }
                if ($hasDupEng) { $parts[] = $messages['category_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['category_create_failed']; }
            } else { $msg = $messages['category_create_success']; }
            $respond($ok, $msg);
        case 'update':
            if ($id <= 0 || $nameVn === '' || $nameEng === '') { $respond(false, $messages['category_require_name']); }
            $ok = category_update($id, $nameVn, $nameEng);
            $detail = category_get_last_error();
            unset($_SESSION['category_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['category_require_name']; }
                if ($hasDupVn)  { $parts[] = $messages['category_duplicate_name_vn']; }
                if ($hasDupEng) { $parts[] = $messages['category_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['category_update_failed']; }
            } else { $msg = $messages['category_update_success']; }
            $respond($ok, $msg);
        case 'delete':
            if ($id <= 0) { $respond(false, 'Thiếu dữ liệu.'); }
            $ok = category_delete($id);
            $msg = $ok ? $messages['category_delete_success'] : $messages['category_delete_failed'];
            $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?category=1">' . htmlspecialchars($messages['error_back_to_company'] ?? 'Quay lại trang', ENT_QUOTES, 'UTF-8') . '</a></p>'
        . '</body></html>';
}
}








