<?php
declare(strict_types=1);

if (!function_exists('srs_profiles')) {
    function srs_profiles(): array
    {
        return [
            'cudy' => [
                'label' => 'Cudy',
                'models' => [
                    'wr1200-v1' => ['model'=>'WR1200','revision'=>'1.0','bands'=>['2.4','5']],
                    'wr1200-v2' => ['model'=>'WR1200','revision'=>'2.0 / 2.1','bands'=>['2.4','5']],
                    'wr1200-v3' => ['model'=>'WR1200','revision'=>'3.0','bands'=>['2.4','5']],
                    'wr1300-v1' => ['model'=>'WR1300','revision'=>'1.0','bands'=>['2.4','5']],
                    'wr1300-v2' => ['model'=>'WR1300','revision'=>'2.0','bands'=>['2.4','5']],
                    'wr1300-v3' => ['model'=>'WR1300','revision'=>'3.0','bands'=>['2.4','5']],
                    'wr3000-v1' => ['model'=>'WR3000','revision'=>'1.0','bands'=>['2.4','5']],
                    'wr3000s-v1' => ['model'=>'WR3000S','revision'=>'1.0','bands'=>['2.4','5']],
                ],
            ],
            'netis' => [
                'label' => 'Netis',
                'models' => [
                    'wf2419e-v6' => ['model'=>'WF2419E','revision'=>'V6','bands'=>['2.4']],
                    'wf2409e-v6' => ['model'=>'WF2409E','revision'=>'V6','bands'=>['2.4']],
                    'nx10-v1' => ['model'=>'NX10','revision'=>'V1','bands'=>['2.4','5']],
                    'nc63-v4' => ['model'=>'NC63','revision'=>'V4','bands'=>['2.4','5']],
                    'nc21-v2' => ['model'=>'NC21','revision'=>'V2','bands'=>['2.4','5']],
                    'w1' => ['model'=>'W1','revision'=>'لوحة الجهاز','bands'=>['2.4']],
                ],
            ],
            'dlink' => [
                'label' => 'D-Link',
                'models' => [
                    'dir615-i1' => ['model'=>'DIR-615','revision'=>'I1','bands'=>['2.4']],
                    'dir615-t3' => ['model'=>'DIR-615','revision'=>'T3','bands'=>['2.4']],
                    'dir615-e4' => ['model'=>'DIR-615','revision'=>'E4','bands'=>['2.4']],
                    'dir825-j1' => ['model'=>'DIR-825','revision'=>'J1','bands'=>['2.4','5']],
                    'dirx1560-a1' => ['model'=>'DIR-X1560','revision'=>'A1','bands'=>['2.4','5']],
                    'dsl2750u' => ['model'=>'DSL-2750U','revision'=>'حسب الملصق','bands'=>['2.4']],
                ],
            ],
            'tplink' => [
                'label' => 'TP-Link',
                'models' => [
                    'archerc6-v2' => ['model'=>'Archer C6','revision'=>'V2','bands'=>['2.4','5']],
                    'archerc6-v4' => ['model'=>'Archer C6','revision'=>'V4','bands'=>['2.4','5']],
                    'archerc6-v6' => ['model'=>'Archer C6','revision'=>'V6','bands'=>['2.4','5']],
                    'archerc50-v5' => ['model'=>'Archer C50','revision'=>'V5','bands'=>['2.4','5']],
                    'archerc54-v1' => ['model'=>'Archer C54','revision'=>'V1 / V1.6','bands'=>['2.4','5']],
                    'tlwr840n-v6' => ['model'=>'TL-WR840N','revision'=>'V6 / V6.2','bands'=>['2.4']],
                    'tlwr841n-v14' => ['model'=>'TL-WR841N','revision'=>'V14','bands'=>['2.4']],
                ],
            ],
            'manual' => [
                'label' => 'إعداد يدوي / موديل آخر',
                'models' => [
                    'single-24' => ['model'=>'نطاق واحد','revision'=>'2.4 GHz','bands'=>['2.4']],
                    'dual-245' => ['model'=>'ثنائي النطاق','revision'=>'2.4 / 5 GHz','bands'=>['2.4','5']],
                    'triple-2456' => ['model'=>'ثلاثي النطاق','revision'=>'2.4 / 5 / 6 GHz','bands'=>['2.4','5','6']],
                    'multi-24567' => ['model'=>'متعدد النطاقات','revision'=>'2.4 / 5 / 6 / 7 GHz','bands'=>['2.4','5','6','7']],
                ],
            ],
        ];
    }
}

if (!function_exists('srs_profile')) {
    function srs_profile(string $vendor, string $key): ?array
    {
        $profiles = srs_profiles();
        if (!isset($profiles[$vendor]['models'][$key])) return null;
        return array_merge(['vendor'=>$vendor,'vendor_label'=>$profiles[$vendor]['label'],'key'=>$key], $profiles[$vendor]['models'][$key]);
    }
}

if (!function_exists('srs_ensure_schema')) {
    function srs_ensure_schema(mysqli $conn): void
    {
        $conn->query("CREATE TABLE IF NOT EXISTS subscriber_router_setups (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            subscriber_id INT NOT NULL,
            vendor VARCHAR(40) NOT NULL,
            profile_key VARCHAR(80) NOT NULL,
            model VARCHAR(100) NOT NULL,
            hardware_revision VARCHAR(80) NOT NULL DEFAULT '',
            wan_type VARCHAR(20) NOT NULL DEFAULT 'pppoe',
            encrypted_payload LONGTEXT NOT NULL,
            restore_status VARCHAR(40) NOT NULL DEFAULT 'not_verified',
            created_by VARCHAR(120) NOT NULL DEFAULT '',
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            KEY idx_router_setup_subscriber (subscriber_id, created_at),
            KEY idx_router_setup_profile (vendor, profile_key)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        $root = dirname(__DIR__) . '/storage/subscriber_router_setups';
        if (!is_dir($root)) @mkdir($root, 0770, true);
        if (!is_file($root . '/.htaccess')) @file_put_contents($root . '/.htaccess', "Require all denied\n");
    }
}

if (!function_exists('srs_key')) {
    function srs_key(): string
    {
        $path = dirname(__DIR__) . '/storage/subscriber_router_setups/app.key';
        if (!is_file($path)) {
            $key = random_bytes(32);
            if (@file_put_contents($path, base64_encode($key), LOCK_EX) === false) throw new RuntimeException('تعذر إنشاء مفتاح حماية إعدادات الراوتر.');
            @chmod($path, 0600);
            return $key;
        }
        $key = base64_decode(trim((string)file_get_contents($path)), true);
        if (!is_string($key) || strlen($key) !== 32) throw new RuntimeException('مفتاح حماية إعدادات الراوتر غير صالح.');
        return $key;
    }
}

if (!function_exists('srs_encrypt')) {
    function srs_encrypt(array $payload): string
    {
        $iv = random_bytes(12);
        $tag = '';
        $plain = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
        $cipher = openssl_encrypt($plain, 'aes-256-gcm', srs_key(), OPENSSL_RAW_DATA, $iv, $tag);
        if ($cipher === false) throw new RuntimeException('تعذر حماية إعدادات الراوتر.');
        return base64_encode($iv . $tag . $cipher);
    }
}

if (!function_exists('srs_decrypt')) {
    function srs_decrypt(string $encoded): array
    {
        $raw = base64_decode($encoded, true);
        if (!is_string($raw) || strlen($raw) < 29) return [];
        $iv = substr($raw, 0, 12);
        $tag = substr($raw, 12, 16);
        $plain = openssl_decrypt(substr($raw, 28), 'aes-256-gcm', srs_key(), OPENSSL_RAW_DATA, $iv, $tag);
        if (!is_string($plain)) return [];
        $data = json_decode($plain, true);
        return is_array($data) ? $data : [];
    }
}

if (!function_exists('srs_password')) {
    function srs_password(string $level): string
    {
        $digits = '0123456789';
        $letters = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
        $symbols = '!#$%+-_@';
        $pick = static function (string $chars, int $count): string {
            $out = '';
            for ($i = 0, $max = strlen($chars) - 1; $i < $count; $i++) $out .= $chars[random_int(0, $max)];
            return $out;
        };
        $shuffle = static function (string $value): string {
            $chars = str_split($value);
            for ($i = count($chars) - 1; $i > 0; $i--) {
                $j = random_int(0, $i);
                [$chars[$i], $chars[$j]] = [$chars[$j], $chars[$i]];
            }
            return implode('', $chars);
        };
        if ($level === 'weak') return $pick($digits, 8);
        if ($level === 'medium') return $shuffle($pick($digits, 8) . $pick($letters, 1) . $pick($symbols, 1));
        return $shuffle($pick($digits, 3) . $pick($letters, 4) . $pick($symbols, 3));
    }
}

if (!function_exists('srs_password_valid_for_level')) {
    function srs_password_valid_for_level(string $password, string $level): bool
    {
        if ($level === 'weak') return (bool)preg_match('/^\d{8}$/', $password);
        if ($level === 'medium') {
            return strlen($password) === 10
                && preg_match_all('/\d/', $password) === 8
                && (bool)preg_match('/[A-Za-z]/', $password)
                && (bool)preg_match('/[^A-Za-z0-9]/', $password);
        }
        return strlen($password) >= 8 && strlen($password) <= 10
            && (bool)preg_match('/\d/', $password)
            && (bool)preg_match('/[A-Za-z]/', $password)
            && (bool)preg_match('/[^A-Za-z0-9]/', $password);
    }
}

if (!function_exists('srs_latin_name')) {
    function srs_latin_name(string $name): string
    {
        $map = [
            'ا'=>'a','أ'=>'a','إ'=>'i','آ'=>'a','ب'=>'b','ت'=>'t','ث'=>'th','ج'=>'j','ح'=>'h','خ'=>'kh',
            'د'=>'d','ذ'=>'th','ر'=>'r','ز'=>'z','س'=>'s','ش'=>'sh','ص'=>'s','ض'=>'d','ط'=>'t','ظ'=>'z',
            'ع'=>'a','غ'=>'gh','ف'=>'f','ق'=>'q','ك'=>'k','ل'=>'l','م'=>'m','ن'=>'n','ه'=>'h','ة'=>'h',
            'و'=>'w','ؤ'=>'o','ي'=>'y','ى'=>'a','ئ'=>'e','ء'=>'','ـ'=>'',
        ];
        $latin = strtr(trim($name), $map);
        if (function_exists('iconv')) {
            $ascii = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $latin);
            if (is_string($ascii) && $ascii !== '') $latin = $ascii;
        }
        $latin = preg_replace('/[^A-Za-z0-9]+/', '-', $latin) ?? '';
        return trim(preg_replace('/-+/', '-', $latin) ?? '', '-');
    }
}

if (!function_exists('srs_ssid')) {
    function srs_ssid(array $subscriber, string $band): string
    {
        // اسم الشبكة يعتمد على حقل الاسم فقط، بلا اسم الأب أو الكنية.
        $firstName = trim((string)($subscriber['first_name'] ?? ''));
        if ($firstName === '') {
            $fullName = trim((string)($subscriber['full_name'] ?? ''));
            $firstName = preg_split('/\s+/u', $fullName, 2)[0] ?? '';
        }
        $base = srs_latin_name($firstName);
        if ($base === '') $base = 'Customer-' . (int)($subscriber['id'] ?? 0);
        $suffixes = ['5'=>'-5G', '6'=>'-6G', '7'=>'-7G', 'guest'=>'-Guest'];
        $suffix = $suffixes[$band] ?? '';
        return substr($base, 0, max(1, 32 - strlen($suffix))) . $suffix;
    }
}

if (!function_exists('srs_wifi_qr_payload')) {
    function srs_wifi_qr_payload(string $ssid, string $password, bool $hidden = false): string
    {
        $escape = static fn(string $v): string => str_replace(['\\',';',',',':','"'], ['\\\\','\\;','\\,','\\:','\\"'], $v);
        return 'WIFI:T:WPA;S:' . $escape($ssid) . ';P:' . $escape($password) . ';H:' . ($hidden ? 'true' : 'false') . ';;';
    }
}

if (!function_exists('srs_save')) {
    function srs_save(mysqli $conn, int $subscriberId, array $profile, array $payload): int
    {
        $encrypted = srs_encrypt($payload);
        $vendor = (string)$profile['vendor'];
        $key = (string)$profile['key'];
        $model = (string)$profile['model'];
        $revision = (string)$profile['revision'];
        // حقل قديم محفوظ لتوافق قاعدة البيانات فقط؛ ميزة ملفات الاستعادة أزيلت من البرنامج.
        $status = 'not_applicable';
        $actor = (string)($_SESSION['admin_username'] ?? $_SESSION['admin_user'] ?? 'admin');
        $stmt = $conn->prepare('INSERT INTO subscriber_router_setups(subscriber_id,vendor,profile_key,model,hardware_revision,encrypted_payload,restore_status,created_by) VALUES(?,?,?,?,?,?,?,?)');
        if (!$stmt) throw new RuntimeException('تعذر حفظ إعداد الراوتر.');
        $stmt->bind_param('isssssss', $subscriberId, $vendor, $key, $model, $revision, $encrypted, $status, $actor);
        if (!$stmt->execute()) throw new RuntimeException('تعذر حفظ إعداد الراوتر.');
        $id = (int)$stmt->insert_id;
        $stmt->close();
        return $id;
    }
}
