<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use PermissionHelper;

class Form extends Model
{
    use HasFactory;

    protected $table = "forms";

    protected $fillable = ["type_unit_id", "user_id", "title", "note"];

    public function typeUnit()
    {
        return $this->belongsTo(TypeUnit::class, "type_unit_id");
    }
    public function user()
    {
        return $this->belongsTo(User::class, "user_id");
    }

    public function sections()
    {
        return $this->hasMany(FormSection::class, "form_id");
    }

    public function scopeFilterByRole($query)
    {
        $user = auth()->user();

        if (!$user) {
            return $query;
        }

        $roleName = strtolower($user->role->role ?? '');

        if (str_contains($roleName, 'operator') || str_contains($roleName, 'driver')) {

            if (PermissionHelper::IsOperator()) {
                return $query->whereHas('typeUnit', function ($q) {
                    $q->where('name', 'like', '%excavator%')
                        ->orWhere('name', 'like', '%loader%');
                });
            } else {
                return $query->whereHas('typeUnit', function ($q) {
                    $q->where(function ($sub) {
                        $sub->where('name', 'not like', '%excavator%')
                            ->where('name', 'not like', '%loader%');
                    });
                });
            }
        }

        return $query;
    }
}