<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Company extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'nit',
        'address',
        'state',
        'city',
        'phone',
        'email',
        'legal_representative',
        'document_type_representative',
        'document_representative',
        'document_expedition_representative',
        'image',
        'plan_id',
        'plan_payment_status',
        'watermark',
        'company_employee_update_time', // tiempo en días para que el empleado pueda actualizar su hoja de vida
    ];



    public function users()
    {
        return $this->belongsToMany(User::class)
            ->withTimestamps()
            ->withPivot('job_position_id', 'payment_method', 'salary_type', 'salary',
            'base_salary', 'performance_factor', 'job_position_administrative_area', 'initial_date_cv');
    }

    public function PaymentMethodName(){
        return DataTypePaymentMethod($this->pivot->payment_method);
    }

    public function plan()
    {
        return $this->belongsTo(Plan::class);
    }

    public function work_permits()
    {
        return $this->hasMany(WorkPermit::class);
    }

    public function psychotechnics_tests()
    {
        return $this->hasMany(UserPsychotechnicsTest::class);
    }

    public function getImagenAttribute(){
        if ($this->image != null)//si la consulta devuelve el nombre de una imagen
        {
            if(file_exists('storage/companies/'. $this->id .'/'. $this->image))//verificamos que la imagen exista fisicamente
               return $this->id .'/'.$this->image; //mostrar la imagen de la base de datos
            else
                return 'no-logo.png';
        }
        else
            return 'no-logo.png';
    }



    public function getCityNameAttribute()
    {
        $city = DB::table('cities')
            ->where('code', $this->city)
            ->get()->first();
        return $city->name;
    }

    public function getStateNameAttribute()
    {
        $state = DB::table('states')
            ->where('code', $this->state)
            ->get()->first();
        return $state->name;
    }


    public function getDocumentTypeRepresentativeNameAttribute()
    {
        return DataTypeDocument($this->document_type_representative);
    }
    public function getDocumentTypeRepresentativeNameAbbreviationAttribute()
    {
        return DataTypeDocument($this->document_type_representative, true);
    }


}
