<?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 Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasRoles, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'phone',
        'profile_picture',
        'company_id',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    /**
     * Get the company that the user belongs to.
     */
    public function company()
    {
        return $this->belongsTo(\App\Modules\PLATFORM\Settings\Models\Company::class);
    }

    /**
     * Get the branches that belong to the user.
     */
    public function branches()
    {
        return $this->belongsToMany(\App\Modules\PLATFORM\Settings\Models\Branch::class)
            ->withTimestamps()
            ->withPivot('is_default');
    }

    /**
     * Get the user's default branch.
     */
    public function defaultBranch()
    {
        return $this->branches()->wherePivot('is_default', true)->first();
    }

    /**
     * Get the currently selected branch from session.
     */
    public function currentBranch()
    {
        return \App\Modules\PLATFORM\Settings\Models\Branch::find(session('current_branch_id'));
    }

    /**
     * Check if the user has access to a specific branch.
     */
    public function hasAccessToBranch(int $branchId): bool
    {
        // Super admin has access to all branches
        if ($this->isSuperAdmin()) {
            return true;
        }

        return $this->branches()->where('branch_id', $branchId)->exists();
    }

    /**
     * Check if the user is a super admin.
     */
    public function isSuperAdmin(): bool
    {
        return $this->hasRole('super-admin');
    }

    /**
     * Get all branches for super admin, or user's branches for regular users.
     */
    public function accessibleBranches()
    {
        if ($this->isSuperAdmin()) {
            return \App\Modules\PLATFORM\Settings\Models\Branch::all();
        }

        return $this->branches;
    }
}
