<?php

namespace App\Http\Controllers;

use App\Http\Api\fiver;
use App\Models\Transaksi;
use App\Models\User;
use App\Models\BankAccount;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

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

    /* ===============================
     * HALAMAN WITHDRAW
     * =============================== */
    public function index()
    {
        Log::info('WITHDRAW PAGE OPEN', [
            'user_id'   => Auth::id(),
            'extplayer' => Auth::user()->name
        ]);

        $rekening = BankAccount::where('user_id', Auth::id())->get();

        // ambil saldo LANGSUNG dari API (display only)
        $fiver = new fiver();
        $balance = $fiver->userbalance(Auth::user()->name);

        Log::info('FIVER USER BALANCE', [
            'response' => $balance
        ]);

        $saldos = $balance['user']['balance'] ?? 0;

        return view('withdraw', compact('rekening', 'saldos'));
    }

    /* ===============================
     * SUBMIT WITHDRAW (USER)
     * =============================== */
    public function store(Request $request)
{
    Log::info('WITHDRAW SUBMIT HIT', [
        'user_id' => Auth::id(),
        'request' => $request->all()
    ]);

    // 1️⃣ cek withdraw pending
    $pending = Transaksi::where('user_id', Auth::id())
        ->where('type', 2)
        ->where('status', 1)
        ->exists();

    if ($pending) {
        return back()->with('error', 'Masih ada withdraw yang belum diproses');
    }

    // 2️⃣ validasi
    $request->validate([
        'amount' => 'required',
        'wd_accno' => 'required|string'
    ]);

    $amount = (int) str_replace(',', '', $request->amount);

    if ($amount <= 0) {
        return back()->with('error', 'Nominal tidak valid');
    }

    // ✅ INI YANG KEMARIN HILANG
    $fiver = new fiver();

    // 3️⃣ PANGGIL API WITHDRAW (SEPERTI CONTROLLER LAMA)
    $res = $fiver->withdraw(Auth::user()->extplayer, $amount);

    Log::info('FIVER WITHDRAW RESPONSE', [
        'user' => Auth::user()->extplayer,
        'amount' => $amount,
        'response' => $res
    ]);

    if (!isset($res['status']) || !in_array($res['status'], [1, 'success'], true)) {
        Log::error('FIVER WITHDRAW FAILED', [
            'user' => Auth::user()->extplayer,
            'amount' => $amount,
            'response' => $res
        ]);

        return back()->with('error', 'Withdraw gagal, saldo tidak mencukupi');
    }

    // simpan transaksi
$trx = new Transaksi();
$trx->type = 2; // withdraw
$trx->status = 1; // pending
$trx->user_id = Auth::id();
$trx->nominal = $amount;
$trx->trans_id = Transaksi::generateTransID();
$trx->wd_accname = $request->wd_accname;
$trx->wd_accno = $request->wd_accno;
$trx->destination_account = $request->destination_account;
$trx->metode_withdraw = $request->metode_withdraw;
$trx->save();

    Log::info('WITHDRAW TRANSACTION CREATED', [
        'trx_id' => $trx->id,
        'amount' => $amount
    ]);

    return back()->with('success', 'Withdraw berhasil diajukan');
}
}