<?php

namespace App\Http\Controllers;

use App\Models\Account;
use App\Models\Contact;
use App\Models\Transaction;
use Illuminate\Http\Request;

class SendController extends Controller
{
    public function index()
    {
        $user = auth()->user();
        $accounts = Account::where('user_id', $user->id)->get();
        $contacts = Contact::where('user_id', $user->id)->get();

        return view('dashboard.send', compact('user', 'accounts', 'contacts'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'from_account' => ['required', 'exists:accounts,id'],
            'recipient_name' => ['required', 'string', 'max:255'],
            'recipient_iban' => ['required', 'string', 'max:255'],
            'recipient_swift' => ['nullable', 'string', 'max:255'],
            'amount' => ['required', 'numeric', 'min:0.01'],
            'description' => ['nullable', 'string', 'max:1000'],
        ]);

        $account = Account::where('id', $validated['from_account'])
            ->where('user_id', auth()->id())
            ->firstOrFail();

        if ($account->balance < $validated['amount']) {
            return back()->withErrors(['amount' => 'Insufficient funds.']);
        }

        $reference = strtoupper(uniqid('TXN'));

        Transaction::create([
            'user_id' => auth()->id(),
            'type' => 'debit',
            'amount' => $validated['amount'],
            'currency' => $account->currency,
            'recipient_name' => $validated['recipient_name'],
            'recipient_iban' => $validated['recipient_iban'],
            'recipient_swift' => $validated['recipient_swift'],
            'description' => $validated['description'],
            'status' => 'completed',
            'reference' => $reference,
        ]);

        $account->decrement('balance', $validated['amount']);

        return redirect('/dashboard/transfers')->with('status', 'Payment sent successfully!');
    }
}
