<?php
session_start();

$configFile = __DIR__ . '/../js/config/master-config.json';

header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? $_GET['action'] ?? '';

error_log('Config Manager - Action: ' . $action);
error_log('Config Manager - File Path: ' . $configFile);
error_log('Config Manager - File Exists: ' . (file_exists($configFile) ? 'yes' : 'no'));

switch ($action) {
    case 'load':
        if (file_exists($configFile)) {
            $config = json_decode(file_get_contents($configFile), true);
            echo json_encode(['success' => true, 'data' => $config]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Config file not found']);
        }
        break;

    case 'updatePayoutMode':
        $mode = $input['mode'] ?? '';
        
        if (!in_array($mode, ['randomize', 'custom'])) {
            echo json_encode(['success' => false, 'message' => 'Invalid mode']);
            exit;
        }

        if (file_exists($configFile)) {
            $config = json_decode(file_get_contents($configFile), true);
            
            if ($mode === 'randomize') {
                $config['modes']['randomizePayoutControl'] = true;
                $config['modes']['customPayoutControl'] = false;
                $manualStatus = false;
            } else {
                $config['modes']['randomizePayoutControl'] = false;
                $config['modes']['customPayoutControl'] = true;
                $manualStatus = true;
            }

            $result = file_put_contents($configFile, json_encode($config, JSON_PRETTY_PRINT));
            if ($result !== false) {
                // Update all assets' manualPercentage.status for all users
                $assetCardsFile = __DIR__ . '/../js/database/activated-asset-cards.json';
                if (file_exists($assetCardsFile)) {
                    $assetData = json_decode(file_get_contents($assetCardsFile), true);
                    
                    foreach ($assetData as $username => &$userData) {
                        if (is_array($userData)) {
                            foreach ($userData as $assetName => &$asset) {
                                if (isset($asset['manualPercentage'])) {
                                    $asset['manualPercentage']['status'] = $manualStatus;
                                }
                            }
                        }
                    }
                    file_put_contents($assetCardsFile, json_encode($assetData, JSON_PRETTY_PRINT));
                }
                
                echo json_encode(['success' => true, 'data' => $config]);
            } else {
                $error = error_get_last();
                error_log('Config write error: ' . print_r($error, true));
                echo json_encode(['success' => false, 'message' => 'Failed to write config: ' . ($error['message'] ?? 'Unknown error')]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Config file not found']);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
?>
