<?php
/**
 * API - Obtener mensajes programados
 */

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

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');

requireAuthentication();

try {
    $db = Database::getInstance();
    
    // Parámetros de filtro
    $userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : null;
    $status = $_GET['status'] ?? null;
    $dateFrom = $_GET['date_from'] ?? null;
    $dateTo = $_GET['date_to'] ?? null;
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 100;
    $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;
    
    // Construir query
    $sql = "SELECT * FROM scheduled_messages_view WHERE 1=1";
    $params = [];
    
    if ($userId) {
        $sql .= " AND user_id = ?";
        $params[] = $userId;
    }
    
    if ($status) {
        $sql .= " AND status = ?";
        $params[] = $status;
    }
    
    if ($dateFrom) {
        $sql .= " AND scheduled_date >= ?";
        $params[] = $dateFrom;
    }
    
    if ($dateTo) {
        $sql .= " AND scheduled_date <= ?";
        $params[] = $dateTo;
    }
    
    // Ordenar por fecha más cercana primero
    $sql .= " ORDER BY scheduled_date ASC, scheduled_time ASC";
    
    // Paginación
    $sql .= " LIMIT ? OFFSET ?";
    $params[] = $limit;
    $params[] = $offset;
    
    $messages = $db->fetchAll($sql, $params);
    
    error_log('📋 get_scheduled_messages.php - Encontrados: ' . count($messages) . ' mensajes');
    error_log('🔍 SQL ejecutado: ' . $sql);
    error_log('📊 Parámetros: ' . json_encode($params));
    
    // Decodificar parámetros JSON
    foreach ($messages as &$message) {
        if ($message['template_parameters']) {
            $message['template_parameters'] = json_decode($message['template_parameters'], true);
        }
    }
    
    // Contar total
    $countSql = "SELECT COUNT(*) as total FROM scheduled_messages WHERE 1=1";
    $countParams = [];
    
    if ($userId) {
        $countSql .= " AND user_id = ?";
        $countParams[] = $userId;
    }
    
    if ($status) {
        $countSql .= " AND status = ?";
        $countParams[] = $status;
    }
    
    if ($dateFrom) {
        $countSql .= " AND scheduled_date >= ?";
        $countParams[] = $dateFrom;
    }
    
    if ($dateTo) {
        $countSql .= " AND scheduled_date <= ?";
        $countParams[] = $dateTo;
    }
    
    $countResult = $db->fetch($countSql, $countParams);
    $total = $countResult['total'] ?? 0;
    
    echo json_encode([
        'success' => true,
        'data' => $messages,
        'total' => $total,
        'limit' => $limit,
        'offset' => $offset
    ]);
    
} catch (Exception $e) {
    error_log("Error in get_scheduled_messages.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Error obteniendo mensajes programados'
    ]);
}
