<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\HasApiTokens;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
use Illuminate\Support\Facades\Log;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'civility',
        'role_id',
        'city_id',
        'controler',
        'device_key',
        'email_pro',
        'password_pro'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];


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

    public function city()
    {
        return $this->belongsTo(City::class)->withTrashed();
    }

    public function role()
    {
        return $this->belongsTo(Role::class)->withTrashed();
    }

    public function userCompanyType()
    {
        return $this->belongsToMany(TypeExpertise::class, 'user_company_type')
            ->withPivot('company_id', 'type_expertise_id');
    }
    public function userTypeCompany()
    {
        return $this->belongsToMany(Company::class, 'user_company_type')
            ->withPivot('type_expertise_id','company_id');
    }
    public function permission()
    {
        return $this->belongsToMany(Permission::class, 'user_permission');
    }
    public function company()
    {
        return $this->belongsToMany(Company::class, 'user_company', 'user_id', 'company_id')->withTrashed();
    }
    public function manygarage()
    {
        return $this->belongsToMany(Garage::class, 'user_garage', 'user_id', 'garage_id')->withTrashed();
    }

    public function hasRolePermission($permission)
    {
        return $this->role->permission->contains('permission', $permission);
    }

    public function hasPermission($permission)
    {
        return $this->permission->contains('permission', $permission);
    }
    public function hasPermissionId($key)
    {
        return $this->permission->contains('key', $key);
    }
    public function hasCompany($company)
    {
        return $this->company->contains('company', $company);
    }
    public function hasType($type)
    {
        return $this->typeexpertise->contains('type', $type);
    }
    public function hasGuarantee($guarantee)
    {
        return $this->guarantee->contains('guarantee', $guarantee);
    }
    public function hasGarage($id)
    {
        return $this->manygarage()->where('garage_id', $id)->exists();
    }

    public function isAdmin()
    {
        return $this->role->contains('role', 'Admin');
    }
    public function seuil()
    {
        return $this->hasMany(Seuil::class);
    }

    public function garage()
    {
        return $this->hasOne(Garage::class)->withTrashed();
    }

    public function observation()
    {
        return $this->hasOne(Observation::class)->withTrashed();
    }

    public function notification()
    {
        return $this->hasMany(Notification::class);
    }

    public function demande()
    {
        return $this->hasMany(Demande::class);
    }

    public function meeting()
    {
        return $this->hasMany(Meeting::class)->withTrashed();
    }

    public function typecompany()
    {
        return $this->belongsToMany(Company::class, 'user_company_type')
            ->withPivot('type_expertise_id');
    }
    public function typec()
    {
        return $this->belongsToMany(TypeExpertise::class, 'user_company_type')
            ->withPivot('company_id');
    }

    public function location()
    {
        return $this->hasOne(Location::class)->withTrashed();
    }

    public function typeexpertise()
    {
        return $this->belongsToMany(TypeExpertise::class, 'user_typeexpertise');
    }

    public function step()
    {
        return $this->belongsToMany(Step::class, 'step_dossier')->withPivot('user_id')->withTimestamps();
    }

    public function guarantee()
    {
        return $this->belongsToMany(Guarantee::class, 'guarantee_user');
    }

    public function substitute()
    {
        return $this->hasOne(Substitute::class);
    }
    public function onecompany()
    {
        return $this->hasOne(Company::class);
    }

    public function call()
    {
        return $this->hasMany(Call::class);
    }

    public function device()
    {
        return $this->hasOne(Device::class);
    }

    public function typedocument()
    {
        return $this->belongsToMany(TypeDocument::class, 'user_typedocuments');
    }

    public function hasTypeDocument($type)
    {
        return $this->typedocument->contains('type', $type);
    }

    public function hasCompanyType($company)
    {
        return $this->typecompany->contains('company', $company);
    }

    public function hasTypeCompany($type, $company, $id)
    {
        $result = DB::table('user_company_type')
            ->where('user_id', $id)
            ->where('type_expertise_id', $type)
            ->where('company_id', $company)
            ->exists();

        return $result;
    }

    public function sendFCMNotification( $title, $body)
    {

        $deviceToken = $this->device_key;
        if ($deviceToken) {


            $firebase = (new Factory)->withServiceAccount(config('services.firebase.credentials'));
            $messaging = $firebase->createMessaging();

            $message = CloudMessage::withTarget('token', $deviceToken)
                ->withNotification(Notification::create($title, $body));

            try {
                $messaging->send($message);
                return response()->json(['status' => 'success'], 200);
            } catch (\Kreait\Firebase\Exception\MessagingException $e) {
                Log::error('Error sending message: ' . $e->getMessage());
                return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
            }
        }
    }
}
