<?php

namespace App\Http\Controllers;

use App\Models\AccountingEntry;
use App\Models\Branch;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AccountingLedgerController extends Controller
{
    public function index(Request $request): View
    {
        $branchIds=$this->allowedBranchIds($request);
        abort_if($branchIds->isEmpty(), 403, 'No branch access is assigned to this user.');
        $query=AccountingEntry::with(['branch','financialAccount','user'])->whereIn('branch_id',$branchIds)->latest('entry_date')->latest('id');
        if($request->filled('search')){
            $search=trim((string)$request->string('search'));
            $query->where(fn($q)=>$q->where('journal_number','like',"%{$search}%")->orWhere('reference','like',"%{$search}%")->orWhere('description','like',"%{$search}%"));
        }
        if($request->filled('category')) $query->where('category',$request->string('category'));
        if($request->filled('branch')) {
            $branchId=$request->integer('branch');
            abort_unless($branchIds->contains($branchId), 403, 'The selected branch is outside your assigned scope.');
            $query->where('branch_id',$branchId);
        }
        return view('accounting.ledger.index',[
            'entries'=>$query->paginate(30)->withQueryString(),
            'branches'=>Branch::whereIn('id',$branchIds)->orderBy('name')->get(),
            'categories'=>AccountingEntry::CATEGORIES,
        ]);
    }

    private function allowedBranchIds(Request $request)
    {
        return collect(app(\App\Services\BranchAccessService::class)->accessibleBranchIds($request->user()));
    }
}
