<?php

namespace App\Models;

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

class Daily extends Model
{
    use HasFactory;
    protected $table = 'dailies';

    protected $fillable = [
        'form_id',
        'user_id',
        'shift_id',
        'location_id',
        'unit_id',
        'code_report',
        'date',
        'status_daily',
        "comment"
    ];

    /**
     * Relasi ke Form
     */
    public function form()
    {
        return $this->belongsTo(Form::class, 'form_id');
    }

    /**
     * Relasi ke User
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id')->withTrashed();
    }

    /**
     * Relasi ke Shift
     */
    public function shift()
    {
        return $this->belongsTo(Shift::class, 'shift_id');
    }

    public function location()
    {
        return $this->belongsTo(Location::class, 'location_id')->withTrashed();
    }

    /**
     * Jika daily punya banyak detail (misalnya daily_items)
     */
    public function detail()
    {
        return $this->hasMany(DetailDaily::class, 'dailies_id');
    }

    public function unit()
    {
        return $this->belongsTo(Unit::class, 'unit_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('unit.unittype', function ($q) {
                    $q->where('name', 'like', '%excavator%')
                        ->orWhere('name', 'like', '%loader%');
                });
            } else {
                return $query->whereHas('unit.unittype', function ($q) {
                    $q->where(function ($sub) {
                        $sub->where('name', 'not like', '%excavator%')
                            ->where('name', 'not like', '%loader%');
                    });
                });
            }
        }

        return $query;
    }

}
