<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use OwenIt\Auditing\Contracts\Auditable;
use OwenIt\Auditing\Auditable as AuditableTrait;

class Role 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',
    ];

    protected $appends = [
        'companies',
        'dealerships',
    ];

    protected $with = [
        'group'
    ];

    /**
     * Get the group that owns the Role
     *
     */
    public function group()
    {
        return $this->belongsTo(RoleGroup::class, 'group_id', 'id');
    }

    public function company_access()
    {
            return $this->hasMany(RoleCompanyAccess::class, 'role_id', 'id');
    }

    public function getCompaniesAttribute()
    {
        if($this->group_id == 1) {
            $record = Company::all();
        } else {
            $record = Company::select('companies.*')->distinct('name')
            ->join('role_company_access', 'companies.id', '=', 'role_company_access.company_id')
            ->where('role_id', $this->id)
            ->get();
        }
        return $record;
    }

    public function getDealershipsAttribute()
    {
        if($this->group_id == 1) {
            $record = Dealership::all();
        } else {
            // \DB::enableQueryLog();
            $record = Dealership::select('dealerships.*')->distinct('name')
            ->join('role_company_access', function($join) {
                $join->on('role_company_access.company_id', '=', 'dealerships.company_id')
                ->on(function($join2) {
                    $join2->on('role_company_access.dealership_id', '=', 'dealerships.id');
                    // ->orWhere('role_company_access.dealership_id', '=', 0);
                });
            })
            ->where('role_company_access.role_id', '=', $this->id)
            ->get();
            // dd(\DB::getQueryLog());
        }

        return $record;
    }
}
