getConnection(); // ── Parámetros ──────────────────────────────────────────────────────── $estado = in_array($_GET['estado'] ?? '', ['aceptado', 'rechazado', 'pendiente']) ? $_GET['estado'] : null; $fecha = !empty($_GET['fecha']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['fecha']) ? $_GET['fecha'] : null; $phone = isset($_GET['phone']) ? trim($_GET['phone']) : ''; $page = max(1, (int)($_GET['page'] ?? 1)); $perPage = min(200, max(1, (int)($_GET['per_page'] ?? 50))); $offset = ($page - 1) * $perPage; // ── WHERE ───────────────────────────────────────────────────────────── $where = []; $params = []; if ($estado !== null) { $where[] = "ta.estado COLLATE utf8mb4_unicode_ci = :estado"; $params[':estado'] = $estado; } if ($fecha !== null) { $where[] = 'DATE(ta.fecha_envio) = :fecha'; $params[':fecha'] = $fecha; } if ($phone !== '') { $where[] = "ta.phone_number COLLATE utf8mb4_unicode_ci LIKE :phone"; $params[':phone'] = '%' . $phone . '%'; } $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : ''; // ── Stats (sin filtro de paginación) ────────────────────────────────── $statsSQL = " SELECT COALESCE(SUM(ta.estado COLLATE utf8mb4_unicode_ci = 'aceptado'), 0) AS aceptado, COALESCE(SUM(ta.estado COLLATE utf8mb4_unicode_ci = 'rechazado'), 0) AS rechazado, COALESCE(SUM(ta.estado COLLATE utf8mb4_unicode_ci = 'pendiente'), 0) AS pendiente, COUNT(*) AS total FROM terms_acceptance ta $whereClause "; $stmtStats = $pdo->prepare($statsSQL); $stmtStats->execute($params); $statsRow = $stmtStats->fetch(PDO::FETCH_ASSOC); $stats = [ 'aceptado' => (int)($statsRow['aceptado'] ?? 0), 'rechazado' => (int)($statsRow['rechazado'] ?? 0), 'pendiente' => (int)($statsRow['pendiente'] ?? 0), ]; $total = (int)($statsRow['total'] ?? 0); // ── Datos paginados ─────────────────────────────────────────────────── $dataSQL = " SELECT ta.id, ta.phone_number, u.name AS user_name, ta.estado, tv.version AS terms_version, ta.fecha_envio, ta.fecha_respuesta FROM terms_acceptance ta LEFT JOIN users u ON u.phone_number COLLATE utf8mb4_unicode_ci = ta.phone_number COLLATE utf8mb4_unicode_ci LEFT JOIN terms_versions tv ON tv.id = ta.terms_version_id $whereClause ORDER BY ta.fecha_envio DESC LIMIT :limit OFFSET :offset "; $stmtData = $pdo->prepare($dataSQL); foreach ($params as $k => $v) { $stmtData->bindValue($k, $v); } $stmtData->bindValue(':limit', $perPage, PDO::PARAM_INT); $stmtData->bindValue(':offset', $offset, PDO::PARAM_INT); $stmtData->execute(); $rows = $stmtData->fetchAll(PDO::FETCH_ASSOC); echo json_encode([ 'success' => true, 'data' => $rows, 'stats' => $stats, 'total' => $total, 'page' => $page, 'pages' => (int)ceil($total / $perPage), ], JSON_UNESCAPED_UNICODE); } catch (Exception $e) { http_response_code(500); echo json_encode(['success' => false, 'error' => $e->getMessage()]); }