<?php

if (!function_exists('billing_table_has_column')) {
    function billing_table_has_column(PDO $pdo, $table, $column)
    {
        static $cache = array();
        $key = $table . '.' . $column;
        if (array_key_exists($key, $cache)) {
            return $cache[$key];
        }

        $table = preg_replace('/[^a-zA-Z0-9_]/', '', (string) $table);
        $stmt = $pdo->prepare("SHOW COLUMNS FROM `" . $table . "` LIKE ?");
        $stmt->execute(array($column));
        $cache[$key] = (bool) $stmt->fetch(PDO::FETCH_ASSOC);
        return $cache[$key];
    }
}

if (!function_exists('billing_clean_rut')) {
    function billing_clean_rut($rut)
    {
        $rut = strtoupper(trim((string) $rut));
        $rut = str_replace(array('.', ' '), '', $rut);
        return $rut;
    }
}

if (!function_exists('billing_extract_sku')) {
    function billing_extract_sku($name, $description = '')
    {
        $name = (string) $name;
        $description = (string) $description;

        if (preg_match('/\(SKU:\s*([^\)]+)\)/i', $name, $m)) {
            return trim($m[1]);
        }

        if (preg_match('/SKU\s*(original|homologado)?\s*:\s*([A-Z0-9_\-\+\.]+)/i', $description, $m)) {
            return trim($m[2]);
        }

        return '';
    }
}

if (!function_exists('billing_money')) {
    function billing_money($value)
    {
        return round((float) $value, 2);
    }
}

if (!function_exists('billing_money_equals')) {
    function billing_money_equals($a, $b)
    {
        return billing_money($a) === billing_money($b);
    }
}

if (!function_exists('billing_safe_substr')) {
    function billing_safe_substr($value, $length)
    {
        $value = trim((string) $value);
        if (function_exists('mb_substr')) {
            return mb_substr($value, 0, $length, 'UTF-8');
        }
        return substr($value, 0, $length);
    }
}

if (!function_exists('billing_normalize_environment')) {
    function billing_normalize_environment($environment = null)
    {
        if (function_exists('icylab_facto_normalize_environment')) {
            return icylab_facto_normalize_environment($environment);
        }
        $environment = strtolower(trim((string) $environment));
        return in_array($environment, array('sandbox', 'production'), true) ? $environment : 'sandbox';
    }
}


if (!function_exists('billing_normalize_unit_measure')) {
    function billing_normalize_unit_measure($value)
    {
        $raw = trim((string) $value);
        if ($raw === '') {
            return 'UN';
        }

        $normalized = strtoupper($raw);
        $normalized = strtr($normalized, array(
            'Á' => 'A', 'É' => 'E', 'Í' => 'I', 'Ó' => 'O', 'Ú' => 'U', 'Ñ' => 'N',
            'á' => 'A', 'é' => 'E', 'í' => 'I', 'ó' => 'O', 'ú' => 'U', 'ñ' => 'N'
        ));
        $normalized = preg_replace('/[^A-Z0-9]+/', '', $normalized);

        $map = array(
            'UNIDAD' => 'UN',
            'UNIDADES' => 'UN',
            'UNID' => 'UN',
            'UND' => 'UN',
            'UNDS' => 'UN',
            'U' => 'UN',
            'UN' => 'UN',
            'UNIT' => 'UN',
            'UNITS' => 'UN',
            'SERVICIO' => 'SERV',
            'SERVICIOS' => 'SERV',
            'SERVICE' => 'SERV',
            'SERV' => 'SERV',
            'LITRO' => 'L',
            'LITROS' => 'L',
            'LT' => 'L',
            'LTS' => 'L',
            'L' => 'L',
            'MILILITRO' => 'ML',
            'MILILITROS' => 'ML',
            'ML' => 'ML',
            'MILLILITER' => 'ML',
            'MILLILITERS' => 'ML',
            'GRAMO' => 'G',
            'GRAMOS' => 'G',
            'GR' => 'G',
            'GRS' => 'G',
            'G' => 'G',
            'KILO' => 'KG',
            'KILOS' => 'KG',
            'KILOGRAMO' => 'KG',
            'KILOGRAMOS' => 'KG',
            'KG' => 'KG',
            'KGS' => 'KG',
            'CAJA' => 'CJ',
            'CAJAS' => 'CJ',
            'CJ' => 'CJ',
            'PACK' => 'PACK',
            'PAQ' => 'PAQ',
            'LOTE' => 'LOTE',
            'MES' => 'MES',
            'HORA' => 'HRA',
            'HORAS' => 'HRA',
            'HRA' => 'HRA'
        );

        if (isset($map[$normalized])) {
            return $map[$normalized];
        }

        if ($normalized === '') {
            return 'UN';
        }

        return substr($normalized, 0, 4);
    }
}
