<?php
/**
 * API: Historial de envíos masivos (broadcasts)
 * GET ?page=1&per_page=20
 */
require_once '../config/config.php';
requireAuthentication();

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Método no permitido']);
    exit;
}

$db = Database::getInstance();

// Crear tabla si no existe todavía
$db->getConnection()->exec("
    CREATE TABLE IF NOT EXISTS broadcast_history (
        id          INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        sent_at     DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
        message_type VARCHAR(20)  NOT NULL DEFAULT 'text',
        selection_type VARCHAR(20) NOT NULL DEFAULT 'filter',
        filter_used  VARCHAR(50)  NULL,
        template_name VARCHAR(120) NULL,
        message_preview TEXT       NULL,
        total_users  INT UNSIGNED NOT NULL DEFAULT 0,
        sent_count   INT UNSIGNED NOT NULL DEFAULT 0,
        error_count  INT UNSIGNED NOT NULL DEFAULT 0,
        sent_by      INT UNSIGNED NULL,
        sent_by_name VARCHAR(120) NULL,
        INDEX idx_sent_at (sent_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");

$page    = max(1, (int)($_GET['page']    ?? 1));
$perPage = min(100, max(5, (int)($_GET['per_page'] ?? 20)));
$offset  = ($page - 1) * $perPage;

try {
    $total = (int)$db->getConnection()
        ->query("SELECT COUNT(*) FROM broadcast_history")
        ->fetchColumn();

    $rows = $db->fetchAll(
        "SELECT * FROM broadcast_history ORDER BY sent_at DESC LIMIT ? OFFSET ?",
        [$perPage, $offset]
    );

    echo json_encode([
        'success'  => true,
        'data'     => $rows,
        'total'    => $total,
        'page'     => $page,
        'per_page' => $perPage,
        'pages'    => (int)ceil($total / $perPage),
    ]);
} catch (Exception $e) {
    error_log('get_broadcast_history.php: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Error interno del servidor']);
}
