﻿<?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) {
                        $builder->where(function ($query) use ($join, $orgId) {
                            $query->where($join->table . '.organisation_id', $orgId)
                                ->orWhereNull($join->table . '.organisation_id');
                        });
                    }
                } else {
                    $builder->where(function ($query) use ($model, $orgId) {
                        $query->where($model->getTable() . '.organisation_id', $orgId)
                            ->orWhereNull($model->getTable() . '.organisation_id');
                    });
                }
            } else {
                Log::warning('Attempted to apply OrganisationScope without an authenticated user.');
            }
        } catch (\Exception $e) {
            Log::error('Error applying OrganisationScope: ' . $e->getMessage());
        }
    }