<?php
if (!function_exists('delivery_report_list_tokens')) {
    function delivery_report_list_tokens($value)
    {
        if (is_array($value)) {
            if (isset($value['reports']) && is_array($value['reports'])) {
                return delivery_report_list_tokens($value['reports']);
            }

            if (isset($value['repnumber']) || isset($value['itemnumber'])) {
                $token = delivery_report_array_to_token($value);
                return $token === '' ? [] : [$token];
            }

            $tokens = [];
            foreach ($value as $item) {
                foreach (delivery_report_list_tokens($item) as $token) {
                    if ($token !== '') {
                        $tokens[] = $token;
                    }
                }
            }
            return $tokens;
        }

        $raw = trim((string) $value);
        if ($raw === '' || $raw === '0' || strtolower($raw) === 'delivery') {
            return [];
        }

        $decoded = json_decode($raw, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            return delivery_report_list_tokens($decoded);
        }

        return array_values(array_filter(array_map('trim', explode('|', $raw)), static function ($token) {
            return $token !== '';
        }));
    }

    function delivery_report_array_to_token(array $report)
    {
        if (isset($report['token']) && trim((string) $report['token']) !== '') {
            return trim((string) $report['token']);
        }

        $repnumber = trim((string) ($report['repnumber'] ?? ''));
        $itemnumber = trim((string) ($report['itemnumber'] ?? ''));
        $reptype = trim((string) ($report['reptype'] ?? ''));
        $esname = trim((string) ($report['esname'] ?? ''));

        if ($repnumber === '' && $itemnumber === '' && $reptype === '' && $esname === '') {
            return '';
        }

        return $repnumber . '-' . $itemnumber . '-' . $reptype . '-' . $esname;
    }

    function delivery_report_token_parts($token)
    {
        $parts = explode('-', (string) $token);

        return [
            'repnumber' => $parts[0] ?? '',
            'itemnumber' => $parts[1] ?? '',
            'reptype' => $parts[2] ?? '',
            'esname' => $parts[3] ?? ''
        ];
    }

    function delivery_report_list_json($value)
    {
        return json_encode(delivery_report_list_tokens($value), JSON_UNESCAPED_UNICODE);
    }
}
