<?php  
  
namespace App\Http\Controllers;  
  
use Illuminate\Http\Request;  
use Illuminate\Support\Facades\Log;  
use App\Services\JayapayService;  
use Illuminate\Support\Facades\Auth;  
use App\Models\Transaksi;  
use App\Models\User;  
use App\Models\Saldo;  
use App\Http\Api\fiver;  
use Illuminate\Support\Facades\DB;  
  
class PaymentGatewayController extends Controller  
{  
    protected $jayapay;  
  
    public function __construct(JayapayService $jayapay)  
    {  
        $this->jayapay = $jayapay;  
    }  
  
    /**  
     * ===============================  
     * CREATE PAYMENT QRIS (JAYAPAY)  
     * ===============================  
     */  
    public function createPayment(Request $request)  
    {  
        try {  
            $user = Auth::user();  
  
            // 🔥 BERSIHKAN NOMINAL DULU  
$nominal = preg_replace('/\D/', '', $request->nominal);  
$amount  = (int) $nominal;  
  
// 🔥 VALIDASI SETELAH BERSIH  
if ($amount < 20000) {  
    Log::error('❌ createPayment error', [  
        'msg' => 'Nominal di bawah minimum',  
        'raw' => $request->nominal,  
        'clean' => $amount  
    ]);  
    return back()->withErrors('Minimal deposit 20.000');  
}  
  
            $orderNum = 'TRX' . now()->format('YmdHis') . rand(100, 999);  
  
            $returnUrl = url('/account/deposit?qris=success&orderNum=' . $orderNum);  
  
            $payload = [  
                'orderNum'      => $orderNum,  
                'amount'        => $amount,  
                'productDetail' => 'Deposit QRIS #' . $user->id,  
                'name'          => $user->name,  
                'email'         => $user->email,  
                'phone'         => preg_match('/^08\d{8,11}$/', $user->telp ?? '')  
                    ? $user->telp  
                    : '081234567890',  
                'method'        => 'QRIS',  
                'returnUrl'     => $returnUrl,  
            ];  
  
            Log::info('🧾 Jayapay createOrder', $payload);  
  
            $response = $this->jayapay->createOrder($payload);  
  
            if (empty($response['success'])) {  
                Log::error('❌ Jayapay gagal', $response);  
                return back()->withErrors('Gagal membuat pembayaran');  
            }  
  
            $result = $response['response'] ?? [];  
            $payUrl = $result['payUrl'] ?? $result['url'] ?? null;  
  
            if (!$payUrl) {  
                Log::error('❌ payUrl tidak ditemukan', $result);  
                return back()->withErrors('URL pembayaran tidak tersedia');  
            }  
  
            // SIMPAN TRANSAKSI  
            Transaksi::create([  
                'trans_id'   => 'DEP' . now()->format('YmdHis') . rand(100, 999),  
                'ref'        => $orderNum,  
                'type'       => 1,  
                'status'     => 1, // pending  
                'nominal'    => $amount,  
                'metode_deposit' => 'Bank',
                'destination_account' => 'QRISHOKI',
                'user_id'    => $user->id,  
                'created_at' => now(),  
                'updated_at' => now(),  
            ]);  
  
            return redirect()->away($payUrl);  
  
        } catch (\Throwable $e) {  
            Log::error('💥 createPayment error', [  
                'msg' => $e->getMessage(),  
            ]);  
            return back()->withErrors('Terjadi kesalahan sistem');  
        }  
    }  
  
    /**  
     * ===============================  
     * CALLBACK JAYAPAY  
     * ===============================  
     */  
    public function callback(Request $request)  
{  
    Log::info('🔔 Jayapay Callback Masuk', $request->all());  
  
    DB::beginTransaction();  
  
    try {  
        $orderNum = $request->input('orderNum');  
  
        // 🔥 JAYAPAY CALLBACK STATUS YANG BENAR  
        $status = strtoupper(  
            $request->input('status')  
            ?? $request->input('platRespCode')  
            ?? ''  
        );  
  
        $code = $request->input('code'); // biasanya "00"  
  
        if (!$orderNum) {  
            DB::rollBack();  
            return response('OK', 200);  
        }  
  
        $trx = Transaksi::where('ref', $orderNum)  
            ->where('type', 1)  
            ->lockForUpdate()  
            ->first();  
  
        if (!$trx) {  
            DB::rollBack();  
            Log::warning("⚠️ Transaksi tidak ditemukan: {$orderNum}");  
            return response('OK', 200);  
        }  
  
        // 🔒 ANTI DOUBLE CALLBACK  
        if ((int) $trx->status === 2) {  
            DB::rollBack();  
            return response('OK', 200);  
        }  
  
        // ❌ JIKA BUKAN SUCCESS  
        if ($status !== 'SUCCESS' && $code !== '00') {  
            $trx->update(['status' => 3]);  
            DB::commit();  
            Log::warning('❌ JAYAPAY PAYMENT FAILED', $request->all());  
            return response('OK', 200);  
        }  
  
        $user = User::find($trx->user_id);  
        if (!$user || !$user->extplayer) {  
            DB::rollBack();  
            Log::error('❌ User / extplayer tidak valid', [  
                'user_id' => $trx->user_id,  
            ]);  
            return response('OK', 200);  
        }  
  
        // ===============================  
        // DEPOSIT KE FIVER  
        // ===============================  
        $fiver  = new fiver();  
        $amount = (int) $trx->nominal;  
  
        $depositRes = $fiver->deposit($user->extplayer, $amount);  
  
        Log::info('🎮 FIVER DEPOSIT RESPONSE', [  
            'user'     => $user->extplayer,  
            'amount'   => $amount,  
            'response' => $depositRes,  
        ]);  
  
        if (!isset($depositRes['status']) || (int) $depositRes['status'] !== 1) {  
            DB::rollBack();  
            Log::error('❌ Deposit FIVER gagal', $depositRes);  
            return response('OK', 200);  
        }  
  
        // ===============================  
        // UPDATE TRANSAKSI  
        // ===============================  
        $trx->update([  
            'status'      => 2,  
            'approved_at' => now(),  
            'approved_by' => 0, // system / gateway  
        ]);  
  
        // ===============================  
        // SYNC SALDO DARI FIVER  
        // ===============================  
        $balanceRes = $fiver->userBalance($user->extplayer);  
  
        Log::info('💰 FIVER BALANCE AFTER DEPOSIT', [  
            'user'     => $user->extplayer,  
            'response' => $balanceRes,  
        ]);  
  
        if (isset($balanceRes['user']['balance'])) {  
            Saldo::updateOrCreate(  
                ['user_id' => $user->id],  
                ['saldo' => $balanceRes['user']['balance']]  
            );  
        }  
  
        DB::commit();  
  
        Log::info('✅ Deposit QRIS AUTO SUCCESS', [  
            'order'  => $orderNum,  
            'amount' => $amount,  
        ]);  
  
        return response('OK', 200);  
  
    } catch (\Throwable $e) {  
        DB::rollBack();  
        Log::error('💥 CALLBACK ERROR', [  
            'msg'  => $e->getMessage(),  
            'line' => $e->getLine(),  
        ]);  
        return response('OK', 200);  
    }  
}  
}  
  
 