<?php 

// app/Http/Controllers/Admin/BankTransferAdminController.php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BankTransfer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BankTransferAdminController extends Controller
{
    public function index(Request $r) {
        $tx = BankTransfer::with(['bank','user'])->latest()
            ->when($r->status, fn($q)=>$q->where('status',$r->status))
            ->paginate(30);
        return view('admin.bank_transfers.index', compact('tx'));
    }

    public function approve(BankTransfer $transfer, Request $r) {
        if ($transfer->status !== 'pending') return back()->with('info','Already processed.');

        try {
            DB::transaction(function () use ($transfer, $r) {
                $user = $transfer->user()->lockForUpdate()->first();
                $bank = $transfer->bank()->first();
                $amount = (float) $transfer->amount;

                if ($user->balance < $amount) abort(400, 'Insufficient balance.');

                // 1) balance debit
                $user->balance = round($user->balance - $amount, 2);

                // 2) reward points (admin-set %)
                $points = $bank->rewardPointsFor($amount); // round(amount * reward_percent/100)
                $user->reward_points = (int)$user->reward_points + $points;
                $user->save();

                // 3) update transfer
                $transfer->update([
                    'status' => 'approved',
                    'admin_note' => $r->string('admin_note'),
                ]);
            });

            return back()->with('success','Approved, debited & reward points added.');
        } catch (\Throwable $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function reject(BankTransfer $transfer, Request $r) {
        if ($transfer->status !== 'pending') return back()->with('info','Already processed.');
        $transfer->update(['status'=>'rejected','admin_note'=>$r->string('admin_note')]);
        return back()->with('success','Rejected.');
    }
}
