<?php
declare(strict_types=1);

function service_branch_codes(): array
{
    $branches = service_branches();
    $codes = array('SRN', 'BNA', 'RMI', 'RPK');
    $map = array();

    foreach ($branches as $index => $branchName) {
        if (isset($codes[$index])) {
            $map[$branchName] = $codes[$index];
        }
    }

    return $map;
}

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

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

    $code = strtoupper((string) preg_replace('/[^A-Z0-9]+/', '', $branchName));

    if ($code === '') {
        return 'CCW';
    }

    return substr(str_pad($code, 3, 'X'), 0, 3);
}

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);
}
