<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Query\Builder;
use Laravel\Prompts\Note;

class Transmittal extends Model
{
    use HasFactory;

    protected $guarded = [];

    protected $casts = [
        'date_created' => 'date',
        'date_dispatch' => 'date',
        'date_received' => 'date'
    ];

    public function files(): HasMany
    {
        return $this->hasMany(File::class);
    }

    public function notes(): HasManyThrough
    {
        return $this->hasManyThrough(Comment::class, File::class);
    }

    public function remarks(): HasManyThrough
    {
        return $this->hasManyThrough(Remark::class, File::class);
    }

    public function client(): BelongsTo
    {
        return $this->belongsTo(Client::class);
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function scopeDateCreatedFilter(Builder $query, $date) : Builder
    {
        $dates = explode(' to ',$date);
        if(isset($dates[1])) {
            return $query->whereBetween('date_created' ,[$dates[0], $dates[1]]);
        }
        return $query->where('date_created', $dates[0]);
    }

    public function scopeDateDispatchedFilter(Builder $query, $date) : Builder
    {
        $dates = explode(' to ',$date);
        if(isset($dates[1])) {
            return $query->whereBetween('date_dispatch', [$dates[0], $dates[1]]);
        }

        return $query->where('date_dispatch', $dates[0]);
    }

    public function scopeDateReceivedFilter(Builder $query, $date) : Builder
    {
        $dates = explode(' to ',$date);
        if(isset($dates[1])) {
            return $query->whereBetween('date_received', [$dates[0], $dates[1]]);
        }
        return $query->where('date_received', $dates[0]);
    }
}
