<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Spatie\Permission\Traits\HasRoles;

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

    /**
     * Spatie permission guard (ডিফল্ট web)
     * config/permission.php এর সাথে ম্যাচ করবে
     */
    protected string $guard_name = 'web';

    protected $fillable = [
        'company_id',
        'branch_id',
        'name',
        'email',
        'password',
        'status',
        'api_token',
        'password_reset_token',
        'employee_full_id',
        'device_token',
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
        'status'            => 'boolean',
    ];

    /**
     * Auto-hash incoming plain text passwords (safe)
     */
    public function setPasswordAttribute($value): void
    {
        if (!$value) {
            $this->attributes['password'] = $value;
            return;
        }

        $looksHashed = Str::startsWith($value, ['$2y$', '$argon2i$', '$argon2id$']);
        $this->attributes['password'] = $looksHashed ? $value : Hash::make($value);
    }

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }
}



