<?php
/**
 * Router Monitoring API Controller
 * Provides monitoring data for dashboard
 */

_admin();
$ui->assign('_title', Lang::T('Router Monitoring'));
$ui->assign('_system_menu', 'monitoring');

$action = $routes['1'];
$ui->assign('_admin', $admin);

if (!in_array($admin['user_type'], ['SuperAdmin', 'Admin'])) {
    _alert(Lang::T('You do not have permission to access this page'), 'danger', "dashboard");
}

switch ($action) {
    case 'dashboard':
        $ui->assign('xfooter', '<script type="text/javascript" src="ui/lib/c/monitoring.js"></script>');
        $ui->display('monitoring.tpl');
        break;
        
    case 'get_router_status':
        $routerId = $_GET['router_id'] ?? null;
        $hours = $_GET['hours'] ?? 24;
        
        if ($routerId) {
            $data = getRouterMonitoringData($routerId, $hours);
        } else {
            $data = getAllRoutersMonitoringData($hours);
        }
        
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
        break;
        
    case 'get_router_history':
        $routerId = $_GET['router_id'] ?? null;
        $days = $_GET['days'] ?? 7;
        
        if (!$routerId) {
            http_response_code(400);
            echo json_encode(['error' => 'Router ID required']);
            exit;
        }
        
        $data = getRouterHistoryData($routerId, $days);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
        break;
        
    case 'get_alerts':
        $hours = $_GET['hours'] ?? 24;
        $data = getRecentAlerts($hours);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
        break;
        
    default:
        r2(U . 'monitoring/dashboard/', 's', '');
}

/**
 * Get monitoring data for specific router
 */
function getRouterMonitoringData($routerId, $hours = 24) {
    $cutoffTime = date('Y-m-d H:i:s', strtotime("-$hours hours"));
    
    $router = ORM::for_table('tbl_routers')->find_one($routerId);
    if (!$router) {
        return ['error' => 'Router not found'];
    }
    
    $monitoringData = ORM::for_table('tbl_router_monitoring')
        ->where('router_id', $routerId)
        ->where_gte('timestamp', $cutoffTime)
        ->order_by_desc('timestamp')
        ->find_many();
    
    $data = [
        'router' => [
            'id' => $router['id'],
            'name' => $router['name'],
            'ip_address' => $router['ip_address'],
            'status' => $router['status'],
            'last_check' => $router['last_check'],
            'last_error' => $router['last_error']
        ],
        'monitoring' => []
    ];
    
    foreach ($monitoringData as $record) {
        $data['monitoring'][] = [
            'timestamp' => $record['timestamp'],
            'ping_status' => (bool)$record['ping_status'],
            'api_status' => (bool)$record['api_status'],
            'uptime' => $record['uptime'],
            'free_memory' => (int)$record['free_memory'],
            'total_memory' => (int)$record['total_memory'],
            'cpu_load' => (int)$record['cpu_load'],
            'temperature' => $record['temperature'],
            'voltage' => $record['voltage'],
            'error' => $record['error']
        ];
    }
    
    return $data;
}

/**
 * Get monitoring data for all routers
 */
function getAllRoutersMonitoringData($hours = 24) {
    $cutoffTime = date('Y-m-d H:i:s', strtotime("-$hours hours"));
    
    $routers = ORM::for_table('tbl_routers')->where('enabled', '1')->find_many();
    $data = [];
    
    foreach ($routers as $router) {
        $latestData = ORM::for_table('tbl_router_monitoring')
            ->where('router_id', $router['id'])
            ->where_gte('timestamp', $cutoffTime)
            ->order_by_desc('timestamp')
            ->find_one();
        
        $data[] = [
            'router' => [
                'id' => $router['id'],
                'name' => $router['name'],
                'ip_address' => $router['ip_address'],
                'status' => $router['status'],
                'last_check' => $router['last_check'],
                'last_error' => $router['last_error']
            ],
            'latest_data' => $latestData ? [
                'timestamp' => $latestData['timestamp'],
                'ping_status' => (bool)$latestData['ping_status'],
                'api_status' => (bool)$latestData['api_status'],
                'uptime' => $latestData['uptime'],
                'free_memory' => (int)$latestData['free_memory'],
                'total_memory' => (int)$latestData['total_memory'],
                'cpu_load' => (int)$latestData['cpu_load'],
                'temperature' => $latestData['temperature'],
                'voltage' => $latestData['voltage'],
                'error' => $latestData['error']
            ] : null
        ];
    }
    
    return $data;
}

/**
 * Get historical data for router
 */
function getRouterHistoryData($routerId, $days = 7) {
    $cutoffTime = date('Y-m-d H:i:s', strtotime("-$days days"));
    
    $data = ORM::for_table('tbl_router_monitoring')
        ->where('router_id', $routerId)
        ->where_gte('timestamp', $cutoffTime)
        ->order_by_asc('timestamp')
        ->find_many();
    
    $result = [];
    foreach ($data as $record) {
        $result[] = [
            'timestamp' => $record['timestamp'],
            'ping_status' => (bool)$record['ping_status'],
            'api_status' => (bool)$record['api_status'],
            'cpu_load' => (int)$record['cpu_load'],
            'memory_usage' => $record['total_memory'] ? 
                round((($record['total_memory'] - $record['free_memory']) / $record['total_memory']) * 100, 1) : 0,
            'temperature' => $record['temperature'],
            'voltage' => $record['voltage']
        ];
    }
    
    return $result;
}

/**
 * Get recent alerts
 */
function getRecentAlerts($hours = 24) {
    $cutoffTime = date('Y-m-d H:i:s', strtotime("-$hours hours"));
    
    $alerts = ORM::for_table('tbl_router_monitoring')
        ->where_gte('timestamp', $cutoffTime)
        ->where_not_null('error')
        ->order_by_desc('timestamp')
        ->find_many();
    
    $result = [];
    foreach ($alerts as $alert) {
        $router = ORM::for_table('tbl_routers')->find_one($alert['router_id']);
        $result[] = [
            'timestamp' => $alert['timestamp'],
            'router_name' => $router ? $router['name'] : 'Unknown',
            'error' => $alert['error'],
            'cpu_load' => $alert['cpu_load'],
            'temperature' => $alert['temperature']
        ];
    }
    
    return $result;
}
?>
