<?php
/**
 * API - Eliminar mensaje programado
 */

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

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: DELETE, POST');
header('Access-Control-Allow-Headers: Content-Type');

requireAuthentication();

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        // Intentar obtener de query params
        $id = isset($_GET['id']) ? intval($_GET['id']) : null;
    } else {
        $id = isset($input['id']) ? intval($input['id']) : null;
    }
    
    if (!$id) {
        throw new Exception('ID de mensaje programado requerido');
    }
    
    $db = Database::getInstance();
    
    // Verificar que existe
    $existing = $db->fetch("SELECT * FROM scheduled_messages WHERE id = ?", [$id]);
    
    if (!$existing) {
        throw new Exception('Mensaje programado no encontrado');
    }
    
    // Eliminar
    $db->execute("DELETE FROM scheduled_messages WHERE id = ?", [$id]);
    
    writeLog('INFO', "Mensaje programado eliminado: ID={$id}");
    
    echo json_encode([
        'success' => true,
        'message' => 'Mensaje programado eliminado exitosamente'
    ]);
    
} catch (Exception $e) {
    error_log("Error in delete_scheduled_message.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
