<?php
/**
 * Model User
 * mySupport - Plateforme de Service Client Intelligent
 */

namespace App\Models;

use Core\Model;

class User extends Model
{
    protected string $table = 'users';

    public function findByEmail(string $email): ?array
    {
        return $this->findBy('email', $email);
    }

    public function authenticate(string $email, string $password): ?array
    {
        $user = $this->findByEmail($email);
        
        if ($user && password_verify($password, $user['password'])) {
            $this->updateLastLogin($user['id']);
            unset($user['password']);
            return $user;
        }
        
        return null;
    }

    public function updateLastLogin(int $id): void
    {
        $this->db->query(
            "UPDATE {$this->table} SET last_login = NOW(), is_online = TRUE WHERE id = :id",
            ['id' => $id]
        );
    }

    public function setOffline(int $id): void
    {
        $this->db->query(
            "UPDATE {$this->table} SET is_online = FALSE WHERE id = :id",
            ['id' => $id]
        );
    }

    public function getByEntreprise(int $entrepriseId, ?string $role = null): array
    {
        $sql = "SELECT id, email, nom, prenom, telephone, role, is_active, is_online, last_login, created_at 
                FROM {$this->table} 
                WHERE entreprise_id = :entreprise_id";
        $params = ['entreprise_id' => $entrepriseId];
        
        if ($role) {
            $sql .= " AND role = :role";
            $params['role'] = $role;
        }
        
        $sql .= " ORDER BY created_at DESC";
        
        return $this->db->fetchAll($sql, $params);
    }

    public function getAgentsByEntreprise(int $entrepriseId): array
    {
        return $this->getByEntreprise($entrepriseId, 'agent');
    }

    public function getOnlineAgents(int $entrepriseId): array
    {
        $sql = "SELECT id, nom, prenom, is_online 
                FROM {$this->table} 
                WHERE entreprise_id = :entreprise_id 
                AND role = 'agent' 
                AND is_active = TRUE 
                AND is_online = TRUE";
        
        return $this->db->fetchAll($sql, ['entreprise_id' => $entrepriseId]);
    }

    public function countAgents(int $entrepriseId): int
    {
        $sql = "SELECT COUNT(*) as count FROM {$this->table} 
                WHERE entreprise_id = :entreprise_id AND role = 'agent'";
        $result = $this->db->fetch($sql, ['entreprise_id' => $entrepriseId]);
        return (int) ($result['count'] ?? 0);
    }

    public function createUser(array $data): int
    {
        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        return $this->create($data);
    }

    public function updatePassword(int $id, string $newPassword): bool
    {
        return $this->update($id, [
            'password' => password_hash($newPassword, PASSWORD_DEFAULT)
        ]) > 0;
    }
}
