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

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

    if ($method === 'GET') {
        $device_id = $_GET['device_id'] ?? null;
        $action = $_GET['action'] ?? null;
        
        if ($action === 'devices') {
            $stmt = $db->query("
                SELECT DISTINCT 
                    t.device_id,
                    t.is_active,
                    t.last_activity,
                    t.app_usage_minutes,
                    COUNT(DISTINCT da.announcement_id) as announcements_received
                FROM telemetry t
                LEFT JOIN device_announcements da ON t.device_id = da.device_id
                GROUP BY t.device_id, t.is_active, t.last_activity, t.app_usage_minutes
                ORDER BY t.last_activity DESC
            ");
            $devices = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'data' => $devices]);
            exit;
        }
        
        if ($device_id) {
            $stmt = $db->prepare("
                SELECT a.* FROM announcements a
                WHERE a.status = 'active'
                AND (a.expires_at IS NULL OR a.expires_at > NOW())
                AND (a.target_devices = 'all' OR a.target_devices LIKE ?)
                AND a.id NOT IN (
                    SELECT announcement_id FROM device_announcements 
                    WHERE device_id = ? AND dismissed_at IS NOT NULL
                )
                ORDER BY a.priority DESC, a.created_at DESC
                LIMIT 1
            ");
            $stmt->execute(['%' . $device_id . '%', $device_id]);
            $announcement = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($announcement) {
                $stmt = $db->prepare("INSERT INTO device_announcements (device_id, announcement_id) VALUES (?, ?) ON CONFLICT DO NOTHING");
                $stmt->execute([$device_id, $announcement['id']]);
            }
            
            echo json_encode(['success' => true, 'data' => $announcement]);
        } else {
            $stmt = $db->query("
                SELECT a.*, 
                       au.username as created_by_name,
                       COUNT(DISTINCT da.device_id) as views_count
                FROM announcements a
                LEFT JOIN admin_users au ON a.created_by = au.id
                LEFT JOIN device_announcements da ON a.id = da.announcement_id
                GROUP BY a.id, au.username
                ORDER BY a.created_at DESC
            ");
            $announcements = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'data' => $announcements]);
        }
        
    } elseif ($method === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $targetDevices = 'all';
        if (isset($input['selected_devices']) && is_array($input['selected_devices']) && count($input['selected_devices']) > 0) {
            $targetDevices = implode(',', $input['selected_devices']);
        }
        
        $stmt = $db->prepare("
            INSERT INTO announcements (title, message, type, action, image_url, target_devices, priority, expires_at, block_duration, created_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $input['title'],
            $input['message'],
            $input['type'] ?? 'info',
            $input['action'] ?? 'none',
            $input['image_url'] ?? null,
            $targetDevices,
            $input['priority'] ?? 0,
            $input['expires_at'] ?? null,
            $input['block_duration'] ?? 0,
            $input['created_by'] ?? 1
        ]);
        
        echo json_encode(['success' => true, 'message' => 'Anuncio creado']);
        
    } elseif ($method === 'PUT') {
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (isset($input['dismiss'])) {
            $stmt = $db->prepare("UPDATE device_announcements SET dismissed_at = NOW() WHERE device_id = ? AND announcement_id = ?");
            $stmt->execute([$input['device_id'], $input['announcement_id']]);
        } else {
            $stmt = $db->prepare("UPDATE announcements SET status = ? WHERE id = ?");
            $stmt->execute([$input['status'], $input['id']]);
        }
        
        echo json_encode(['success' => true]);
        
    } elseif ($method === 'DELETE') {
        $input = json_decode(file_get_contents('php://input'), true);
        $stmt = $db->prepare("DELETE FROM announcements WHERE id = ?");
        $stmt->execute([$input['id']]);
        echo json_encode(['success' => true]);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
