<?php
require_once 'conexion/conexion.php';

header('Content-Type: application/json');

function obtenerIP() {
    if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return $_SERVER['HTTP_CF_CONNECTING_IP'];
    }
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
    }
    return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}

try {
    $ip = obtenerIP();

    $stmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM registros 
        WHERE ip_usuario = :ip 
        AND fecha_hora >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
    ");

    $stmt->execute([':ip' => $ip]);
    $conteo = $stmt->fetchColumn();

    echo json_encode(['envios' => (int)$conteo]);

} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}