<?php
ob_start();
error_reporting(0);
ini_set('display_errors', 0);

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

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

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

try {
    // Agregar columna si no existe
    $pdo->exec("ALTER TABLE device_telemetry ADD COLUMN IF NOT EXISTS app_usage_minutes INTEGER DEFAULT 0");
    
    if ($method === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);
        
        $device_id = $data['device_id'] ?? null;
        $user_id = $data['user_id'] ?? null;
        $is_active = $data['is_active'] ?? false;
        $storage_used = $data['storage_used'] ?? 0;
        $internet_usage = $data['internet_usage'] ?? 0;
        $conversation_count = $data['conversation_count'] ?? 0;
        $app_usage_minutes = $data['app_usage_minutes'] ?? 0;
        $last_activity = $data['last_activity'] ?? time() * 1000;
        
        if (!$device_id) {
            throw new Exception('device_id es requerido');
        }
        
        $stmt = $pdo->prepare("SELECT id FROM device_telemetry WHERE device_id = ?");
        $stmt->execute([$device_id]);
        $existing = $stmt->fetch();
        
        if ($existing) {
            $stmt = $pdo->prepare("
                UPDATE device_telemetry 
                SET user_id = ?, 
                    is_active = ?, 
                    storage_used_mb = ?, 
                    internet_usage_bytes = ?, 
                    conversation_count = ?,
                    app_usage_minutes = ?,
                    last_activity = to_timestamp(?/1000),
                    updated_at = CURRENT_TIMESTAMP
                WHERE device_id = ?
            ");
            $stmt->execute([
                $user_id,
                $is_active ? 't' : 'f',
                $storage_used,
                $internet_usage,
                $conversation_count,
                $app_usage_minutes,
                $last_activity,
                $device_id
            ]);
        } else {
            $stmt = $pdo->prepare("
                INSERT INTO device_telemetry 
                (device_id, user_id, is_active, storage_used_mb, internet_usage_bytes, conversation_count, app_usage_minutes, last_activity)
                VALUES (?, ?, ?, ?, ?, ?, ?, to_timestamp(?/1000))
            ");
            $stmt->execute([
                $device_id,
                $user_id,
                $is_active ? 't' : 'f',
                $storage_used,
                $internet_usage,
                $conversation_count,
                $app_usage_minutes,
                $last_activity
            ]);
        }
        
        echo json_encode(['success' => true, 'message' => 'Telemetría recibida']);
        
    } else if ($method === 'GET') {
        $action = $_GET['action'] ?? 'stats';
        
        if ($action === 'stats') {
            $stmt = $pdo->query("
                SELECT 
                    COUNT(*) as total_devices,
                    COUNT(CASE WHEN is_active = true AND last_activity > NOW() - INTERVAL '5 minutes' THEN 1 END) as active_devices,
                    COALESCE(SUM(storage_used_mb), 0) as total_storage_mb,
                    COALESCE(SUM(internet_usage_bytes), 0) as total_internet_bytes,
                    COALESCE(SUM(conversation_count), 0) as total_conversations
                FROM device_telemetry
            ");
            $stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->query("SELECT COUNT(*) as total_users FROM admin_users");
            $users = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'data' => [
                    'total_users' => (int)$users['total_users'],
                    'active_devices' => (int)$stats['active_devices'],
                    'pending_errors' => 0,
                    'total_storage_mb' => (int)$stats['total_storage_mb'],
                    'total_internet_mb' => round((int)$stats['total_internet_bytes'] / (1024 * 1024), 2),
                    'total_conversations' => (int)$stats['total_conversations']
                ]
            ]);
            
        } else if ($action === 'internet_traffic') {
            $stmt = $pdo->query("
                SELECT 
                    date_trunc('hour', updated_at) as hour,
                    SUM(internet_usage_bytes) / (1024 * 1024) as mb_used
                FROM device_telemetry
                WHERE updated_at >= NOW() - INTERVAL '24 hours'
                GROUP BY date_trunc('hour', updated_at)
                ORDER BY hour ASC
            ");
            $traffic = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode(['success' => true, 'data' => $traffic]);
            
        } else if ($action === 'conversations_flow') {
            $stmt = $pdo->query("
                SELECT 
                    date_trunc('hour', updated_at) as hour,
                    SUM(conversation_count) as count
                FROM device_telemetry
                WHERE updated_at >= NOW() - INTERVAL '24 hours'
                GROUP BY date_trunc('hour', updated_at)
                ORDER BY hour ASC
            ");
            $conversations = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode(['success' => true, 'data' => $conversations]);
            
        } else if ($action === 'app_usage') {
            $stmt = $pdo->query("
                SELECT 
                    device_id,
                    app_usage_minutes,
                    updated_at
                FROM device_telemetry
                WHERE app_usage_minutes > 0
                ORDER BY app_usage_minutes DESC
                LIMIT 10
            ");
            $usage = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode(['success' => true, 'data' => $usage]);
        }
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
