<?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 Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;

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

    protected $fillable = [
        'name', 'email', 'phone', 'password',
        'role', 'doctor_id', 'avatar', 'is_active',
    ];

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

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

    // ===== العلاقات =====
    public function doctor()
    {
        return $this->hasOne(Doctor::class);
    }

    public function patient()
    {
        return $this->hasOne(Patient::class);
    }

    // ===== Helpers للصلاحيات =====
    public function isAdmin(): bool    { return $this->role === 'admin'; }
    public function isDoctor(): bool   { return $this->role === 'doctor'; }
    public function isPatient(): bool  { return $this->role === 'patient'; }

    /** كلمة مرور عشوائية داخلية (تسجيل دخول برقم الهاتف فقط) */
    public static function randomPasswordHash(): string
    {
        return Hash::make(Str::password(48));
    }

    /**
     * البحث عن مستخدم برقم الهاتف مع تطبيع بسيط (تطابق كامل أو آخر 10 أرقام).
     */
    public static function findByPhone(?string $raw): ?self
    {
        if ($raw === null || trim($raw) === '') {
            return null;
        }

        $raw = trim($raw);
        $digits = preg_replace('/\D/', '', $raw);
        if ($digits === '') {
            return null;
        }

        $byExact = static::query()
            ->where(function ($q) use ($raw, $digits) {
                $q->where('phone', $raw)->orWhere('phone', $digits);
            })
            ->first();

        if ($byExact) {
            return $byExact;
        }

        $suffix10 = strlen($digits) >= 10 ? substr($digits, -10) : $digits;

        return static::query()
            ->whereNotNull('phone')
            ->where('phone', '!=', '')
            ->get()
            ->first(function (self $u) use ($digits, $suffix10) {
                $p = preg_replace('/\D/', '', (string) $u->phone);
                if ($p === '' || $p === '0') {
                    return false;
                }
                if ($p === $digits) {
                    return true;
                }
                if (strlen($suffix10) >= 10 && strlen($p) >= 10) {
                    return substr($p, -10) === $suffix10;
                }

                return false;
            });
    }

    // ===== Filament Admin Panel =====
    public function canAccessPanel(\Filament\Panel $panel): bool
    {
        return $this->isAdmin() && $this->is_active;
    }
}
