<?php
namespace App\Models;

use PDO;

/**
 * Modelo de usuarios
 */
class User extends BaseModel
{
    protected $table = 'users';
    
    /**
     * Crea un nuevo usuario
     */
    public function create($data)
    {
        $sql = "INSERT INTO users (username, password, full_name, role, active) 
                VALUES (:username, :password, :full_name, :role, :active)";
        
        $stmt = $this->db->prepare($sql);
        
        return $stmt->execute([
            'username' => $data['username'],
            'password' => password_hash($data['password'], PASSWORD_BCRYPT),
            'full_name' => $data['full_name'],
            'role' => $data['role'] ?? 'ayudante',
            'active' => $data['active'] ?? 1
        ]);
    }
    
    /**
     * Actualiza un usuario
     */
    public function update($id, $data)
    {
        $fields = [];
        $params = ['id' => $id];
        
        if (isset($data['username'])) {
            $fields[] = "username = :username";
            $params['username'] = $data['username'];
        }
        
        if (isset($data['password']) && !empty($data['password'])) {
            $fields[] = "password = :password";
            $params['password'] = password_hash($data['password'], PASSWORD_BCRYPT);
        }
        
        if (isset($data['full_name'])) {
            $fields[] = "full_name = :full_name";
            $params['full_name'] = $data['full_name'];
        }
        
        if (isset($data['role'])) {
            $fields[] = "role = :role";
            $params['role'] = $data['role'];
        }
        
        if (isset($data['active'])) {
            $fields[] = "active = :active";
            $params['active'] = $data['active'];
        }
        
        if (empty($fields)) {
            return false;
        }
        
        $sql = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = :id";
        $stmt = $this->db->prepare($sql);
        
        return $stmt->execute($params);
    }
    
    /**
     * Busca un usuario por nombre de usuario
     */
    public function findByUsername($username)
    {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$username]);
        return $stmt->fetch();
    }
    
    /**
     * Obtiene usuarios por rol
     */
    public function getByRole($role)
    {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE role = ? AND active = 1 ORDER BY full_name");
        $stmt->execute([$role]);
        return $stmt->fetchAll();
    }
    
    /**
     * Obtiene todos los ayudantes (incluyendo coordinadores) ordenados por sort_order
     */
    public function getAllHelpers()
    {
        $sql = "SELECT * FROM users 
                WHERE role IN ('ayudante', 'coordinador') 
                AND active = 1 
                ORDER BY sort_order ASC, id ASC";
        
        $stmt = $this->db->query($sql);
        return $stmt->fetchAll();
    }

    /**
     * Actualiza el orden de un usuario para la rotación
     * @param int $userId
     * @param int $position
     */
    public function updateOrder($userId, $position)
    {
        $stmt = $this->db->prepare("UPDATE users SET sort_order = ? WHERE id = ?");
        return $stmt->execute([$position, $userId]);
    }
    
    /**
     * Obtiene usuarios activos
     */
    public function getActive()
    {
        $stmt = $this->db->query("SELECT * FROM users WHERE active = 1 ORDER BY full_name");
        return $stmt->fetchAll();
    }
    
    /**
     * Verifica si un nombre de usuario ya existe
     */
    public function usernameExists($username, $excludeId = null)
    {
        if ($excludeId) {
            $stmt = $this->db->prepare("SELECT COUNT(*) as count FROM users WHERE username = ? AND id != ?");
            $stmt->execute([$username, $excludeId]);
        } else {
            $stmt = $this->db->prepare("SELECT COUNT(*) as count FROM users WHERE username = ?");
            $stmt->execute([$username]);
        }
        
        $result = $stmt->fetch();
        return $result['count'] > 0;
    }
    
    /**
     * Activa o desactiva un usuario
     */
    public function toggleActive($id)
    {
        $stmt = $this->db->prepare("UPDATE users SET active = NOT active WHERE id = ?");
        return $stmt->execute([$id]);
    }
}
