<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Role;

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

    protected $fillable = [
        'username',
        'name',
        'email',
        'password',
        'primary_role_id',
        'roles_backup',
        'profile_photo'
    ];

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

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

    protected $guard_name = 'web';

    // =========================================
    // RELATIONSHIPS
    // =========================================

    public function primaryRole()
    {
        return $this->belongsTo(Role::class, 'primary_role_id');
    }

    public function spSiptCreated()
    {
        return $this->hasMany(SpSipt::class, 'created_by');
    }

    public function spSiptApproved()
    {
        return $this->hasMany(SpSipt::class, 'approved_by');
    }

    // =========================================
    // CUSTOM HELPER METHODS
    // =========================================

    /**
     * Get primary role name
     */
    public function getPrimaryRoleName()
    {
        return $this->primaryRole ? $this->primaryRole->name : null;
    }

    /**
     * Get primary role display name
     */
    public function getPrimaryRoleDisplayName()
    {
        return $this->primaryRole
            ? ($this->primaryRole->display_name ?? $this->primaryRole->name)
            : 'User';
    }

    /**
     * Assign role and set as primary
     */
    public function assignRoleAndSetPrimary($role)
    {
        $this->assignRole($role);

        $roleModel = is_string($role)
            ? Role::where('name', $role)->first()
            : $role;

        if ($roleModel) {
            $this->update(['primary_role_id' => $roleModel->id]);
        }

        return $this;
    }

    /**
     * Sync roles and set primary
     */
    public function syncRolesAndSetPrimary($roles, $primaryRole = null)
    {
        $this->syncRoles($roles);

        if ($primaryRole) {
            $roleModel = is_string($primaryRole)
                ? Role::where('name', $primaryRole)->first()
                : $primaryRole;
        } else {
            // Set first role as primary if not specified
            $roleModel = $this->roles->first();
        }

        if ($roleModel) {
            $this->update(['primary_role_id' => $roleModel->id]);
        }

        return $this;
    }

    /**
     * Check if user is superadmin
     */
    public function isSuperAdmin()
    {
        return $this->hasRole('superadmin');
    }

    // =========================================
    // QUERY SCOPES
    // =========================================

    public function scopeWithRole($query, $role)
    {
        return $query->whereHas('roles', function ($q) use ($role) {
            $q->where('name', $role);
        });
    }

    public function scopeWithPermission($query, $permission)
    {
        return $query->whereHas('permissions', function ($q) use ($permission) {
            $q->where('name', $permission);
        });
    }
}
