<?php

use CodeIgniter\I18n\Time;
use Config\Company;

if (! function_exists('format_money')) {
    function format_money(float|int|string|null $amount): string
    {
        return '$ ' . number_format((float) $amount, 2, '.', ',');
    }
}

if (! function_exists('format_quote_date')) {
    function format_quote_date(string|null $date): string
    {
        if ($date === null || $date === '') {
            return '';
        }

        $time = Time::parse($date, 'America/Mexico_City');
        $formatter = new \IntlDateFormatter(
            'es_MX',
            \IntlDateFormatter::LONG,
            \IntlDateFormatter::NONE,
            'America/Mexico_City',
            \IntlDateFormatter::GREGORIAN,
            "d 'de' MMMM 'de' yyyy"
        );

        $formatted = $formatter->format($time->toDateTime());

        return is_string($formatted) ? $formatted : $time->format('d/m/Y');
    }
}

if (! function_exists('company_asset_path')) {
    function company_asset_path(string $relativePath): ?string
    {
        $path = FCPATH . ltrim(str_replace('/', DIRECTORY_SEPARATOR, $relativePath), DIRECTORY_SEPARATOR);

        return is_file($path) ? str_replace('\\', '/', $path) : null;
    }
}

if (! function_exists('company_config')) {
    function company_config(): Company
    {
        return config('Company');
    }
}

if (! function_exists('customer_display_name')) {
    function customer_display_name(array $quotation): string
    {
        return $quotation['customer_name'] ?: 'Cliente';
    }
}

if (! function_exists('quotation_status_label')) {
    function quotation_status_label(?string $status): string
    {
        return match ((string) $status) {
            'draft' => 'Borrador',
            'issued' => 'Emitida',
            'approved' => 'Aprobada',
            'rejected' => 'Rechazada',
            'expired' => 'Vencida',
            'cancelled' => 'Cancelada',
            default => 'Emitida',
        };
    }
}

if (! function_exists('system_settings_map')) {
    function system_settings_map(): array
    {
        static $settings;

        if (is_array($settings)) {
            return $settings;
        }

        try {
            $db = db_connect();
            if (! method_exists($db, 'tableExists') || ! $db->tableExists('system_settings')) {
                $settings = [];

                return $settings;
            }

            $settings = (new \App\Models\SystemSettingModel())->getMap();
        } catch (\Throwable $e) {
            $settings = [];
        }

        return $settings;
    }
}

if (! function_exists('system_setting')) {
    function system_setting(string $key, mixed $default = null): mixed
    {
        $settings = system_settings_map();

        return array_key_exists($key, $settings) ? $settings[$key] : $default;
    }
}

if (! function_exists('settings_lines')) {
    function settings_lines(?string $value, array $fallback = []): array
    {
        if ($value === null || trim($value) === '') {
            return $fallback;
        }

        $lines = preg_split('/\r\n|\r|\n/', $value) ?: [];
        $lines = array_values(array_filter(array_map(static fn (string $line): string => trim($line), $lines)));

        return $lines === [] ? $fallback : $lines;
    }
}

if (! function_exists('settings_lines_text')) {
    function settings_lines_text(array $lines): string
    {
        return implode(PHP_EOL, array_values(array_filter(array_map(static fn ($line): string => trim((string) $line), $lines))));
    }
}

if (! function_exists('company_profile')) {
    function company_profile(): array
    {
        $config = company_config();
        $name = trim((string) system_setting('company_name', $config->name));
        $brandMark = trim((string) system_setting('brand_mark', ''));

        if ($brandMark === '') {
            $lower = mb_strtolower($name, 'UTF-8');
            $brandMark = mb_substr($lower, 0, 4, 'UTF-8');
            $brandMark = $brandMark !== '' ? $brandMark : 'simp';
        }

        return [
            'name' => $name,
            'brand_mark' => $brandMark,
            'tagline' => trim((string) system_setting('company_tagline', 'Sistemas Integrales de Mantenimiento')),
            'website' => trim((string) system_setting('company_website', $config->website)),
            'linkedin' => trim((string) system_setting('company_linkedin', $config->linkedin)),
            'whatsapp' => trim((string) system_setting('company_whatsapp', $config->whatsapp)),
            'emails' => settings_lines(system_setting('company_emails'), $config->emails),
            'phones' => settings_lines(system_setting('company_phones'), $config->phones),
            'intro_lead' => trim((string) system_setting('company_intro_lead', $config->introLead)),
            'intro_body' => trim((string) system_setting('company_intro_body', $config->introBody)),
            'strengths' => settings_lines(system_setting('company_strengths'), $config->strengths),
            'default_delivery_time' => trim((string) system_setting('default_delivery_time', $config->defaultDeliveryTime)),
            'default_payment_terms' => trim((string) system_setting('default_payment_terms', $config->defaultPaymentTerms)),
            'condition_lines' => settings_lines(system_setting('condition_lines'), $config->conditionLines),
            'developer_footer' => trim((string) system_setting('developer_footer', 'Simprofire · Sistemas Integrales de Mantenimiento')),
            'logo_path' => trim((string) system_setting('company_logo_path', '')),
            'qr_path' => trim((string) system_setting('company_qr_path', '')),
        ];
    }
}

if (! function_exists('company_brand_asset_url')) {
    function company_brand_asset_url(string $type): ?string
    {
        $company = company_profile();
        $settingPath = $type === 'qr' ? $company['qr_path'] : $company['logo_path'];

        if ($settingPath !== '') {
            $fullPath = FCPATH . ltrim(str_replace('/', DIRECTORY_SEPARATOR, $settingPath), DIRECTORY_SEPARATOR);
            if (is_file($fullPath)) {
                return base_url(str_replace('\\', '/', $settingPath));
            }
        }

        $fallbackRelativePath = $type === 'qr' ? 'assets/brand/qr.png' : 'assets/brand/logo.png';

        if (company_asset_path($fallbackRelativePath) === null) {
            return null;
        }

        return base_url($fallbackRelativePath);
    }
}

if (! function_exists('company_brand_asset_path')) {
    function company_brand_asset_path(string $type): ?string
    {
        $company = company_profile();
        $settingPath = $type === 'qr' ? $company['qr_path'] : $company['logo_path'];

        if ($settingPath !== '') {
            $fullPath = FCPATH . ltrim(str_replace('/', DIRECTORY_SEPARATOR, $settingPath), DIRECTORY_SEPARATOR);
            if (is_file($fullPath)) {
                return str_replace('\\', '/', $fullPath);
            }
        }

        return company_asset_path($type === 'qr' ? 'assets/brand/qr.png' : 'assets/brand/logo.png');
    }
}

if (! function_exists('branding_pin_hash')) {
    function branding_pin_hash(): string
    {
        $envPin = (string) env('BRANDING_PIN', '2468');
        return (string) system_setting('branding_pin_hash', password_hash($envPin, PASSWORD_DEFAULT));
    }
}
