<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Http\Api\fiver;

class FiverSyncGames extends Command
{
    protected $signature = 'fiver:sync-games';
    protected $description = 'Sync ONLY SPADEGAMING & FASTSPIN';

    public function handle()
    {
        // 🔒 HANYA 2 PROVIDER INI
        $providers = [
            'SPADEGAMING',
            'FASTSPIN'
        ];

        $api = new fiver();

        foreach ($providers as $provider) {

            $this->info("⏳ Sync {$provider}...");

            // 🔒 skip kalau sudah pernah sync
            $totalGame = DB::table('fiver_games2')
                ->where('game_provider', $provider)
                ->count();

            if ($totalGame > 0) {
                $this->line("⏭ {$provider} sudah ada ({$totalGame} game), skip");
                continue;
            }

            $response = $api->gameList($provider);

            if (($response['status'] ?? 0) != 1) {
                $this->error("❌ Gagal {$provider}");
                continue;
            }

            foreach ($response['games'] as $game) {

                DB::table('fiver_games2')->updateOrInsert(
                    [
                        'game_provider' => $provider,
                        'game_code'     => $game['game_code'],
                    ],
                    [
                        'game_name'     => is_array($game['game_name'])
                                            ? ($game['game_name']['en'] ?? reset($game['game_name']))
                                            : $game['game_name'],
                        'game_image'    => $game['banner'] ?? null,
                        'game_category' => 'slot',
                        'status'        => $game['status'] ?? 1,
                        'created_at'    => now(),
                        'updated_at'    => now(),
                    ]
                );
            }

            $this->info("✅ {$provider} selesai (".count($response['games'])." game)");
        }

        $this->info('🎉 DONE - hanya SPADEGAMING & FASTSPIN');

        return Command::SUCCESS;
    }
}