<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

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

    protected $table = 'users';

    protected $fillable = [
        'name',
        'email',
        'phone',
        'otp',
        'otp_expires_at',
        'password',
        // Remove 'role' from here - it's managed by Spatie
    ];

    protected $hidden = [
        'password',
        'remember_token',
        'otp',
        'otp_expires_at',
    ];

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

    // Add this method to verify OTP
    public function verifyOtp($otp): bool
    {
        if ($this->otp === $otp && now()->lt($this->otp_expires_at)) {
            $this->otp = null;
            $this->otp_expires_at = null;
            $this->save();
            return true;
        }
        return false;
    }

    /**
     * Get the primary role name for display purposes
     */
    public function getDisplayRoleAttribute(): string
    {
        return $this->getRoleNames()->first() ?? 'No Role';
    }
}