<?php
/**
 * API - Obtener usuarios
 * Fecha: 13 de noviembre de 2025
 */

require_once '../config/config.php';

// Suprimir errores para obtener JSON limpio
error_reporting(E_ERROR | E_PARSE);

// Modo debug: desactivar autenticación si existe el parámetro debug
$debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';

if (!$debugMode) {
    requireAuthentication();
}

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');

try {
    $db = Database::getInstance();
    
    // Parámetros de paginación
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $limit = isset($_GET['limit']) ? max(1, min(100, intval($_GET['limit']))) : 20;
    $offset = ($page - 1) * $limit;
    
    // Búsqueda opcional
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $whereClause = '';
    $params = [];
    
    if (!empty($search)) {
        $whereClause = "WHERE u.phone_number LIKE ? OR u.name LIKE ? OR u.email LIKE ?";
        $searchParam = "%{$search}%";
        $params = [$searchParam, $searchParam, $searchParam];
    }
    
    // Contar total de registros
    $countQuery = "SELECT COUNT(*) as total FROM users u {$whereClause}";
    $totalResult = $db->fetch($countQuery, $params);
    $total = $totalResult['total'];
    $totalPages = ceil($total / $limit);
    
    // Obtener usuarios paginados
    $query = "SELECT 
            u.id,
            u.phone_number,
            u.name,
            u.email,
            u.status,
            u.current_menu_id,
            u.current_step,
            u.created_at,
            u.updated_at,
            m.name as current_menu
         FROM users u
         LEFT JOIN menus m ON u.current_menu_id = m.id
         {$whereClause}
         ORDER BY u.created_at DESC
         LIMIT ? OFFSET ?";
    
    $params[] = $limit;
    $params[] = $offset;
    
    $users = $db->fetchAll($query, $params);
    
    echo json_encode([
        'success' => true,
        'data' => $users,
        'pagination' => [
            'page' => $page,
            'limit' => $limit,
            'total' => $total,
            'totalPages' => $totalPages,
            'hasNext' => $page < $totalPages,
            'hasPrev' => $page > 1
        ]
    ]);
    
} catch (Exception $e) {
    error_log("Error in get_users.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Error interno del servidor'
    ]);
}
?>