<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Provider;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Api\SeamlesWsController; // Sesuaikan namespace controller API Anda

class SyncGameLists extends Command
{
    // Nama perintah yang akan dipanggil di terminal
    protected $signature = 'games:sync-all';
    protected $description = 'Sinkronisasi otomatis semua game dari API berdasarkan provider yang aktif';

    public function handle()
    {
        $this->info('Memulai sinkronisasi game...');
        $api = new SeamlesWsController();
        $providers = Provider::where('status', 1)->get();

        if ($providers->isEmpty()) {
            $this->error('Tidak ada provider aktif yang ditemukan.');
            return;
        }

        $now = Carbon::now();

        foreach ($providers as $provider) {
            $provider_code = strtoupper($provider->provider_code);
            $this->line("Sinkronisasi provider: {$provider_code}...");

            try {
                $getGame = $api->getGamelist($provider_code);
                $result = json_decode($getGame, true);

                if (!isset($result['status']) || $result['status'] != 1) {
                    $this->error("Gagal sync {$provider_code}: API error.");
                    continue;
                }

                $games = $result['games'] ?? [];
                
                foreach ($games as $game) {
                    DB::table('game_lists')->updateOrInsert(
                        ['game_code' => $game['game_code'], 'provider' => ucfirst($provider_code)],
                        [
                            'provider'      => ucfirst($provider_code),
                            'provider_code' => $provider_code,
                            'game_name'     => $game['game_name'] ?? '',
                            'game_code'     => $game['game_code'] ?? '',
                            'game_id'       => $game['game_code'] ?? '',
                            'game_image'    => $game['banner'] ?? '',
                            'product_code'  => 'nxs',
                            'game_type'     => $game['type'] ?? 'slot',
                            'status'        => intval($game['status'] ?? 1),
                            'sequence'      => 1,
                            'created_at'    => $now,
                            'updated_at'    => $now,
                        ]
                    );
                }
                $this->info("Sukses sync {$provider_code}: " . count($games) . " games.");

            } catch (\Exception $e) {
                $this->error("Error pada {$provider_code}: " . $e->getMessage());
            }
        }
        $this->info('Semua proses sinkronisasi selesai!');
    }
}