<?php
/**
 * SalonPro X - User Model
 */

namespace Modules\Authentication\Models;

use core\Model;

class User extends Model
{
    protected string $table = 'users';
    protected string $primaryKey = 'id';
    protected bool $timestamps = true;
    protected array $fillable = [
        'branch_id', 'role_id', 'employee_id', 'username', 'email',
        'password', 'first_name', 'last_name', 'phone', 'avatar',
        'status', 'is_superadmin', 'last_login', 'ip_address',
        'remember_token', 'password_reset_token', 'password_reset_expires',
    ];
    protected array $guarded = ['id'];
    protected array $hidden = ['password', 'remember_token'];
    protected array $rules = [
        'username' => 'required|min_length:3|max_length:50',
        'email' => 'required|email|max_length:100',
        'password' => 'required|min_length:8',
        'first_name' => 'required|max_length:50',
        'last_name' => 'required|max_length:50',
    ];

    /**
     * Get users with role and branch info
     */
    public function getWithRelations(int $perPage = PAGINATION_LIMIT): object
    {
        return $this->db->table($this->table)
            ->select('users.*, roles.name as role_name, branches.name as branch_name')
            ->leftJoin('roles', 'users.role_id', '=', 'roles.id')
            ->leftJoin('branches', 'users.branch_id', '=', 'branches.id')
            ->orderBy('users.id', 'DESC')
            ->paginate($perPage);
    }

    /**
     * Find by email
     */
    public function findByEmail(string $email): ?object
    {
        return $this->findBy('email', $email);
    }

    /**
     * Get active users count
     */
    public function getActiveCount(): int
    {
        return $this->db->table($this->table)
            ->where('status', 'active')
            ->count();
    }

    /**
     * Update last login
     */
    public function updateLastLogin(int $userId, string $ip): void
    {
        $this->db->table($this->table)->where('id', $userId)->update([
            'last_login' => date(DATE_TIME_FORMAT),
            'ip_address' => $ip,
        ]);
    }
}
