<?php
require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$endpoint = $_GET['endpoint'] ?? '';

switch ($endpoint) {
    case 'dashboard':
        getDashboardStats();
        break;
    case 'users':
        handleUsers($method);
        break;
    case 'errors':
        handleErrors($method);
        break;
    case 'announcements':
        handleAnnouncements($method);
        break;
    case 'interactions':
        getInteractions();
        break;
    case 'learning':
        getLearningData();
        break;
    default:
        http_response_code(404);
        echo json_encode(['error' => 'Endpoint not found']);
}

function getDashboardStats() {
    $db = getDB();
    
    // Usuarios totales y activos
    $stmt = $db->query("SELECT 
        COUNT(*) as total_users,
        SUM(CASE WHEN last_active >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 ELSE 0 END) as active_users,
        SUM(CASE WHEN install_date >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) as new_users_month
    FROM app_users");
    $userStats = $stmt->fetch();
    
    // Errores pendientes
    $stmt = $db->query("SELECT COUNT(*) as pending_errors FROM error_reports WHERE status = 'new'");
    $errorStats = $stmt->fetch();
    
    // Interacciones hoy
    $stmt = $db->query("SELECT COUNT(*) as today_interactions FROM user_interactions WHERE DATE(timestamp) = CURDATE()");
    $interactionStats = $stmt->fetch();
    
    // Métricas de los últimos 7 días
    $stmt = $db->query("SELECT metric_date, active_users, total_interactions, total_errors 
        FROM daily_metrics 
        ORDER BY metric_date DESC 
        LIMIT 7");
    $weeklyMetrics = $stmt->fetchAll();
    
    // Top interacciones
    $stmt = $db->query("SELECT interaction_type, COUNT(*) as count 
        FROM user_interactions 
        WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        GROUP BY interaction_type 
        ORDER BY count DESC 
        LIMIT 5");
    $topInteractions = $stmt->fetchAll();
    
    echo json_encode([
        'success' => true,
        'data' => [
            'users' => $userStats,
            'errors' => $errorStats,
            'interactions' => $interactionStats,
            'weekly_metrics' => array_reverse($weeklyMetrics),
            'top_interactions' => $topInteractions
        ]
    ]);
}

function handleUsers($method) {
    $db = getDB();
    
    if ($method === 'GET') {
        $page = $_GET['page'] ?? 1;
        $limit = 20;
        $offset = ($page - 1) * $limit;
        
        $stmt = $db->prepare("SELECT * FROM app_users ORDER BY last_active DESC LIMIT ? OFFSET ?");
        $stmt->execute([$limit, $offset]);
        $users = $stmt->fetchAll();
        
        $stmt = $db->query("SELECT COUNT(*) as total FROM app_users");
        $total = $stmt->fetch()['total'];
        
        echo json_encode([
            'success' => true,
            'data' => $users,
            'pagination' => [
                'page' => (int)$page,
                'total' => (int)$total,
                'pages' => ceil($total / $limit)
            ]
        ]);
    }
}

function handleErrors($method) {
    $db = getDB();
    
    if ($method === 'GET') {
        $status = $_GET['status'] ?? 'all';
        
        $sql = "SELECT e.*, u.user_name, u.device_model 
                FROM error_reports e 
                LEFT JOIN app_users u ON e.device_id = u.device_id";
        
        if ($status !== 'all') {
            $sql .= " WHERE e.status = :status";
        }
        
        $sql .= " ORDER BY e.timestamp DESC LIMIT 50";
        
        $stmt = $db->prepare($sql);
        if ($status !== 'all') {
            $stmt->execute(['status' => $status]);
        } else {
            $stmt->execute();
        }
        
        $errors = $stmt->fetchAll();
        
        echo json_encode([
            'success' => true,
            'data' => $errors
        ]);
    } elseif ($method === 'PUT') {
        $data = json_decode(file_get_contents('php://input'), true);
        $id = $data['id'] ?? null;
        $status = $data['status'] ?? null;
        $notes = $data['notes'] ?? '';
        
        if ($id && $status) {
            $stmt = $db->prepare("UPDATE error_reports SET status = ?, notes = ? WHERE id = ?");
            $stmt->execute([$status, $notes, $id]);
            
            echo json_encode(['success' => true, 'message' => 'Error updated']);
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'Missing parameters']);
        }
    }
}

function handleAnnouncements($method) {
    $db = getDB();
    
    if ($method === 'GET') {
        $stmt = $db->query("SELECT * FROM announcements ORDER BY created_at DESC LIMIT 50");
        $announcements = $stmt->fetchAll();
        
        echo json_encode([
            'success' => true,
            'data' => $announcements
        ]);
    } elseif ($method === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);
        
        $stmt = $db->prepare("INSERT INTO announcements (title, message, type, target_audience, scheduled_for) 
                              VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $data['title'],
            $data['message'],
            $data['type'] ?? 'info',
            $data['target_audience'] ?? 'all',
            $data['scheduled_for'] ?? null
        ]);
        
        echo json_encode(['success' => true, 'message' => 'Announcement created', 'id' => $db->lastInsertId()]);
    }
}

function getInteractions() {
    $db = getDB();
    
    $stmt = $db->query("SELECT 
        DATE(timestamp) as date,
        COUNT(*) as total,
        AVG(response_time_ms) as avg_response_time
        FROM user_interactions 
        WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        GROUP BY DATE(timestamp)
        ORDER BY date ASC");
    
    $interactions = $stmt->fetchAll();
    
    echo json_encode([
        'success' => true,
        'data' => $interactions
    ]);
}

function getLearningData() {
    $db = getDB();
    
    $stmt = $db->query("SELECT 
        learning_type,
        COUNT(*) as count,
        AVG(confidence_score) as avg_confidence
        FROM ai_learning_data 
        GROUP BY learning_type");
    
    $learning = $stmt->fetchAll();
    
    echo json_encode([
        'success' => true,
        'data' => $learning
    ]);
}
