<?php

namespace App\Http\Controllers;

use App\Models\Transaksi;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
use Carbon\Carbon;

class UserHistoryController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /* ===============================
     * CONFIG API PROVIDER
     * =============================== */
    private $endpoint     = "https://{API_ENDPOINT}";
    private $agent_code   = "testAgent";
    private $agent_token  = "41f5cc794aef2b138c715cf25f767cc1";

    /* ===============================
     * HALAMAN HISTORY USER
     * =============================== */
    public function index(Request $request)
    {
        $user = Auth::user();

        // =============================
        // HISTORY TRANSAKSI LOKAL
        // =============================
        $transaksi = $this->getTransaksi($user->id);
        $summary   = $this->getSummary($user->id);

        // =============================
        // HISTORY GAME PROVIDER
        // =============================
        $start = $request->start ?? Carbon::today()->format('Y-m-d 00:00:00');
        $end   = $request->end   ?? Carbon::today()->format('Y-m-d 23:59:59');

        $gameHistory = $this->getGameHistory($user->extplayer, $start, $end);

        return view('history', [
            'transaksi'      => $transaksi,
            'jumlahBerhasil' => $summary['jumlahBerhasil'],
            'totalDebit'     => $summary['totalDebit'],
            'totalKredit'    => $summary['totalKredit'],
            'gameHistory'    => $gameHistory,
            'start'          => $start,
            'end'            => $end,
        ]);
    }

    /* ===============================
     * AMBIL HISTORY TRANSAKSI DB
     * =============================== */
    private function getTransaksi($userId)
    {
        return Transaksi::with('DataBank')
            ->where('user_id', $userId)
            ->latest()
            ->limit(5)
            ->get();
    }

    /* ===============================
     * SUMMARY DEPOSIT & WITHDRAW
     * =============================== */
    private function getSummary($userId)
    {
        return [
            'jumlahBerhasil' => Transaksi::where('user_id',$userId)->where('status',2)->count(),

            'totalKredit' => Transaksi::where('user_id',$userId)
                ->where('status',2)
                ->where('type',1)
                ->sum('nominal'),

            'totalDebit' => Transaksi::where('user_id',$userId)
                ->where('status',2)
                ->where('type',2)
                ->sum('nominal'),
        ];
    }

    /* ===============================
     * AMBIL HISTORY GAME API
     * =============================== */
    private function getGameHistory($playerCode, $start, $end)
    {
        try {

            $payload = [
                "method" => "get_game_log",
                "agent_code" => $this->agent_code,
                "agent_token" => $this->agent_token,
                "user_code" => $playerCode,
                "game_type" => "slot",
                "start" => $start,
                "end"   => $end,
                "page" => 0,
                "perPage" => 100
            ];

            $response = Http::timeout(30)->post($this->endpoint, $payload);

            if (!$response->ok()) {
                return collect(); // kalau API mati, halaman tetap load
            }

            $result = $response->json();

            if (!$result || $result['status'] != 1 || empty($result['slot'])) {
                return collect();
            }

            return collect($result['slot'])->map(function ($row) {
                return [
                    'time' => Carbon::parse($row['created_at'])->format('d M Y H:i'),
                    'provider' => $row['provider_code'],
                    'game' => $row['game_code'],
                    'bet' => $row['bet_money'],
                    'win' => $row['win_money'],
                    'before' => $row['user_start_balance'],
                    'after' => $row['user_end_balance'],
                    'type' => $row['type']
                ];
            });

        } catch (\Exception $e) {
            // kalau API error / timeout jangan rusak halaman
            return collect();
        }
    }

    /* ===============================
     * METHOD RESOURCE (TIDAK DIPAKAI)
     * =============================== */
    public function create() {}
    public function store($request) {}
    public function show(string $id) {}
    public function edit(string $id) {}
    public function update($request, string $id) {}
    public function destroy(string $id) {}
}