<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

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

    protected $primaryKey = 'user_id';

    protected $fillable = [
        'email',
        'password_hash',
        'role_id', // ✅ Correct - using role_id
        'first_name',
        'last_name',
        'phone_number',
        'profile_picture_url',
        'date_of_birth',
        'gender',
        'bio',
        'preferred_language',
        'preferred_currency',
        'base_currency',
        'is_email_verified',
        'is_phone_verified',
        'is_profile_completed',
        'is_active',
        'last_login_at',
        'reset_password_token', // ✅ Added for password reset
        'reset_password_token_expires_at' // ✅ Added for password reset
    ];

    protected $hidden = [
        'password_hash',
        'remember_token',
        'reset_password_token', // ✅ Hide reset token
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'date_of_birth' => 'date',
        'is_email_verified' => 'boolean',
        'is_phone_verified' => 'boolean',
        'is_profile_completed' => 'boolean',
        'is_active' => 'boolean',
        'last_login_at' => 'datetime',
        'reset_password_token_expires_at' => 'datetime', // ✅ Added cast
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime'
    ];

    /**
     * Get the password attribute for authentication
     */
    public function getAuthPassword()
    {
        return $this->password_hash;
    }

    /**
     * Get the role that owns the user.
     */
    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id', 'role_id');
    }

    /**
     * Get the addresses for the user.
     */
    public function addresses()
    {
        return $this->hasMany(Address::class, 'user_id', 'user_id');
    }

    /**
     * Get the primary address for the user.
     */
    public function primaryAddress()
    {
        return $this->hasOne(Address::class, 'user_id', 'user_id')->where('is_primary', true);
    }

    /**
     * Get the babysitter profile for the user.
     */
    // User.php model में
    public function babysitterProfile()
    {
        return $this->hasOne(BabysitterProfile::class, 'user_id', 'user_id');
    }

    /**
     * Get the parent profile for the user.
     */
    public function parentProfile()
    {
        return $this->hasOne(ParentProfile::class, 'user_id', 'user_id');
    }

    /**
     * Get the user languages.
     */
    public function userLanguages()
    {
        return $this->hasMany(UserLanguage::class, 'user_id', 'user_id');
    }

    /**
     * Scope active users
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope by role
     */
    public function scopeByRole($query, $roleId)
    {
        return $query->where('role_id', $roleId);
    }

    /**
     * Scope by role name
     */
    public function scopeByRoleName($query, $roleName)
    {
        return $query->whereHas('role', function ($q) use ($roleName) {
            $q->where('role_name', $roleName);
        });
    }

    /**
     * Check if user has specific permission
     */
    public function hasPermission($permission)
    {
        if (!$this->role) {
            return false;
        }

        return $this->role->hasPermission($permission);
    }

    /**
     * Check if user is super admin
     */
    public function isSuperAdmin()
    {
        return $this->role && $this->role->role_name === 'super_admin';
    }

    /**
     * Check if user is babysitter
     */
    public function isBabysitter()
    {
        return $this->role && $this->role->role_name === 'babysitter';
    }

    public function getFormattedBabysitterDataAttribute()
    {
        if (!$this->isBabysitter()) {
            return null;
        }

        return [
            'babysitter_id' => $this->user_id,
            'babysitter_profile_id' => $this->babysitterProfile ? $this->babysitterProfile->profile_id : null,
            'user_id' => $this->user_id,
            'email' => $this->email,
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'full_name' => $this->full_name,
            'phone_number' => $this->phone_number,
            'profile_picture_url' => $this->profile_picture_url,
            'date_of_birth' => $this->date_of_birth,
            'gender' => $this->gender,
            'bio' => $this->bio,
            'babysitter_profile' => $this->babysitterProfile
        ];
    }

    /**
     * Check if user is parent
     */
    public function isParent()
    {
        return $this->role && $this->role->role_name === 'parent';
    }

    /**
     * Get full name attribute
     */
    public function getFullNameAttribute()
    {
        return $this->first_name . ' ' . $this->last_name;
    }

    /**
     * Check if reset token is valid
     */
    public function hasValidResetToken()
    {
        return $this->reset_password_token &&
               $this->reset_password_token_expires_at &&
               $this->reset_password_token_expires_at->isFuture();
    }

    /**
     * Clear reset token
     */
    public function clearResetToken()
    {
        $this->update([
            'reset_password_token' => null,
            'reset_password_token_expires_at' => null
        ]);
    }

    /**
     * Route notifications for the mail channel.
     */
    public function routeNotificationForMail($notification)
    {
        return $this->email;
    }

    /**
     * Route notifications for the broadcast channel.
     */
    public function routeNotificationForBroadcast($notification)
    {
        return 'users.' . $this->user_id;
    }
}
