<?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 Laravel\Sanctum\HasApiTokens;

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

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

//     /**
//      * 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',
//     ];
// }
// app/Models/User.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 Laravel\Sanctum\HasApiTokens;

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

    protected $fillable = [
        'name',
        'email',
        'country',
        'telephone',
        'password',
        'otp_code',
        'otp_expires_at',
        'otp_verified_at'
    ];

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

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

    // Génère un OTP valable 10 minutes
    public function generateOtp()
    {
        $this->update([
            'otp_code' => rand(100000, 999999),
            'otp_expires_at' => now()->addMinutes(10),
            'otp_verified_at' => null
        ]);

        return $this->otp_code;
    }

    // Vérifie l'OTP
    public function verifyOtp($code)
    {
        if ($this->otp_code !== $code) {
            return false;
        }

        if (now()->gt($this->otp_expires_at)) {
            return false;
        }

        $this->update([
            'otp_verified_at' => now(),
            'otp_code' => null,
            'otp_expires_at' => null
        ]);

        return true;
    }
}
