<?php
// Set content type to JSON
header('Content-Type: application/json');

// Check API permission
check_api_permission('user-resources');

require_once('/docker/whp/web/libs/mysqlmgmt.php');
$MySQLMgmt = new mysqlmgmt();

// Get request method and action
$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

// Handle different HTTP methods and actions
switch ($method) {
    case 'GET':
        switch ($action) {
            case 'list':
                // List all users with their resource allocations
                $users_result = $MySQLMgmt->getAllSystemUsersWithResources();
                if ($users_result['status'] === '0') {
                    echo json_encode(array(
                        'status' => 'success',
                        'data' => $users_result['users']
                    ));
                } else {
                    http_response_code(500);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => $users_result['msg']
                    ));
                }
                break;

            case 'usage':
                // Get resource usage for a specific user
                if (empty($_GET['username'])) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Username is required'
                    ));
                    break;
                }
                
                $username = $_GET['username'];
                $usage = $MySQLMgmt->getUserResourceUsage($username);
                echo json_encode(array(
                    'status' => 'success',
                    'data' => $usage
                ));
                break;

            default:
                http_response_code(400);
                echo json_encode(array(
                    'status' => 'error',
                    'message' => 'Invalid action. Use ?action=list to list users or ?action=usage&username=USER to get usage.'
                ));
                break;
        }
        break;

    case 'POST':
        // Get JSON input
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            http_response_code(400);
            echo json_encode(array(
                'status' => 'error',
                'message' => 'Invalid JSON input'
            ));
            break;
        }
        
        switch ($action) {
            case 'update':
                // Update user resource allocation with automatic quota syncing
                if (empty($input['username']) || !isset($input['max_cpu_allowance']) || !isset($input['max_memory_allowance'])) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Username, max_cpu_allowance, and max_memory_allowance are required'
                    ));
                    break;
                }
                
                // Validate resource limits
                $max_cpu = floatval($input['max_cpu_allowance']);
                $max_memory = intval($input['max_memory_allowance']);
                $max_disk_space = isset($input['max_disk_space']) ? intval($input['max_disk_space']) : null;
                $max_email_accounts = isset($input['max_email_accounts']) ? intval($input['max_email_accounts']) : null;
                
                if ($max_cpu < 0.25 || $max_cpu > 8) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'CPU allowance must be between 0.25 and 8 cores'
                    ));
                    break;
                }
                
                if ($max_memory < 256 || $max_memory > 8192) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Memory allowance must be between 256 MB and 8 GB'
                    ));
                    break;
                }
                
                if ($max_disk_space !== null && ($max_disk_space < 100 || $max_disk_space > 100000)) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Disk space must be between 100 MB and 100,000 MB'
                    ));
                    break;
                }
                
                // Use the proper updateClientAllowances method that includes quota syncing
                $result = $MySQLMgmt->updateClientAllowances(
                    $input['username'],
                    $max_cpu,
                    $max_memory,
                    null, // max_domains not needed for API
                    $max_disk_space,
                    $max_email_accounts
                );
                
                if ($result['status'] === '0') {
                    echo json_encode(array(
                        'status' => 'success',
                        'message' => $result['msg'],
                        'data' => array(
                            'username' => $input['username'],
                            'max_cpu_allowance' => $max_cpu,
                            'max_memory_allowance' => $max_memory,
                            'max_disk_space' => $max_disk_space,
                            'max_email_accounts' => $max_email_accounts
                        )
                    ));
                } else {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => $result['msg']
                    ));
                }
                break;
                
            case 'reset':
                // Reset user resources to default with automatic quota syncing
                if (empty($input['username'])) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Username is required'
                    ));
                    break;
                }
                
                // Use the proper updateClientAllowances method with default values
                $result = $MySQLMgmt->updateClientAllowances(
                    $input['username'],
                    0.5,    // Default CPU
                    512,    // Default memory
                    null,   // max_domains not needed
                    1000,   // Default disk space
                    0       // Default email accounts
                );
                
                if ($result['status'] === '0') {
                    echo json_encode(array(
                        'status' => 'success',
                        'message' => 'Resource allocation reset to default values',
                        'data' => array(
                            'username' => $input['username'],
                            'max_cpu_allowance' => 0.5,
                            'max_memory_allowance' => 512,
                            'max_disk_space' => 1000,
                            'max_email_accounts' => 0
                        )
                    ));
                } else {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => $result['msg']
                    ));
                }
                break;
                
            case 'bulk_update':
                // Bulk update multiple users with automatic quota syncing
                if (empty($input['updates']) || !is_array($input['updates'])) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Updates array is required'
                    ));
                    break;
                }
                
                $success_count = 0;
                $error_count = 0;
                $errors = [];
                
                foreach ($input['updates'] as $update) {
                    if (empty($update['username']) || !isset($update['max_cpu_allowance']) || !isset($update['max_memory_allowance'])) {
                        $error_count++;
                        $errors[] = "Invalid data for username: " . ($update['username'] ?? 'unknown');
                        continue;
                    }
                    
                    $max_cpu = floatval($update['max_cpu_allowance']);
                    $max_memory = intval($update['max_memory_allowance']);
                    $max_disk_space = isset($update['max_disk_space']) ? intval($update['max_disk_space']) : null;
                    $max_email_accounts = isset($update['max_email_accounts']) ? intval($update['max_email_accounts']) : null;
                    
                    if ($max_cpu < 0.25 || $max_cpu > 8 || $max_memory < 256 || $max_memory > 8192) {
                        $error_count++;
                        $errors[] = "Invalid resource limits for username: " . $update['username'];
                        continue;
                    }
                    
                    if ($max_disk_space !== null && ($max_disk_space < 100 || $max_disk_space > 100000)) {
                        $error_count++;
                        $errors[] = "Invalid disk space limit for username: " . $update['username'];
                        continue;
                    }
                    
                    // Use the proper updateClientAllowances method for each user
                    $result = $MySQLMgmt->updateClientAllowances(
                        $update['username'],
                        $max_cpu,
                        $max_memory,
                        null, // max_domains not needed
                        $max_disk_space,
                        $max_email_accounts
                    );
                    
                    if ($result['status'] === '0') {
                        $success_count++;
                    } else {
                        $error_count++;
                        $errors[] = "Failed to update " . $update['username'] . ": " . $result['msg'];
                    }
                }
                
                echo json_encode(array(
                    'status' => 'success',
                    'message' => "Bulk update completed: $success_count successful, $error_count errors",
                    'data' => array(
                        'success_count' => $success_count,
                        'error_count' => $error_count,
                        'errors' => $errors
                    )
                ));
                break;
                
            default:
                http_response_code(400);
                echo json_encode(array(
                    'status' => 'error',
                    'message' => 'Invalid action. Use update, reset, or bulk_update.'
                ));
                break;
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(array(
            'status' => 'error',
            'message' => 'Method not allowed. Use GET or POST.'
        ));
        break;
}
?> 