<?php
ob_start();
require_once 'config.php';

$db = getDB();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // Obtener estadísticas REALES desde device_telemetry (igual que el dashboard)
    $stmt = $db->query("
        SELECT 
            COUNT(CASE WHEN is_active = true AND last_activity > NOW() - INTERVAL '5 minutes' THEN 1 END) as active_devices,
            COALESCE(SUM(conversation_count), 0) as total_conversations
        FROM device_telemetry
    ");
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Obtener contenido del landing
    $stmt = $db->query("SELECT section, title, subtitle, content FROM landing_content ORDER BY section");
    $content = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $content[$row['section']] = [
            'title' => $row['title'],
            'subtitle' => $row['subtitle'],
            'content' => json_decode($row['content'], true)
        ];
    }
    
    echo json_encode([
        'success' => true,
        'stats' => [
            'total_users' => (int)$stats['active_devices'],
            'total_conversations' => (int)$stats['total_conversations']
        ],
        'data' => $content
    ]);
    
} elseif ($method === 'PUT') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $stmt = $db->prepare("
        INSERT INTO landing_content (section, title, subtitle, content) 
        VALUES (?, ?, ?, ?)
        ON CONFLICT (section) 
        DO UPDATE SET title = ?, subtitle = ?, content = ?
    ");
    
    $contentJson = json_encode($input['content']);
    $stmt->execute([
        $input['section'],
        $input['title'],
        $input['subtitle'],
        $contentJson,
        $input['title'],
        $input['subtitle'],
        $contentJson
    ]);
    
    echo json_encode(['success' => true]);
}
