<?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\SoftDeletes;
use OwenIt\Auditing\Contracts\Auditable;
use OwenIt\Auditing\Auditable as AuditableTrait;

class Dealership extends Model implements Auditable
{
    use HasFactory, SoftDeletes, AuditableTrait;

     /**
     * The attributes that are NOT mass assignable.
     *
     */
    protected $guarded = [
        'deleted_at',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class, 'company_id');
    }

    // public function group_division(): HasMany
    // {
    //     return $this->hasMany(Group::class, 'dealership_id');
    // }

    public function group_division(): HasMany
    {
        return $this->hasMany(Group::class, 'group_division_id');
    }

    public function dealership_approver()
    {
        return $this->hasMany(Approver::class, 'type_id')
                    ->where('type', 'dealership');
    }

    public function departments()
    {
        return $this->hasManyThrough(
            Department::class, // Target model
            Employee::class,   // Intermediate model
            'dealer_id',       // Foreign key on the employees table (to match dealer_id)
            'id',   // Foreign key on the departments table
            'id',              // Local key on the dealers table
            'department_id'               // Local key on the employees table (to match department_id)
        )
        ->where('employees.enabled', 1) // Filter employees by enabled = 1
        ->whereNull('employees.date_resign') // Filter employees by not resigned
        ->distinct('department_id');
    }

    public function attendance_posting(): HasMany
    {
        return $this->hasMany(AttendancePosting::class, 'dealership_id');
    }

    public function payroll(): HasMany
    {
        return $this->hasMany(Payroll::class, 'dealership_id');
    }
}
