<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class OrganisationScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        try {
            $user = Auth::user();
            if ($user) {
                $orgId = $user->organisation_id;

                // Apply organisation_id based on whether it's a join query
                if ($builder->getQuery()->joins) {
                    foreach ($builder->getQuery()->joins as $join) {
                        // Add where clause for organisation_id on joined table
                        $builder->where($join->table . '.organisation_id', $orgId);
                    }
                } else {
                    // Regular query, apply to the main table
                    $builder->where($model->getTable() . '.organisation_id', $orgId);
                }
            } else {
                // Log::warning('Attempted to apply OrganisationScope without an authenticated user.');
            }
        } catch (\Exception $e) {
            Log::error('Error applying OrganisationScope: ' . $e->getMessage());
        }
    }
}
