<?php
declare(strict_types=1);

function service_branch_codes(?mysqli $conn = null): array
{
    $resolvedConnection = branch_resolve_connection($conn);
    $map = array();

    if ($resolvedConnection instanceof mysqli) {
        foreach (branch_master_rows($resolvedConnection, true) as $row) {
            $branchName = trim((string) ($row['branch_name'] ?? ''));
            $branchCode = normalize_branch_code((string) ($row['branch_code'] ?? ''));

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

            if ($branchCode === '') {
                $branchCode = branch_generated_code_from_name($branchName);
            }

            $map[$branchName] = $branchCode;
        }
    }

    if (!empty($map)) {
        return $map;
    }

    foreach (branch_seed_code_map() as $branchName => $branchCode) {
        if (trim((string) $branchName) !== '' && trim((string) $branchCode) !== '') {
            $map[(string) $branchName] = normalize_branch_code((string) $branchCode);
        }
    }

    return $map;
}

function branch_code(string $branchName): string
{
    $branchName = normalize_branch_name($branchName);
    $branchCodes = service_branch_codes();

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

    return branch_generated_code_from_name($branchName === '' ? 'CCW' : $branchName);
}

function build_order_bill_number(string $branchName, ?string $orderDate, int $orderId): string
{
    $timestamp = $orderDate ? strtotime($orderDate) : false;

    if ($timestamp === false) {
        $timestamp = time();
    }

    return branch_code($branchName) . date('mY', $timestamp) . '/' . str_pad((string) $orderId, 4, '0', STR_PAD_LEFT);
}
