<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use Carbon\Carbon;
use App\Http\Controllers\Api\SeamlesWsController;

class DistributeRollingan extends Command
{
    // Cara memanggilnya di terminal nanti: php artisan bonus:rollingan
    protected $signature = 'bonus:rollingan';
    protected $description = 'Membagikan bonus rollingan otomatis ke semua member (Standar Enterprise)';

    public function handle()
    {
        $this->info('Memulai perhitungan bonus rollingan...');

        // 1. Ambil settingan persentase dari database
        $settings = DB::table('rollingan_settings')->get()->keyBy('game_type');
        
        if ($settings->isEmpty()) {
            $this->error('Settingan rollingan kosong! Harap isi tabel rollingan_settings.');
            return;
        }

        // Tentukan batas waktu pemotongan data (Mencegah data baru masuk saat proses berjalan)
        $cutoffTime = Carbon::now();

        // 2. AGREGASI SUPER CEPAT (Menjumlahkan TO jutaan baris langsung di level SQL)
        $turnoverData = DB::table('turnover_logs')
            ->select('user_id', 'game_type', DB::raw('SUM(valid_bet_amount) as total_to'))
            ->where('is_calculated', 0)
            ->where('bet_time', '<=', $cutoffTime)
            ->groupBy('user_id', 'game_type')
            ->get();

        if ($turnoverData->isEmpty()) {
            $this->info('Tidak ada turnover baru yang perlu dihitung.');
            return;
        }

        $totalDibagikan = 0;

        // 3. MULAI DATABASE TRANSACTION (Keamanan Finansial)
        DB::beginTransaction();

        try {
            foreach ($turnoverData as $data) {
                // Cek apakah game_type ini ada di settingan (misal: slot)
                if (!$settings->has($data->game_type)) continue;

                $setting = $settings[$data->game_type];

                // Cek Syarat Minimal TO
                if ($data->total_to >= $setting->min_turnover) {
                    
                    // Hitung Bonus: (Total TO * Persentase) / 100
                    $bonus = ($data->total_to * $setting->persentase) / 100;
                    
                    $user = User::where('id', $data->user_id)->first();
                    //$end = new SeamlesWsController();
                    //$result = json_decode($end->deposit($user->extplayer, (int)$bonus));
            
                    // Validasi response provider (mencegah error "Trying to get property of non-object")
                    //if (isset($result->status) && $result->status == 1) {
                        // A. Tambah saldo user (Gunakan increment agar menghindari race condition)
                        User::where('id', $data->user_id)->increment('balance', $bonus);
                        // B. Catat ke history bonus
                        DB::table('bonus_histories')->insert([
                            'user_id' => $data->user_id,
                            'bonus_type' => 'Rollingan ' . ucfirst($data->game_type),
                            'total_turnover' => $data->total_to,
                            'bonus_amount' => $bonus,
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]);
                        
                        $totalDibagikan += $bonus;
                    //} else {
                    //    $this->info("Pastikan Saldo API Cukup");
                    //}

                }
            }

            // 4. KUNCI DATA (Tandai TO yang sudah dihitung menjadi is_calculated = 1)
            // Hanya update data sebelum $cutoffTime agar taruhan yang baru masuk sepersekian detik lalu tidak ikut ke-reset!
            DB::table('turnover_logs')
                ->where('is_calculated', 0)
                ->where('bet_time', '<=', $cutoffTime)
                ->update(['is_calculated' => 1]);

            // 5. SIMPAN PERMANEN
            DB::commit();

            $this->info("Sukses! Total bonus rollingan yang dibagikan: IDR " . number_format($totalDibagikan, 0, ',', '.'));

        } catch (\Exception $e) {
            // JIKA TERJADI ERROR (Misal server mati / DB overload), BATALKAN SEMUA PERUBAHAN SALDO!
            DB::rollBack();
            $this->error('Terjadi kesalahan fatal: ' . $e->getMessage());
            \Log::error('Rollingan Error: ' . $e->getMessage());
        }
    }
}