<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Transaction;
use App\Models\Bonus;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;
use App\Http\Controllers\Api\SeamlesWsController;
use Exception;

class WithdrawController extends Controller
{

    public function index(Request $request)
    {
        $transaction = Transaction::where('transaksi','Withdraw')->where('status','Pending')->orderBy('created_at','desc')->get();
        return view('backend.withdraw.pending', compact('transaction'));
    }

    public function list(Request $request)
    {
        $transaction = Transaction::where('transaksi','Withdraw')->orderBy('created_at','desc');
        if ($request->ajax()) {
            return DataTables::of($transaction)
                ->addIndexColumn()
                ->addColumn('status', function ($row) {
                    if ($row->status == 'Pending') {
                        $statusbtn = '<span class="badge bg-label-warning rounded-pill">Pending</span>';
                    } elseif ($row->status == 'Ditolak') {
                        $statusbtn = '<span class="badge bg-label-danger rounded-pill">Rejected</span>';
                    } else {
                        $statusbtn = '<span class="badge bg-label-success rounded-pill">Active</span>';
                    }
                    return $statusbtn;
                })
                ->addColumn('bank_user', function ($row) {
                    if (auth()->guard('admin')->user()->level == 'master') {
                        $admin_btn = $row->dari_bank;
                    } else {
                        $admin_btn = censor($row->dari_bank,4);
                    }
                    return $admin_btn;
                })
                ->addColumn('created_at', function ($row) {
                    $cbtrn = $row->created_at;
                    return $cbtrn;
                })
                ->addColumn('total', function ($row) {
                    $amounts = 'Rp.' . number_format($row->total);
                    return $amounts;
                })
                ->rawColumns(['status','created_at', 'total','bank_user'])
                ->make(true);
        }

        return view('backend.withdraw.list');
    }

    public function approve($id, Request $request)
    {
        $transaction = Transaction::find($id);
        $transaction->transaction_by = auth()->guard('admin')->user()->username;
        $transaction->status = 'Sukses';
        $transaction->save();
        
        // Eksekusi notifikasi di luar transaksi DB agar proses load lebih cepat
        sendNotifPayout($transaction->trx_id,$transaction->total,$transaction->username,$transaction->dari_bank,$transaction->status,'Withdraw');

        return back()->with('success', 'Withdraw Sucesssfully approved');

    }

    public function reject($id, Request $request)
    {
        // 1. Fail-Safe Fetching & Validasi Status (Mencegah double-reject)
        $transaction = Transaction::findOrFail($id);
    
        if ($transaction->status !== 'Pending') {
            return back()->with('error', 'Transaksi ini sudah diproses sebelumnya.');
        }

        $user = User::findOrFail($transaction->id_user);

        // 2. Call API Provider untuk mengembalikan saldo (Refund Withdraw)
        $end = new SeamlesWsController();
        $result = json_decode($end->deposit($user->extplayer, (int)$transaction->total, $transaction->trx_id), true);

        // 3. Validasi keberhasilan API Provider
        if (isset($result['status']) && $result['status'] == 1) {
            try {
                // 4. Gunakan DB Transaction agar update data sinkron
                DB::transaction(function () use ($transaction, $user) {
                
                    $transaction->update([
                        'status' => 'Ditolak',
                        'transaction_by' => auth()->guard('admin')->user()->username
                    ]);

                    // Update saldo lokal menggunakan data dari provider, bukan penjumlahan manual
                    $user->update(['balance' => $user->balance + $transaction->total]);
                });

                return back()->with('success', 'Withdraw Successfully rejected');

            } catch (Exception $e) {
                // Jika database gagal menyimpan, proses dibatalkan (Rollback)
                return back()->with('error', 'Gagal menyimpan ke database: ' . $e->getMessage());
            }
        }

        // 5. Fallback pesan error jika gagal dari sisi API
        return back()->with('error', $result['msg'] ?? 'Terjadi kesalahan pada respon API Provider.');
    }
}
