<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\VipResellerService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class SyncVipResellerPrices extends Command
{
    protected $signature = 'vipreseller:sync {--force : Force sync even if recently synced}';
    protected $description = 'Sync products with API notes as description (SMART UPDATE - Preserve category & image)';

    private $vipreseller;
    private $stats = ['created' => 0, 'updated' => 0, 'skipped' => 0];

    public function __construct(VipResellerService $vipreseller)
    {
        parent::__construct();
        $this->vipreseller = $vipreseller;
    }

    public function handle()
    {
        $this->info('🚀 Starting Game Sync & API Note Sync...');

        $priceList = $this->vipreseller->fetchGameProducts();
        if (empty($priceList)) {
            $this->error('❌ Failed to fetch products from VIP Reseller');
            return 1;
        }

        $this->info('📦 Found ' . count($priceList) . ' products from API');

        // --- STEP 1: CREATE CATEGORIES (Only new ones, don't update existing) ---
        $this->info('📂 Syncing categories...');
        $categoryCount = 0;
        
        foreach ($priceList as $item) {
            $gameName = $item['game'] ?? null;
            if (!$gameName || $this->isRegionLuar($gameName)) continue;

            $brandCode = $this->normalizeGameName($gameName);
            $slug = Str::slug($gameName);
            
            // Sample note for category description
            $sampleNote = $item['note'] ?? 'Top up ' . $gameName . ' otomatis 24 jam instan.';

            // Check if has available products
            $hasProducts = collect($priceList)->contains(fn($p) => 
                $this->normalizeGameName($p['game'] ?? '') === $brandCode && 
                ($p['status'] ?? '') === 'available'
            );

            if (!$hasProducts) continue;

            // ============================================
            // ONLY CREATE NEW - Don't update existing
            // ============================================
            $existingCategory = DB::table('categories')->where('slug', $slug)->first();
            
            if (!$existingCategory) {
                DB::table('categories')->insert([
                    'name'          => $gameName,
                    'slug'          => $slug,
                    'brand_code'    => $brandCode,
                    'category_type' => 'game',
                    'input_type'    => $this->detectInputType($gameName),
                    'description'   => $sampleNote,
                    'api_filter'    => $this->generateAutoFilter($gameName),
                    'is_active'     => true,
                    'created_at'    => now(),
                    'updated_at'    => now(),
                ]);
                
                $this->info("  ✅ Created category: {$gameName}");
                $categoryCount++;
            }
        }
        
        $this->info("📂 Category sync complete: {$categoryCount} new categories");

        // --- STEP 2: SYNC PRODUCTS (Smart Update) ---
        $this->info('🎮 Syncing products...');
        $categories = DB::table('categories')->where('is_active', true)->get();
        
        foreach ($categories as $category) {
            $productCount = $this->syncCategoryProducts($category, $priceList);
            if ($productCount > 0) {
                $this->comment("  ✅ {$category->name}: {$productCount} products synced");
            }
        }

        // --- STEP 3: DELETE EMPTY CATEGORIES ---
        $this->info('🧹 Cleaning up empty categories...');
        $emptyCategories = DB::table('categories')
            ->leftJoin('products', 'categories.id', '=', 'products.category_id')
            ->select('categories.id', 'categories.name', DB::raw('count(products.id) as product_count'))
            ->groupBy('categories.id', 'categories.name')
            ->having('product_count', '=', 0)
            ->get();

        foreach ($emptyCategories as $cat) {
            DB::table('categories')->where('id', $cat->id)->delete();
            $this->warn("  🗑️ Deleted empty category: {$cat->name}");
        }

        $this->newLine();
        $this->info("✅ Sync Complete!");
        $this->info("   Created: {$this->stats['created']} products");
        $this->info("   Updated: {$this->stats['updated']} products");
        $this->info("   Skipped: {$this->stats['skipped']} products");
        
        return 0;
    }

    private function syncCategoryProducts($category, $priceList)
    {
        $syncCount = 0;
        
        $filteredProducts = array_filter($priceList, function($item) use ($category) {
            $itemGame = $this->normalizeGameName($item['game'] ?? '');
            return $itemGame === $category->brand_code;
        });

        foreach ($filteredProducts as $product) {
            $sku = $product['code'] ?? null;
            if (!$sku) continue;
            
            // Skip unavailable products
            if (($product['status'] ?? '') !== 'available') {
                $this->stats['skipped']++;
                continue;
            }

            $basePrice = $product['price']['basic'] ?? 0;
            if ($basePrice <= 0) {
                $this->stats['skipped']++;
                continue;
            }

            // API note for description
            $apiNote = $product['note'] ?? 'Proses otomatis 24 jam.';

            // Calculate selling price with 10% markup
            $sellingPrice = round($basePrice * 1.10);

            $existing = DB::table('products')->where('sku', $sku)->first();
            
            if ($existing) {
                // ====================================
                // UPDATE MODE - Smart Update!
                // Only update: name, price, stock, status
                // PRESERVE: category_id, image, custom description
                // ====================================
                $updateData = [
                    'name' => $product['name'] ?? 'Unknown',
                    'base_price' => $basePrice,
                    'stock' => 9999,
                    'unlimited_stock' => 1,
                    'seller_product_status' => 1,
                    'updated_at' => now(),
                ];
                
                // Update selling_price ONLY if not customized (no markup)
                if ($existing->selling_price == $existing->base_price) {
                    $updateData['selling_price'] = $sellingPrice;
                }
                
                // Update description ONLY if still default
                if (empty($existing->description) || $existing->description === 'Proses otomatis 24 jam.') {
                    $updateData['description'] = $apiNote;
                }
                
                DB::table('products')
                    ->where('id', $existing->id)
                    ->update($updateData);
                
                $this->stats['updated']++;
            } else {
                // ====================================
                // INSERT MODE - New Product
                // ====================================
                DB::table('products')->insert([
                    'category_id' => $category->id,
                    'name' => $product['name'] ?? 'Unknown',
                    'sku' => $sku,
                    'api_code' => $sku,
                    'base_price' => $basePrice,
                    'selling_price' => $sellingPrice,
                    'description' => $apiNote,
                    'stock' => 9999,
                    'unlimited_stock' => 1,
                    'seller_product_status' => 1,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
                
                $this->stats['created']++;
            }
            
            $syncCount++;
        }
        
        return $syncCount;
    }

    /**
     * Auto-detect input type based on game name
     */
    private function detectInputType($gameName)
    {
        $n = strtoupper($gameName);
        
        // Games with Zone ID
        if (Str::contains($n, ['MOBILE LEGENDS', 'GENSHIN', 'HONKAI', 'HOK', 'ARENA OF VALOR', 'LORDS MOBILE'])) {
            return 'user-id-zone';
        }
        
        // Vouchers
        if (Str::contains($n, ['VOUCHER', 'WALLET', 'CODE', 'STEAM WALLET', 'RAZER GOLD', 'SHELL', 'GARENA SHELL'])) {
            return 'voucher';
        }
        
        // Default: User ID only
        return 'user-id';
    }

    /**
     * Check if game is from foreign region
     */
/**
 * Check if game is from foreign region OR non-gaming
 */
    private function isRegionLuar($name)
    {
        $n = strtoupper($name);
        
        // Regional filters
        $badRegions = [
            'PHILIPPINES', 'PHILLIPINES', 'BRAZIL', 'VIETNAM', 'SINGAPORE', 
            'MALAYSIA', 'RUSSIA', 'THAILAND', 'TURKEY', 'EUROPE', 'USA', 'GLOBAL',
            'SIA', 'SOUTH ASIA', 'NORTH AMERICA', 'LATIN', 'MIDDLE EAST'
        ];
        
        // ⭐ NON-GAMING SERVICES (Skip these)
        $nonGaming = [
            // Productivity & AI
            'CHATGPT', 'PERPLEXITY', 'GEMINI', 'CLAUDE',
            'CANVA', 'FIGMA', 'ADOBE', 'GRAMMARLY', 'NOTION',
            
            // Entertainment (non-gaming)
            'YOUTUBE PREMIUM', 'SPOTIFY', 'APPLE MUSIC',
            'NETFLIX', 'DISNEY', 'PRIME VIDEO', 'HBO',
            'BSTATION', 'WETV', 'IQIYI', 'VIU',
            
            // Video Editing (unless for gaming content)
            'CAPCUT', 'KINEMASTER', 'ALIGHT MOTION',
            
            // VPN & Utilities
            'WARP', 'CLOUDFLARE', 'VPN',
            
            // PPOB
            'PULSA', 'TOKEN LISTRIK', 'PLN',
            'DANA', 'OVO', 'GOPAY', 'SHOPEEPAY',
        ];
        
        // Check all filters
        foreach ($badRegions as $region) {
            if (str_contains($n, $region)) return true;
        }
        
        foreach ($nonGaming as $item) {
            if (str_contains($n, $item)) return true;
        }
        
        return false;
    }

    /**
     * Generate API filter for nickname checking
     */
    private function generateAutoFilter($name)
    {
        $n = strtoupper($name);
        $target = 'default';
        
        // Check if game needs ID + Server (Zone)
        if (Str::contains($n, ['ZONE', 'SERVER', 'MOBILE LEGENDS', 'GENSHIN', 'HONKAI', 'HOK', 'ARENA OF VALOR', 'magic-chess-go-go'])) {
            $target = 'id-zone';
        }

        $slug = Str::slug($name);
        $checkCode = $this->mapGameCode($slug);

        return json_encode([
            'target_type' => $target, 
            'id_label'    => 'User ID', 
            'check_code'  => $checkCode
        ]);
    }

    /**
     * Map game slug to API game code for nickname validation
     */
    private function mapGameCode($game)
    {
        $mapping = [
            'mobile-legends' => 'mobile-legends',
            'mobile-legend'  => 'mobile-legends',
            'mobilelegends'  => 'mobile-legends',
            'ml'             => 'mobile-legends',
            'mlbb'           => 'mobile-legends',
            'free-fire'      => 'free-fire',
            'ff'             => 'free-fire',
            'pubg-mobile'    => 'pubgmobile',
            'pubg'           => 'pubgmobile',
            'genshin-impact' => 'genshin-impact',
            'genshin'        => 'genshin-impact',
            'valorant'       => 'valorant',
            'arena-of-valor' => 'arena-of-valor',
            'aov'            => 'arena-of-valor',
        ];
        
        $cleaned = strtolower(trim($game));

        foreach ($mapping as $key => $validCode) {
            if (str_contains($cleaned, $key)) {
                return $validCode;
            }
        }
        
        return null;
    }

    /**
     * Normalize game name to brand code
     */
    private function normalizeGameName($name)
    {
        return strtoupper(preg_replace('/[^A-Z0-9]/', '', trim($name)));
    }
    private function isNonGamingService($name)
    {
    $n = strtoupper($name);
    
    // ⭐ NON-GAMING AI & PRODUCTIVITY
    $nonGaming = [
        'CHATGPT', 'PERPLEXITY', 'GEMINI', 'CLAUDE',  // AI
        'CANVA', 'FIGMA', 'ADOBE',  // Design
        'GRAMMARLY', 'NOTION',  // Productivity
        'YOUTUBE PREMIUM', 'SPOTIFY', 'APPLE MUSIC',  // Entertainment (non-gaming)
        'NETFLIX', 'DISNEY', 'PRIME VIDEO', 'HBO',  // Streaming
        'BSTATION', 'WETV', 'IQIYI', 'VIU', 'likee', 'vidio-premier','%video%premier%','%vidio%premier%',  // Anime/Asian drama
        '%likee%','%like%video%',
    ];
    
    // ⭐ EXCEPTION: Keep if gaming-related
    $gamingExceptions = [
        'DISCORD NITRO',  // Gaming communication
        'NVIDIA', 'GEFORCE',  // Gaming hardware
        'TWITCH',  // Gaming streams
    ];
    
    // Check exceptions first
    foreach ($gamingExceptions as $exception) {
        if (str_contains($n, $exception)) {
            return false; // Keep it!
        }
    }
    
    // Check non-gaming
    foreach ($nonGaming as $item) {
        if (str_contains($n, $item)) {
            return true; // Remove it!
        }
    }
    
    return false;
}
}