<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\FinancialAccount;
use App\Services\AuditService;
use App\Services\BranchAccessService;
use App\Services\FinancialAccountingService;
use Carbon\CarbonImmutable;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CapitalInjectionController extends Controller
{
    public function create(Request $request): View
    {
        return view('accounting.capital.create',['accounts'=>$this->accounts($request)]);
    }

    public function store(Request $request, FinancialAccountingService $service): RedirectResponse
    {
        $data=$request->validate([
            'account_id'=>['required','integer','exists:financial_accounts,id'],
            'amount'=>['required','decimal:0,2','min:0.01'],
            'date'=>['required','date'],
            'reference'=>['nullable','string','max:150'],
            'notes'=>['nullable','string','max:2000'],
        ]);
        $account=FinancialAccount::findOrFail($data['account_id']);
        abort_unless($request->user()->canAccessBranch($account->branch_id),403);
        $capital=$service->injectCapital($account,(string)$data['amount'],CarbonImmutable::parse($data['date']),$data['reference'] ?? null,$data['notes'] ?? null,$request->user());
        AuditService::record('capital.injected',$capital,[],['amount'=>$capital->amount,'account_id'=>$capital->account_id,'capital_number'=>$capital->capital_number],$account->branch_id);
        return redirect()->route('accounts.show',$account)->with('success','Business capital recorded successfully.');
    }

    private function accounts(Request $request)
    {
        $branchIds=app(BranchAccessService::class)->accessibleBranchIds($request->user());
        return FinancialAccount::with('branch')->whereIn('branch_id',$branchIds)->where('status','active')->orderBy('name')->get();
    }
}
