<?php
declare(strict_types=1);

function branch_catalog_thai(): array
{
    return array(
        'srinakarin' => json_decode('"\u0e2a\u0e32\u0e02\u0e32\u0e28\u0e23\u0e35\u0e19\u0e04\u0e23\u0e34\u0e19\u0e17\u0e23\u0e4c"'),
        'bangna' => json_decode('"\u0e2a\u0e32\u0e02\u0e32\u0e1a\u0e32\u0e07\u0e19\u0e32"'),
        'ramintra' => json_decode('"\u0e2a\u0e32\u0e02\u0e32\u0e23\u0e32\u0e21\u0e2d\u0e34\u0e19\u0e17\u0e23\u0e32"'),
        'rachapruek' => json_decode('"\u0e2a\u0e32\u0e02\u0e32\u0e23\u0e32\u0e0a\u0e1e\u0e24\u0e01\u0e29\u0e4c"'),
    );
}

function canonical_service_branches(): array
{
    return array_values(branch_catalog_thai());
}

function branch_name_replacements(): array
{
    static $cache = null;

    if (is_array($cache)) {
        return $cache;
    }

    $branches = branch_catalog_thai();
    $cache = array();

    foreach ($branches as $code => $canonicalName) {
        $cache[$canonicalName] = $canonicalName;
    }

    $cache[json_decode('"\u0e28\u0e23\u0e35\u0e19\u0e04\u0e23\u0e34\u0e19\u0e17\u0e23\u0e4c"')] = $branches['srinakarin'];
    $cache[json_decode('"\u0e1a\u0e32\u0e07\u0e19\u0e32"')] = $branches['bangna'];
    $cache[json_decode('"\u0e23\u0e32\u0e21\u0e2d\u0e34\u0e19\u0e17\u0e23\u0e32"')] = $branches['ramintra'];
    $cache[json_decode('"\u0e23\u0e32\u0e0a\u0e1e\u0e24\u0e01\u0e29\u0e4c"')] = $branches['rachapruek'];

    $cache['srn'] = $branches['srinakarin'];
    $cache['bna'] = $branches['bangna'];
    $cache['rmi'] = $branches['ramintra'];
    $cache['rpk'] = $branches['rachapruek'];

    $cache['srinakarin'] = $branches['srinakarin'];
    $cache['srinakharin'] = $branches['srinakarin'];
    $cache['bangna'] = $branches['bangna'];
    $cache['ramintra'] = $branches['ramintra'];
    $cache['ramindra'] = $branches['ramintra'];
    $cache['rachapruek'] = $branches['rachapruek'];
    $cache['ratchapruek'] = $branches['rachapruek'];
    $cache['ratchaphruek'] = $branches['rachapruek'];
    $cache['rajapruek'] = $branches['rachapruek'];

    return $cache;
}

function normalize_branch_name(?string $branchName): string
{
    $branchName = trim((string) $branchName);

    if ($branchName === '') {
        return '';
    }

    $replacements = branch_name_replacements();

    if (isset($replacements[$branchName])) {
        return $replacements[$branchName];
    }

    $asciiKey = strtolower($branchName);

    return $replacements[$asciiKey] ?? $branchName;
}

function normalize_branch_names_in_database(mysqli $conn): void
{
    static $normalized = false;

    if ($normalized) {
        return;
    }

    $replacements = branch_name_replacements();
    $tables = array('orders', 'audit_logs', 'quick_service_settings_profiles');

    foreach ($tables as $tableName) {
        foreach ($replacements as $sourceName => $targetName) {
            if ($sourceName === $targetName) {
                continue;
            }

            $stmt = db_prepare($conn, "UPDATE {$tableName} SET branch_name = ? WHERE branch_name = ?");

            if ($stmt === false) {
                continue;
            }

            $stmt->bind_param('ss', $targetName, $sourceName);
            $stmt->execute();
            $stmt->close();
        }
    }

    $normalized = true;
}

function service_branches(): array
{
    return canonical_service_branches();
}

function normalized_branch_options(array $branchNames): array
{
    $normalized = array();

    foreach ($branchNames as $branchName) {
        $branchName = normalize_branch_name((string) $branchName);

        if ($branchName === '' || in_array($branchName, $normalized, true)) {
            continue;
        }

        $normalized[] = $branchName;
    }

    return $normalized;
}

function distinct_branch_options_from_table(mysqli $conn, string $tableName): array
{
    static $cache = array();

    $tableName = strtolower(trim($tableName));
    $allowedTables = array('orders', 'audit_logs');

    if (!in_array($tableName, $allowedTables, true)) {
        return service_branches();
    }

    if (isset($cache[$tableName])) {
        return $cache[$tableName];
    }

    $branchNames = service_branches();
    $result = $conn->query("
        SELECT DISTINCT branch_name
        FROM {$tableName}
        WHERE branch_name IS NOT NULL AND branch_name <> ''
        ORDER BY branch_name ASC
    ");

    if ($result instanceof mysqli_result) {
        while ($row = $result->fetch_assoc()) {
            $branchNames[] = (string) ($row['branch_name'] ?? '');
        }
    }

    $cache[$tableName] = normalized_branch_options($branchNames);

    return $cache[$tableName];
}

function order_branch_options(mysqli $conn): array
{
    return distinct_branch_options_from_table($conn, 'orders');
}

function authorized_order_branch_options(mysqli $conn): array
{
    static $cache = null;

    if (is_array($cache)) {
        return $cache;
    }

    $cache = auth_filter_branch_options($conn, order_branch_options($conn));

    return $cache;
}

function audit_branch_options(mysqli $conn): array
{
    return distinct_branch_options_from_table($conn, 'audit_logs');
}

function authorized_audit_branch_options(mysqli $conn): array
{
    static $cache = null;

    if (is_array($cache)) {
        return $cache;
    }

    $cache = auth_filter_branch_options($conn, audit_branch_options($conn));

    return $cache;
}
