<?php

namespace App\Models;

use App\Notifications\ResetUserPassword;
use App\Notifications\VerifyUserEmail;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Storage;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable, CanResetPassword;

    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'password',
        'role',
        'company_name',
        'state',
        'profile_image',
        'phone',
        'fax',
        'address',
        'house_no',
        'zip',
        'city',
        'country',
        'last_login',
        'two_factor_code',
        'two_factor_expires_at',
    ];

    protected $attributes = [
        'state' => ['pendingEmailValidation', 'pendingApproval', 'active', 'inactive'],
    ];

    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_code',
    ];

    protected $casts = [
        'email_verified_at'      => 'datetime',
        'two_factor_expires_at'  => 'datetime',
    ];

    public function isAdmin()
    {
        return $this->role !== 'user';
    }

    public function hasRole($role)
    {
        return $this->role === $role;
    }

    public function legalEntity()
    {
        return $this->hasMany(LegalEntity::class);
    }

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

    public function trustedDevices()
    {
        return $this->hasMany(TrustedDevice::class);
    }

    public function getStateFormated()
    {
        switch ($this->state) {
            case 'pendingEmailValidation':
                return 'Pending Email Validation';
                break;
            case 'pendingApproval':
                return 'Pending Approval';
                break;
            case 'active':
                return 'Active';
                break;
            default:
                # inactive
                return 'Inactive';
                break;
        }
    }

    public function sendPasswordUserResetNotification($token, $email)
    {
        $this->notify(new ResetUserPassword($token, $email));
    }

    public function sendEmailVerificationNotification()
    {
        $this->notify(new VerifyUserEmail);
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($user) {
            $profileImage = $user->profile_image;
            if ($profileImage) {
                $filePath = 'profile_images/' . $profileImage;

                if (Storage::disk('public')->exists($filePath)) {
                    Storage::disk('public')->delete($filePath);
                }
            }
        });
    }
}
