<?php
header('Content-Type: application/json; charset=UTF-8');
ini_set('display_errors', 1);
error_reporting(E_ALL);

try {
    $host = 'localhost';
    $dbname = 'ASPEL01';
    $user = 'root';
    $pass = 'root';

    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);

    // Parámetros de paginación
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 100;
    $offset = ($page - 1) * $per_page;

    // Traer los correos excluyendo los que tengan "aspel" antes o después del @
    $stmt = $pdo->prepare("
        SELECT CLAVE, TRIM(CORREO) AS CORREO
        FROM clie01
        WHERE CORREO IS NOT NULL 
          AND TRIM(CORREO) <> '' 
          AND CORREO NOT LIKE '%aspel%'
        ORDER BY CLAVE
        LIMIT :per_page OFFSET :offset
    ");
    $stmt->bindValue(':per_page', $per_page, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $correos = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Contar total de registros excluyendo "aspel"
    $total = $pdo->query("
        SELECT COUNT(*) 
        FROM clie01 
        WHERE CORREO IS NOT NULL 
          AND TRIM(CORREO) <> '' 
          AND CORREO NOT LIKE '%aspel%'
    ")->fetchColumn();

    echo json_encode([
        "success" => true,
        "data" => $correos,
        "total" => (int)$total,
        "page" => $page,
        "per_page" => $per_page
    ]);

} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Error: " . $e->getMessage()
    ]);
}
