<?php

namespace App\Http\Controllers\CRM;

use Illuminate\Http\Request;
use App\Models\CRM\Individual;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use App\Http\Requests\CRM\AccountsRequest;

class MoneyAccountController extends Controller
{
    /**
     * Process the form submission to create/update the accounts.
     */
    public function store(AccountsRequest $request, Individual $individual): RedirectResponse
    {
        $validated = $request->validated();

        // Create or update Bank Account
        if (!empty($validated['bank']['account_number'])) {
            $individual->bankAccounts()->updateOrCreate(
                ['status' => 'active'],
                ['account_number' => $validated['bank']['account_number']]
            );
        }

        // Create or update EUR Account
        if (!empty($validated['eur']['account_number'])) {
            $individual->eurAccounts()->updateOrCreate(
                ['status' => 'active'],
                ['account_number' => $validated['eur']['account_number']]
            );
        }

        // Create or update USD Account
        if (!empty($validated['usd']['account_number'])) {
            $individual->usdAccounts()->updateOrCreate(
                ['status' => 'active'],
                ['account_number' => $validated['usd']['account_number']]
            );
        }

        // Create or update Security Account
        if (!empty($validated['security']['account_number'])) {
            $individual->securityAccounts()->updateOrCreate(
                ['status' => 'active'],
                ['account_number' => $validated['security']['account_number']]
            );
        }

        return redirect()->route('crm.individuals.edit', $individual)
            ->with('status', 'Accounts have been successfully updated.');
    }
}
