<?php

if (!function_exists('delivery_exclusion_normalise_codes')) {
    function delivery_exclusion_normalise_codes(array $codes): array
    {
        $out = [];

        foreach ($codes as $code) {
            if (is_array($code)) {
                $code = $code['code'] ?? '';
            }
            $code = strtoupper(trim((string)$code));
            if ($code !== '') {
                $out[$code] = true;
            }
        }

        return $out;
    }
}

if (!function_exists('delivery_exclusion_flag_enabled')) {
    function delivery_exclusion_flag_enabled($value): bool
    {
        if (is_bool($value)) {
            return $value;
        }

        $value = strtolower(trim((string)$value));
        return in_array($value, ['1', 'true', 'yes', 'y', 'on'], true);
    }
}

if (!function_exists('delivery_exclusion_normalise_codes_for_scope')) {
    function delivery_exclusion_normalise_codes_for_scope(array $codes, string $scope): array
    {
        $out = [];
        $scope = strtolower(trim($scope));

        foreach ($codes as $entry) {
            if (is_array($entry)) {
                $code = strtoupper(trim((string)($entry['code'] ?? '')));
                $enabled = delivery_exclusion_flag_enabled($entry[$scope] ?? false);
            } else {
                $code = strtoupper(trim((string)$entry));
                $enabled = $scope !== 'delivery';
            }

            if ($code !== '' && $enabled) {
                $out[$code] = true;
            }
        }

        return $out;
    }
}

if (!function_exists('delivery_exclusion_tenant_codes')) {
    function delivery_exclusion_tenant_codes(): array
    {
        static $codes = null;

        if ($codes !== null) {
            return $codes;
        }

        $codes = [];
        $tenantDir = defined('TENANT_URL') ? trim((string)TENANT_URL, "/\\") : enrep_tenant_segment();
        if ($tenantDir === '') {
            return $codes;
        }

        $path = __DIR__ . '/../../../' . $tenantDir . '/output/delivery_exclusions.php';
        if (!is_file($path)) {
            return $codes;
        }

        $excludeCodes = [];
        $loaded = include $path;

        if (is_array($loaded)) {
            $excludeCodes = $loaded;
        }

        if (is_array($excludeCodes)) {
            $codes = delivery_exclusion_normalise_codes_for_scope($excludeCodes, 'delivery');
        }

        return $codes;
    }
}

if (!function_exists('delivery_exclusion_global_codes')) {
    function delivery_exclusion_global_codes(): array
    {
        static $codes = null;

        if ($codes !== null) {
            return $codes;
        }

        $codes = [];

        if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
            return $codes;
        }

        try {
            $stmt = $GLOBALS['con']->prepare("
                SELECT `code`
                FROM `dd_plant`
                WHERE `delivery_exclusion` = 1
                  AND `code` IS NOT NULL
                  AND `code` <> ''
            ");
            if (!$stmt) {
                return $codes;
            }
            $stmt->execute();
            $res = $stmt->get_result();
            $stmt->close();
        } catch (Throwable $e) {
            return $codes;
        }

        if (!$res) {
            return $codes;
        }

        while ($row = mysqli_fetch_assoc($res)) {
            $code = strtoupper(trim((string)($row['code'] ?? '')));
            if ($code !== '') {
                $codes[$code] = true;
            }
        }

        return $codes;
    }
}

if (!function_exists('delivery_exclusion_codes')) {
    function delivery_exclusion_codes(): array
    {
        return delivery_exclusion_global_codes() + delivery_exclusion_tenant_codes();
    }
}

if (!function_exists('delivery_item_code_excluded')) {
    function delivery_item_code_excluded($code): bool
    {
        $code = strtoupper(trim((string)$code));
        if ($code === '') {
            return false;
        }

        $codes = delivery_exclusion_codes();
        return isset($codes[$code]);
    }
}

if (!function_exists('delivery_filter_repitems_by_exclusions')) {
    function delivery_filter_repitems_by_exclusions(array $repitems): array
    {
        $repitems = array_values(array_filter(array_map('intval', $repitems)));
        if (empty($repitems) || empty(delivery_exclusion_codes())) {
            return $repitems;
        }

        $sqlRepitems = implode(',', array_values(array_unique($repitems)));
        $excludedRepitems = [];
        $res = mysqli_query($GLOBALS['con'], "
            SELECT DISTINCT a.`repitem`, b.`code`
            FROM `reportitems` a
            INNER JOIN `itemdetails` b ON b.`itemnumber` = a.`itemnumber`
            WHERE a.`repitem` IN ($sqlRepitems)
        ");

        if (!$res) {
            return $repitems;
        }

        while ($row = mysqli_fetch_assoc($res)) {
            if (delivery_item_code_excluded($row['code'] ?? '')) {
                $excludedRepitems[(int)$row['repitem']] = true;
            }
        }

        if (empty($excludedRepitems)) {
            return $repitems;
        }

        return array_values(array_filter($repitems, static function ($repitem) use ($excludedRepitems) {
            return !isset($excludedRepitems[(int)$repitem]);
        }));
    }
}
