<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Artisan;

class RollinganSettingController extends Controller
{
    // 1. Tampilkan Halaman Setting
    public function index()
    {
        $settings = DB::table('rollingan_settings')->get();
        return view('backend.rollingan.index', compact('settings'));
    }

    // 2. Simpan atau Update Settingan
    public function store(Request $request)
    {
        // Validasi Anti-Error
        $request->validate([
            'game_type'    => 'required|string',
            'min_turnover' => 'required|numeric|min:0',
            'persentase'   => 'required|numeric|min:0|max:100',
        ]);

        // Gunakan updateOrInsert: Jika 'slot' sudah ada, maka update nilainya. Jika belum, buat baru.
        DB::table('rollingan_settings')->updateOrInsert(
            ['game_type' => strtolower($request->game_type)],
            [
                'min_turnover' => $request->min_turnover,
                'persentase'   => $request->persentase,
                'updated_at'   => now()
            ]
        );

        return redirect()->back()->with('success', 'Pengaturan Rollingan berhasil disimpan!');
    }

    // 3. Hapus Settingan
    public function destroy($id)
    {
        DB::table('rollingan_settings')->where('id', $id)->delete();
        return redirect()->back()->with('success', 'Pengaturan berhasil dihapus!');
    }
    
    public function manualSync()
    {
        try {
            // Memanggil command terminal php artisan api:sync-turnover dari background
            Artisan::call('api:sync-turnover');
            
            return response()->json([
                'success' => true, 
                'message' => 'Penarikan data dari API berhasil dieksekusi!'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false, 
                'message' => 'Gagal: ' . $e->getMessage()
            ]);
        }
    }

    // 5. Eksekusi Bagi Bonus Manual
    public function manualDistribute()
    {
        try {
            // Memanggil command terminal php artisan bonus:rollingan dari background
            Artisan::call('bonus:rollingan');
            
            return response()->json([
                'success' => true, 
                'message' => 'Bonus Rollingan berhasil dihitung dan dibagikan ke player!'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false, 
                'message' => 'Gagal: ' . $e->getMessage()
            ]);
        }
    }
    
    public function turnover(Request $request)
    {
        if ($request->ajax()) {
            $query = DB::table('turnover_logs')
                ->join('users', 'turnover_logs.user_id', '=', 'users.id')
                ->select(['turnover_logs.*', 'users.username']);

            return DataTables::of($query)
                ->addIndexColumn() // Membuat penomoran otomatis (DT_RowIndex)
                ->editColumn('bet_time', function($row) {
                    return \Carbon\Carbon::parse($row->bet_time)->format('d M Y H:i:s');
                })
                ->editColumn('username', function($row) {
                    return '<span class="fw-bold text-primary">' . strtoupper($row->username) . '</span>';
                })
                ->editColumn('game_type', function($row) {
                    return '<span class="badge bg-info text-uppercase">' . $row->game_type . '</span>';
                })
                ->editColumn('valid_bet_amount', function($row) {
                    return '<span class="text-success fw-bold">IDR ' . number_format($row->valid_bet_amount, 0, ',', '.') . '</span>';
                })
                ->editColumn('is_calculated', function($row) {
                    if($row->is_calculated == 1) {
                        return '<span class="badge bg-success"><i class="fas fa-check"></i> Sudah</span>';
                    } else {
                        return '<span class="badge bg-warning text-dark"><i class="fas fa-clock"></i> Belum</span>';
                    }
                })
                // Memberitahu DataTables bahwa kolom ini berisi HTML, bukan teks biasa
                ->rawColumns(['username', 'game_type', 'valid_bet_amount', 'is_calculated']) 
                ->make(true);
        }

        return view('backend.rollingan.turnover');
    }

    // 2. Laporan Bukti Pembagian Bonus
    public function history(Request $request)
    {
        if ($request->ajax()) {
            $query = DB::table('bonus_histories')
                ->join('users', 'bonus_histories.user_id', '=', 'users.id')
                ->select(['bonus_histories.*', 'users.username']);

            return DataTables::of($query)
                ->addIndexColumn()
                ->editColumn('created_at', function($row) {
                    return \Carbon\Carbon::parse($row->created_at)->format('d M Y H:i:s');
                })
                ->editColumn('username', function($row) {
                    return '<span class="fw-bold text-primary">' . strtoupper($row->username) . '</span>';
                })
                ->editColumn('bonus_type', function($row) {
                    return '<span class="badge bg-secondary">' . $row->bonus_type . '</span>';
                })
                ->editColumn('total_turnover', function($row) {
                    return 'IDR ' . number_format($row->total_turnover, 0, ',', '.');
                })
                ->editColumn('bonus_amount', function($row) {
                    return '<span class="fw-bold text-success">+ IDR ' . number_format($row->bonus_amount, 0, ',', '.') . '</span>';
                })
                ->rawColumns(['username', 'bonus_type', 'bonus_amount'])
                ->make(true);
        }

        return view('backend.rollingan.history');
    }
}