<?php

namespace App\Domain\Shared\Traits;

use App\Domain\Identity\Models\Branch;

trait UsesBranchScope
{
    public function getActiveBranchId(): ?int
    {
        return session('active_branch_id', auth()->user()->branch_id);
    }

    public function getActiveBranchIdOrFail(): int
    {
        $id = $this->getActiveBranchId();

        if (!$id) {
            $branch = Branch::where('is_active', true)->first()
                ?? Branch::withoutGlobalScopes()->where('is_active', true)->first();

            if ($branch) {
                $id = $branch->id;
                session(['active_branch_id' => $id]);
            } else {
                abort(403, 'لا يوجد فرع نشط. يرجى إنشاء فرع أولاً.');
            }
        }

        return $id;
    }

    public function isAllBranches(): bool
    {
        return session('active_branch_id') === null && !session()->has('active_branch_id');
    }
}
