<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\HasApiTokens;

use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'first_name',
        'last_name',
        'phone',
        'email',
        'document_type',
        'document',
        'document_expedition',
        'gender_user',
        'status',
        'password',
        'weak_password',
        'civil_status',
        'nationality',
        'birth_date',
        'birth_place',
        'address',
        'state_residence',
        'city_residence',
        'eps_id',
        'title_position',
        'professional_license',
        'professional_profile',
        'social_facebook',
        'social_twitter',
        'social_instagram',
        'social_linkedin',
        'image',
        'signature',
        'notification',
        'last_login_at',
        'last_login_ip',
    ];

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

    public function CompanyId() {
        $company_id = DB::table('users')
        ->join('company_user', 'users.id', '=', 'company_user.user_id')
        ->join('companies', 'company_user.company_id', '=', 'companies.id')
        ->select('companies.id')
        ->where('users.id', Auth::user()->id)
        ->get()->first();

        return $company_id->id;
    }
    public function CompanyInfo($param) {
        $company_id = DB::table('users')
        ->join('company_user', 'users.id', '=', 'company_user.user_id')
        ->join('companies', 'company_user.company_id', '=', 'companies.id')
        ->select('companies.*')
        ->where('users.id', Auth::user()->id)
        ->get()->first();
        return $company_id->$param;
    }
    public function LogoCompany() {
        $company_logo = DB::table('users')
        ->join('company_user', 'users.id', '=', 'company_user.user_id')
        ->join('companies', 'company_user.company_id', '=', 'companies.id')
        ->select('companies.id as company_id', 'companies.image as imagen', 'companies.name as company_name')
        ->where('users.id', Auth::user()->id)
        ->get()->first();
        if (Auth::user()->hasRole('Soporte')) {
            $logo=url('storage/companies/3mas1r.png');
            $class_img='img-logo-app';
            $company_name = '3Mas1R';
        }
        else if (Auth::user()->hasRole('Super Admin')){
            $logo=url('storage/companies/alira.svg');
            $class_img='img-logo-app';
            $company_name = "Alira";
        }
        else{
            $logo=url('storage/companies/'.$company_logo->company_id.'/'.$company_logo->imagen);
            $class_img='img-logo-company';
            $company_name=$company_logo->company_name;
        }

        return array('logo'=>$logo,'class_img'=>$class_img,'company_name'=>$company_name);
    }

    public function getImagenAttribute(){
        if ($this->image != null)//si la consulta devuelve el nombre de una imagen
        {
            if(file_exists('storage/users/'.$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-user.png';
        }
        else
            return 'no-user.png';
    }

    public function getCityResidenceNameAttribute(){
        $city = DB::table('cities')
        ->select('name')
        ->where('code', $this->city_residence)
        ->get()->first();
        return $city->name;
    }
    public function getStateResidenceNameAttribute(){
        $state = DB::table('states')
        ->select('name')
        ->where('code', $this->state_residence)
        ->get()->first();
        return $state->name;
    }
    public function getEpsNameAttribute(){
        $eps = DB::table('eps')
        ->select('name')
        ->where('id', $this->eps_id)
        ->get()->first();
        return $eps->name;
    }
    public function getAgeAttribute(){
        return Carbon::parse($this->birth_date)->age;
    }

    public function getCivilStatusNameAttribute(){
        if ($this->gender == "Masculino")
            $g = "o";
        else
            $g = "a";

        if ($this->civil_status == '3')
            return DataTypeCivilStatus($this->civil_status);
        else
            return DataTypeCivilStatus($this->civil_status).$g;
    }
    public function getDocumentTypeNameAttribute(){
        return DataTypeDocument($this->document_type);
    }
    public function getDocumentTypeNameAbbreviationAttribute(){
        return DataTypeDocument($this->document_type, true);
    }

    public function getBirthDateEsAttribute(){
        return Carbon::parse($this->birth_date)->day . ' de ' . Carbon::parse($this->birth_date)->monthName . ' de ' . Carbon::parse($this->birth_date)->year;
    }

    public function getFullNameAttribute(){
        return $this->first_name . ' ' . $this->last_name;
    }
/*
    public function setBirthDateAttribute($value){
        return Carbon::createFromFormat('Y-m-d', $value);
    }
*/
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function city_residence(){
        return $this->belongsTo('App\Models\City','city_residence','code');
    }
    public function state_residence(){
        return $this->belongsTo('App\Models\State','state_residence','code');
    }

    public function languages(){
        return $this->belongsToMany(Language::class)
                    ->withPivot(['level'])
                    ->as('language_level');
    }
    public function nacionality(){
        return $this->belongsTo(Country::class);
    }
    public function work_experiences(){
        return $this->hasMany(WorkExperience::class);
    }
    public function academic_formations(){
        return $this->hasMany(academic_formation::class);
    }
    public function skills(){
        return $this->hasMany(Skill::class);
    }
    public function references(){
        return $this->hasMany(Reference::class);
    }
    public function trainings(){
        return $this->hasMany(Training::class);
    }
}
