<?php
declare(strict_types=1);

if (!function_exists('company_profile_contact_types')) {
    function company_profile_contact_types(): array
    {
        return [
            'phone' => 'هاتف',
            'mobile' => 'موبايل',
            'whatsapp' => 'واتساب',
            'telegram' => 'تلغرام',
            'email' => 'بريد إلكتروني',
            'website' => 'موقع إلكتروني',
            'facebook' => 'فيسبوك',
            'instagram' => 'إنستغرام',
            'other' => 'وسيلة أخرى',
        ];
    }
}

if (!function_exists('company_profile_table')) {
    function company_profile_table(mysqli $conn): string
    {
        if (function_exists('table_exists') && table_exists($conn, 'company_info')) return 'company_info';
        if (function_exists('table_exists') && table_exists($conn, 'system_settings')) return 'system_settings';
        return '';
    }
}

if (!function_exists('company_profile_ensure_schema')) {
    function company_profile_ensure_schema(mysqli $conn): string
    {
        $table = company_profile_table($conn);
        if ($table === '') return '';
        foreach (['company_name','owner_name','phone','address','logo_path'] as $column) {
            if (!function_exists('col_exists') || !col_exists($conn, $table, $column)) {
                try { $conn->query("ALTER TABLE `$table` ADD COLUMN `$column` VARCHAR(255) NULL"); } catch (Throwable $ignored) {}
            }
        }
        if (!function_exists('col_exists') || !col_exists($conn, $table, 'contact_methods_json')) {
            try { $conn->query("ALTER TABLE `$table` ADD COLUMN `contact_methods_json` LONGTEXT NULL"); } catch (Throwable $ignored) {}
        }
        if (!function_exists('col_exists') || !col_exists($conn, $table, 'admin_alert_phones')) {
            try { $conn->query("ALTER TABLE `$table` ADD COLUMN `admin_alert_phones` TEXT NULL"); } catch (Throwable $ignored) {}
        }
        return $table;
    }
}

if (!function_exists('company_profile_contacts_decode')) {
    function company_profile_contacts_decode($raw): array
    {
        if (is_string($raw)) {
            $decoded = json_decode($raw, true);
            $raw = is_array($decoded) ? $decoded : [];
        }
        if (!is_array($raw)) return [];
        $types = company_profile_contact_types();
        $out = [];
        foreach ($raw as $item) {
            if (!is_array($item)) continue;
            $type = strtolower(trim((string)($item['type'] ?? 'other')));
            if (!isset($types[$type])) $type = 'other';
            $value = trim((string)($item['value'] ?? ''));
            if ($value === '') continue;
            $label = trim((string)($item['label'] ?? ''));
            if ($label === '') $label = $types[$type];
            $out[] = [
                'type' => $type,
                'label' => mb_substr($label, 0, 80, 'UTF-8'),
                'value' => mb_substr($value, 0, 255, 'UTF-8'),
            ];
            if (count($out) >= 30) break;
        }
        return $out;
    }
}

if (!function_exists('company_profile_contacts_from_post')) {
    function company_profile_contacts_from_post(array $post): array
    {
        $types = is_array($post['contact_type'] ?? null) ? $post['contact_type'] : [];
        $labels = is_array($post['contact_label'] ?? null) ? $post['contact_label'] : [];
        $values = is_array($post['contact_value'] ?? null) ? $post['contact_value'] : [];
        $rows = [];
        $count = min(30, max(count($types), count($labels), count($values)));
        for ($i = 0; $i < $count; $i++) {
            $rows[] = [
                'type' => (string)($types[$i] ?? 'other'),
                'label' => (string)($labels[$i] ?? ''),
                'value' => (string)($values[$i] ?? ''),
            ];
        }
        return company_profile_contacts_decode($rows);
    }
}

if (!function_exists('company_profile_fetch')) {
    function company_profile_fetch(mysqli $conn): array
    {
        $company = [
            'company_name' => 'الشركة',
            'owner_name' => '',
            'phone' => '',
            'address' => '',
            'logo_path' => '',
            'contact_methods_json' => '',
            'admin_alert_phones' => '',
            'contacts' => [],
        ];
        $table = company_profile_ensure_schema($conn);
        if ($table !== '') {
            try {
                $result = $conn->query("SELECT * FROM `$table` WHERE id=1 LIMIT 1");
                if ($result && ($row = $result->fetch_assoc())) {
                    foreach (array_keys($company) as $key) {
                        if ($key !== 'contacts' && array_key_exists($key, $row)) {
                            $company[$key] = trim((string)$row[$key]);
                        }
                    }
                }
            } catch (Throwable $ignored) {}
        }
        if ($company['company_name'] === '') $company['company_name'] = 'الشركة';
        $company['contacts'] = company_profile_contacts_decode($company['contact_methods_json']);
        return $company;
    }
}

if (!function_exists('company_profile_contact_lines')) {
    function company_profile_contact_lines(array $company): array
    {
        $lines = [];
        $seen = [];
        $primaryPhone = trim((string)($company['phone'] ?? ''));
        if ($primaryPhone !== '') {
            $lines[] = ['type' => 'phone', 'label' => 'هاتف', 'value' => $primaryPhone];
            $seen[mb_strtolower($primaryPhone, 'UTF-8')] = true;
        }
        foreach (company_profile_contacts_decode($company['contacts'] ?? ($company['contact_methods_json'] ?? [])) as $contact) {
            $key = mb_strtolower(trim((string)$contact['value']), 'UTF-8');
            if ($key === '' || isset($seen[$key])) continue;
            $seen[$key] = true;
            $lines[] = $contact;
        }
        return $lines;
    }
}

if (!function_exists('company_profile_program_name')) {
    function company_profile_program_name(): string
    {
        $name = defined('APP_NAME') ? trim((string)APP_NAME) : '';
        return $name !== '' ? $name : 'إدارة الشبكة والعملاء';
    }
}
