<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\Business;
use App\Models\ExpenseCategory;
use App\Services\AuditService;
use App\Services\BranchAccessService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class ExpenseCategoryController extends Controller
{
    public function index(Request $request): View
    {
        $businessIds = $this->allowedBusinessIds($request);
        $categories = ExpenseCategory::whereIn('business_id',$businessIds)->orderBy('name')->get();
        $businesses = Business::whereIn('id',$businessIds)->orderBy('name')->get();
        return view('expense-categories.index', compact('categories','businesses'));
    }

    public function store(Request $request): RedirectResponse
    {
        $businessIds = $this->allowedBusinessIds($request);
        $data = $request->validate([
            'business_id'=>['required','integer',Rule::in($businessIds->all())],
            'name'=>['required','string','max:120',Rule::unique('expense_categories','name')->where(fn ($q) => $q->where('business_id',$request->integer('business_id')))],
            'code'=>['nullable','string','max:40',Rule::unique('expense_categories','code')->where(fn ($q) => $q->where('business_id',$request->integer('business_id')))],
            'description'=>['nullable','string','max:1000'],
        ]);
        $category = ExpenseCategory::create($data + ['status'=>'active']);
        AuditService::record('expense_category.created',$category,[], $category->toArray());
        return back()->with('success','Expense category created.');
    }

    public function update(Request $request, ExpenseCategory $category): RedirectResponse
    {
        abort_unless($this->allowedBusinessIds($request)->contains($category->business_id),403);
        $data = $request->validate([
            'name'=>['required','string','max:120',Rule::unique('expense_categories','name')->where(fn ($q) => $q->where('business_id',$category->business_id))->ignore($category->id)],
            'code'=>['nullable','string','max:40',Rule::unique('expense_categories','code')->where(fn ($q) => $q->where('business_id',$category->business_id))->ignore($category->id)],
            'description'=>['nullable','string','max:1000'],
            'status'=>['required',Rule::in(['active','inactive'])],
        ]);
        $before = $category->only(['name','code','description','status']);
        $category->update($data);
        AuditService::record('expense_category.updated',$category,$before,$category->only(array_keys($before)));
        return back()->with('success','Expense category updated.');
    }

    private function allowedBusinessIds(Request $request)
    {
        $branchAccess = app(BranchAccessService::class);
        if ($branchAccess->isSystemWide($request->user())) {
            return Business::pluck('id');
        }

        return Branch::whereIn('id',$branchAccess->accessibleBranchIds($request->user()))
            ->pluck('business_id')
            ->unique()
            ->values();
    }
}
