<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    public const STAFF_ROLES = [
        'admin' => 'Administrator',
        'manager' => 'Manager',
        'supervisor' => 'Supervisor',
        'accountant' => 'Accountant',
        'receptionist' => 'Receptionist',
        'chef' => 'Chef',
        'kitchen' => 'Kitchen Staff',
        'bartender' => 'Bartender',
        'waiter' => 'Waiter',
        'housekeeper' => 'Housekeeper',
        'storekeeper' => 'Storekeeper',
        'procurement' => 'Procurement Officer',
    ];

    protected $fillable = [
        'name', 'email', 'password', 'role', 'phone', 'avatar', 'address',
        'department', 'status', 'referral_code', 'referred_by', 'last_login_at',
        'two_factor_secret', 'two_factor_confirmed_at', 'two_factor_recovery_codes',
    ];

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

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

    public function customerProfile()
    {
        return $this->hasOne(Customer::class);
    }

    public function chefProfile()
    {
        return $this->hasOne(Chef::class);
    }

    public function hotel()
    {
        return $this->belongsTo(Hotel::class);
    }

    public function isSuperAdmin(): bool
    {
        return $this->role === 'super_admin';
    }

    public function isStaff(): bool
    {
        return $this->isSuperAdmin() || array_key_exists($this->role, self::STAFF_ROLES);
    }

    public function hasRole(string ...$roles): bool
    {
        return $this->isSuperAdmin() || in_array($this->role, $roles, true);
    }

    public function roleLabel(): string
    {
        if ($this->isSuperAdmin()) {
            return 'Platform Owner';
        }

        return self::STAFF_ROLES[$this->role] ?? ucfirst($this->role ?? 'customer');
    }

    public function initials(): string
    {
        $parts = preg_split('/\s+/', trim((string) $this->name));

        return strtoupper(substr($parts[0] ?? 'U', 0, 1) . substr($parts[1] ?? '', 0, 1));
    }

    public function hasTwoFactor(): bool
    {
        return ! is_null($this->two_factor_confirmed_at);
    }
}
