<?php

namespace Database\Seeders;

use App\Models\Banner;
use App\Models\Category;
use App\Models\Country;
use App\Models\Coupon;
use App\Models\Currency;
use App\Models\Game;
use App\Models\ManualPaymentGateway;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\ProductVariant;
use App\Models\StockCode;
use App\Models\SupportTicket;
use App\Models\User;
use App\Models\Voucher;
use App\Services\StockCodeInventoryService;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DatabaseSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        $egp = Currency::create([
            'code' => 'EGP',
            'name_ar' => 'جنيه مصري',
            'name_en' => 'Egyptian Pound',
            'symbol' => 'ج.م',
            'symbol_position' => 'after',
            'exchange_rate' => 1,
            'rate_updated_at' => now(),
            'is_base' => true,
        ]);

        foreach ([
            ['SAR', 'ريال سعودي', 'Saudi Riyal', 'ر.س', 12.8],
            ['AED', 'درهم إماراتي', 'UAE Dirham', 'د.إ', 13.1],
            ['USD', 'دولار أمريكي', 'US Dollar', '$', 48.2],
            ['EUR', 'يورو', 'Euro', '€', 52.1],
        ] as [$code, $ar, $en, $symbol, $rate]) {
            Currency::create([
                'code' => $code,
                'name_ar' => $ar,
                'name_en' => $en,
                'symbol' => $symbol,
                'exchange_rate' => $rate,
                'rate_updated_at' => now(),
            ]);
        }

        $egypt = Country::create([
            'name_ar' => 'مصر',
            'name_en' => 'Egypt',
            'iso_code' => 'EG',
            'dial_code' => '+20',
            'flag_code' => 'EG',
            'default_locale' => 'ar',
            'default_currency_code' => 'EGP',
        ]);

        Country::create([
            'name_ar' => 'السعودية',
            'name_en' => 'Saudi Arabia',
            'iso_code' => 'SA',
            'dial_code' => '+966',
            'flag_code' => 'SA',
            'default_locale' => 'ar',
            'default_currency_code' => 'SAR',
        ]);

        $player = User::factory()->create([
            'name' => 'Raseed Player',
            'display_name' => 'Player One',
            'email' => 'player@raseednow.test',
            'referral_code' => 'RNPLAYER',
            'country_id' => $egypt->id,
            'currency_id' => $egp->id,
        ]);

        User::factory()->create([
            'name' => 'Raseed Admin',
            'display_name' => 'Admin',
            'email' => 'admin@raseednow.test',
            'referral_code' => 'RNADMIN',
            'password' => Hash::make('admin-password-change-me'),
            'role' => 'admin',
            'country_id' => $egypt->id,
            'currency_id' => $egp->id,
        ]);

        $wallet = $player->wallet()->create([
            'currency_code' => 'EGP',
            'balance_minor' => 250000,
        ]);

        $wallet->entries()->create([
            'uuid' => (string) Str::uuid(),
            'type' => 'seed_credit',
            'amount_minor' => 250000,
            'balance_after_minor' => 250000,
            'description' => 'Local seed credit for QA only.',
        ]);

        Coupon::create([
            'code' => 'WELCOME10',
            'name_ar' => 'خصم ترحيبي 10%',
            'name_en' => 'Welcome 10% off',
            'type' => 'percent',
            'percent_off' => 10,
            'max_discount_minor' => 10000,
            'min_subtotal_minor' => 1000,
            'usage_limit' => 100,
            'once_per_customer' => true,
            'is_active' => true,
        ]);

        Coupon::create([
            'code' => 'SAVE50',
            'name_ar' => 'خصم 50 جنيه',
            'name_en' => 'Save 50 EGP',
            'type' => 'fixed',
            'value_minor' => 5000,
            'min_subtotal_minor' => 20000,
            'usage_limit' => 50,
            'once_per_customer' => false,
            'is_active' => true,
        ]);

        Voucher::create([
            'code' => 'QA100',
            'name_ar' => 'شحن تجريبي 100 جنيه',
            'name_en' => 'QA 100 EGP top-up',
            'currency_code' => 'EGP',
            'amount_minor' => 10000,
            'usage_limit' => 25,
            'once_per_user' => true,
            'is_active' => true,
        ]);

        ManualPaymentGateway::create([
            'name_ar' => 'فودافون كاش',
            'name_en' => 'Vodafone Cash',
            'account_label_ar' => 'رقم المحفظة',
            'account_label_en' => 'Wallet number',
            'account_number' => '01000000000',
            'instructions_ar' => 'حوّل المبلغ على الرقم، ثم ارفع صورة التحويل واكتب رقم هاتفك.',
            'instructions_en' => 'Transfer the amount, upload the receipt screenshot, and enter your phone number.',
            'icon_path' => 'images/payments/vodafone-cash.png',
            'is_active' => true,
            'sort_order' => 1,
        ]);

        $categories = collect([
            ['games', 'شحن الألعاب', 'Game Top-up', 'zap', '#1769d1'],
            ['gift-cards', 'بطاقات الألعاب', 'Game Cards', 'gift', '#1769d1'],
            ['subscriptions', 'اشتراكات التطبيقات', 'Subscriptions', 'badge', '#1769d1'],
            ['deals', 'الدفع الإلكتروني', 'E-payment', 'spark', '#1769d1'],
            ['social-media', 'سوشيال ميديا', 'Social Media', 'users', '#1769d1'],
            ['activation-keys', 'مفاتيح التفعيل', 'Activation Keys', 'key', '#1769d1'],
            ['shopping', 'التسوق', 'Shopping', 'bag', '#1769d1'],
            ['telecom', 'بطاقات الإتصالات', 'Telecom Cards', 'phone', '#1769d1'],
        ])->map(fn ($row, $index) => Category::create([
            'slug' => $row[0],
            'name_ar' => $row[1],
            'name_en' => $row[2],
            'icon' => $row[3],
            'color' => $row[4],
            'sort_order' => $index + 1,
            'is_featured' => $index < 3,
        ]));

        $games = collect([
            ['pubg-mobile', 'ببجي', 'PUBG Mobile', 'Tencent', '#1769d1', $categories[0], 'images/kroti/product-109.webp'],
            ['free-fire', 'فري فاير', 'Free Fire', 'Garena', '#1769d1', $categories[0], 'images/kroti/product-108.webp'],
            ['playstation-store', 'بلايستيشن ستور', 'PlayStation Store', 'Sony', '#1769d1', $categories[1], 'images/kroti/product-119.webp'],
            ['xbox-store', 'إكس بوكس', 'Xbox Store', 'Microsoft', '#1769d1', $categories[1], 'images/kroti/product-121.webp'],
            ['steam-wallet', 'بطاقات ستيم', 'Steam Wallet', 'Valve', '#1769d1', $categories[1], 'images/kroti/product-117.webp'],
            ['valorant', 'فالورانت', 'Valorant', 'Riot Games', '#1769d1', $categories[0], 'images/kroti/product-114.webp'],
            ['tiktok-epayment', 'عملات تيكتوك', 'TikTok Coins', 'TikTok', '#1769d1', $categories[3], 'images/kroti/product-126.webp'],
            ['mobile-legends', 'موبايل ليجندز', 'Mobile Legends', 'Moonton', '#1769d1', $categories[0], 'images/kroti/product-113.webp'],
            ['call-of-duty', 'Call Of Duty', 'Call Of Duty', 'Activision', '#1769d1', $categories[0], 'images/kroti/product-111.webp'],
            ['efootball', 'e-Football', 'e-Football', 'Konami', '#1769d1', $categories[0], 'images/kroti/product-110.webp'],
            ['clash-of-clans', 'كلاش اوف كلانس', 'Clash of Clans', 'Supercell', '#1769d1', $categories[0], 'images/kroti/product-112.webp'],
            ['jawaker', 'جواكر', 'Jawaker', 'Jawaker', '#1769d1', $categories[0], 'images/kroti/product-118.webp'],
            ['yalla-ludo', 'بطاقات يلا ليدو', 'Yalla Ludo', 'Yalla Group', '#1769d1', $categories[1], 'images/kroti/product-116.webp'],
            ['roblox', 'بطاقات روبلوكس', 'Roblox Cards', 'Roblox', '#1769d1', $categories[1], 'images/kroti/product-118.webp'],
            ['razer-gold', 'بطاقات ريزر جولد', 'Razer Gold', 'Razer', '#1769d1', $categories[1], 'images/kroti/product-120.webp'],
        ])->map(fn ($row, $index) => Game::create([
            'slug' => $row[0],
            'name_ar' => $row[1],
            'name_en' => $row[2],
            'publisher' => $row[3],
            'cover_color' => $row[4],
            'category_id' => $row[5]->id,
            'image_path' => $row[6],
            'is_featured' => $index < 4,
            'description_ar' => $row[1].' بخيارات متعددة وأسعار واضحة. اختر الباقة المناسبة ثم أكمل الطلب من صفحة الدفع.',
            'required_fields' => [
                ['key' => 'player_id', 'label_ar' => 'Player ID', 'type' => 'text', 'required' => true],
                ['key' => 'server', 'label_ar' => 'السيرفر', 'type' => 'select', 'required' => false],
            ],
            'faq' => [
                ['q' => 'متى يصل الطلب؟', 'a' => 'التنفيذ اليدوي التجريبي يظهر كطلب قيد المعالجة.'],
            ],
        ]));

        $products = [
            [$games[0], 'PUBG-60UC', '60 شدة', '60 UC', 60, 4900, true, true, 'manual'],
            [$games[0], 'PUBG-325UC', '325 شدة', '325 UC', 325, 22900, true, false, 'api'],
            [$games[1], 'FF-110D', '110 جوهرة', '110 Diamonds', 110, 5900, true, true, 'manual'],
            [$games[1], 'FF-572D', '572 جوهرة', '572 Diamonds', 572, 25900, false, false, 'api'],
            [$games[2], 'PSN-10USD', 'بطاقة 10 دولار', '10 USD Gift Card', 10, 54900, true, true, 'stored_code'],
            [$games[3], 'XBOX-15USD', 'بطاقة 15 دولار', '15 USD Gift Card', 15, 78900, false, false, 'stored_code'],
            [$games[4], 'STEAM-20USD', 'ستيم 20 دولار', 'Steam 20 USD', 20, 104900, true, false, 'stored_code'],
            [$games[5], 'VAL-475VP', '475 نقطة فالورانت', '475 Valorant Points', 475, 23900, false, true, 'manual'],
            [$games[6], 'TT-350', '350 عملة', '350 Coins', 350, 43500, true, false, 'manual'],
            [$games[6], 'TT-500', '500 عملة', '500 Coins', 500, 61900, true, false, 'manual'],
            [$games[6], 'TT-700', '700 عملة', '700 Coins', 700, 86300, true, false, 'manual'],
            [$games[6], 'TT-1000', '1000 عملة', '1000 Coins', 1000, 123900, true, false, 'manual'],
            [$games[6], 'TT-1500', '1500 عملة', '1500 Coins', 1500, 185800, false, false, 'manual'],
            [$games[6], 'TT-2000', '2000 عملة', '2000 Coins', 2000, 247800, false, false, 'manual'],
            [$games[6], 'TT-2500', '2500 عملة', '2500 Coins', 2500, 309700, false, false, 'manual'],
            [$games[6], 'TT-4000', '4000 عملة', '4000 Coins', 4000, 495600, false, false, 'manual'],
            [$games[6], 'TT-7000', '7000 عملة', '7000 Coins', 7000, 867300, false, false, 'manual'],
            [$games[6], 'TT-10000', '10,000 عملة', '10,000 Coins', 10000, 1239000, false, false, 'manual'],
            [$games[6], 'TT-20000', '20,000 عملة', '20,000 Coins', 20000, 2450000, false, false, 'manual'],
            [$games[6], 'TT-50000', '50,000 عملة', '50,000 Coins', 50000, 6000000, false, false, 'manual'],
            [$games[7], 'ML-86D', '86 جوهرة', '86 Diamonds', 86, 23900, true, false, 'manual'],
            [$games[8], 'COD-420CP', '420 CP', '420 CP', 420, 29900, true, false, 'manual'],
            [$games[9], 'EFOOTBALL-130', '130 كوينز', '130 Coins', 130, 54900, true, false, 'manual'],
            [$games[10], 'COC-500G', '500 جوهرة', '500 Gems', 500, 104900, true, false, 'manual'],
            [$games[11], 'JAWAKER-1000', '1000 توكن', '1000 Tokens', 1000, 19900, true, false, 'manual'],
            [$games[12], 'YALLA-10USD', 'بطاقة 10 دولار', '10 USD Card', 10, 54900, true, false, 'stored_code'],
            [$games[13], 'ROBLOX-10USD', 'بطاقة 10 دولار', '10 USD Card', 10, 54900, true, false, 'stored_code'],
            [$games[14], 'RAZER-10USD', 'بطاقة 10 دولار', '10 USD Card', 10, 54900, true, false, 'stored_code'],
        ];

        foreach ($products as [$game, $sku, $nameAr, $nameEn, $quantity, $price, $featured, $bestSeller, $method]) {
            $variant = ProductVariant::create([
                'game_id' => $game->id,
                'sku' => $sku,
                'name_ar' => $nameAr,
                'name_en' => $nameEn,
                'quantity' => $quantity,
                'unit_ar' => str_contains($sku, 'USD') ? 'دولار' : 'وحدة',
                'unit_en' => str_contains($sku, 'USD') ? 'USD' : 'Unit',
                'cost_minor' => (int) round($price * 0.82),
                'price_minor' => $price,
                'sale_price_minor' => $bestSeller ? (int) round($price * 0.93) : null,
                'delivery_method' => $method,
                'stock_available' => $method === 'stored_code' ? 5 : 999,
                'cashback_basis_points' => 150,
                'loyalty_points' => (int) floor($price / 10000),
                'is_featured' => $featured,
                'is_best_seller' => $bestSeller,
                'dynamic_fields' => $game->required_fields,
                'instructions_ar' => 'راجع رقم اللاعب قبل تأكيد الطلب. الأسعار محفوظة كلقطة داخل الطلب.',
                'instructions_en' => 'Verify the player ID before checkout. Prices are snapshotted per order.',
            ]);

            if ($method === 'stored_code') {
                foreach (range(1, 5) as $i) {
                    $plainCode = $sku.'-TEST-CODE-'.$i;

                    StockCode::create([
                        'product_variant_id' => $variant->id,
                        'batch_reference' => 'LOCAL-QA',
                        'encrypted_code' => Crypt::encryptString($plainCode),
                        'code_fingerprint' => StockCodeInventoryService::fingerprint($plainCode),
                        'serial_number' => $sku.'-SN-'.$i,
                        'cost_minor' => (int) round($price * 0.76),
                        'status' => 'available',
                    ]);
                }
            }
        }

        Banner::create([
            'title_ar' => 'اشحن ألعابك في خطوات قليلة',
            'title_en' => 'Top up your games in a few steps',
            'subtitle_ar' => 'اختيار سريع، تسعير واضح، وتنفيذ قابل للتتبع من لوحة الإدارة.',
            'subtitle_en' => 'Fast selection, clear pricing, and trackable fulfillment.',
            'cta_label_ar' => 'ابدأ الشحن',
            'cta_label_en' => 'Start top-up',
            'image_path' => 'images/hero/hero-gaming-original.png',
            'tone' => 'emerald',
            'sort_order' => 1,
        ]);

        Banner::create([
            'title_ar' => 'بطاقات رقمية بمخزون محمي',
            'title_en' => 'Protected digital code inventory',
            'subtitle_ar' => 'الأكواد مشفرة ولا يتم بيع الكود مرتين.',
            'subtitle_en' => 'Codes are encrypted and reserved safely.',
            'cta_label_ar' => 'استكشف البطاقات',
            'cta_label_en' => 'Browse cards',
            'image_path' => 'images/hero/hero-digital-original.png',
            'tone' => 'indigo',
            'sort_order' => 2,
        ]);

        $order = Order::create([
            'uuid' => (string) Str::uuid(),
            'order_number' => 'RN-'.now()->format('ymd').'-1001',
            'user_id' => $player->id,
            'customer_name' => $player->name,
            'customer_email' => $player->email,
            'subtotal_minor' => 4900,
            'total_minor' => 4900,
            'payment_method' => 'manual',
            'payment_status' => 'pending',
            'fulfillment_status' => 'pending',
            'customer_fields' => ['player_id' => '123456789'],
        ]);

        OrderItem::create([
            'order_id' => $order->id,
            'product_variant_id' => ProductVariant::where('sku', 'PUBG-60UC')->value('id'),
            'name_snapshot' => '60 شدة',
            'sku_snapshot' => 'PUBG-60UC',
            'unit_price_minor' => 4900,
            'total_minor' => 4900,
            'delivery_method_snapshot' => 'manual',
        ]);

        $order->timelines()->create([
            'actor_id' => null,
            'event' => 'created',
            'title' => 'تم إنشاء الطلب التجريبي',
            'note' => 'Seed data for local QA.',
        ]);

        $ticket = SupportTicket::create([
            'uuid' => (string) Str::uuid(),
            'user_id' => $player->id,
            'ticket_number' => 'TCK-1001',
            'subject' => 'تأكيد طلب شحن',
            'priority' => 'normal',
            'last_message' => 'برجاء متابعة حالة الطلب التجريبي.',
            'last_activity_at' => now(),
        ]);

        $ticket->messages()->create([
            'sender_user_id' => $player->id,
            'sender_type' => 'customer',
            'body' => 'برجاء متابعة حالة الطلب التجريبي.',
        ]);
    }
}
