<?php

namespace App\Http\Controllers\Client;

use App\Enums\RecordStatus;
use App\Enums\UserRole;
use App\Http\Controllers\Controller;
use App\Models\SiteSetting;
use App\Models\Transaction;
use App\Models\Transfer;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TransferController extends Controller
{
    public function store(Request $request)
    {
        $minLimit = (float) SiteSetting::get('transfer_min_limit', 0);
        $chargePercent = (float) SiteSetting::get('transfer_charge', 0);

        $data = $request->validate([
            'recipient' => ['required', 'string'],
            'amount' => ['required', 'numeric', 'min:'.max($minLimit, 1)],
        ]);

        $recipient = User::where('role', UserRole::User)
            ->where(function ($q) use ($data) {
                $q->where('email', $data['recipient'])
                    ->orWhere('username', $data['recipient']);
            })
            ->first();

        if (! $recipient) {
            return back()->with('error', 'Recipient not found.');
        }

        if ($recipient->id === $request->user()->id) {
            return back()->with('error', 'You cannot transfer to yourself.');
        }

        $fee = $data['amount'] * ($chargePercent / 100);
        $total = $data['amount'] + $fee;

        if ($request->user()->balance < $total) {
            return back()->with('error', 'Insufficient balance (including fees).');
        }

        DB::transaction(function () use ($request, $recipient, $data, $fee, $total) {
            $sender = $request->user();
            $sender->decrement('balance', $total);
            $recipient->increment('balance', $data['amount']);

            Transfer::create([
                'from_user_id' => $sender->id,
                'to_user_id' => $recipient->id,
                'amount' => $data['amount'],
                'status' => 'completed',
            ]);

            Transaction::create([
                'user_id' => $sender->id,
                'type' => 'transfer',
                'details' => "Transfer to {$recipient->username}",
                'amount' => $data['amount'],
                'status' => RecordStatus::Approved,
            ]);
        });

        return redirect()->route('client.home.transfer')
            ->with('success', 'Transfer completed successfully.');
    }
}
