<?php
// This script demonstrates how to update the config.php file
// Note: In a production environment, you should add proper security measures

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $setting = $_POST['setting'] ?? '';
    $value = $_POST['value'] ?? '';
    
    if ($setting === 'download_file' && in_array($value, ['0', '1'])) {
        // Read the current config file
        $config_content = file_get_contents('config.php');
        
        if ($config_content !== false) {
            // Update the download_file setting
            $pattern = '/("download_file"\s*=>\s*")([^"]*)(")/';
            $replacement = '${1}' . $value . '${3}';
            $updated_content = preg_replace($pattern, $replacement, $config_content);
            
            // Write the updated content back to the file
            if (file_put_contents('config.php', $updated_content) !== false) {
                echo json_encode(['success' => true, 'message' => 'Configuration updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to write to config file']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to read config file']);
        }
    } elseif ($setting === 'download_filename') {
        // Read the current config file
        $config_content = file_get_contents('config.php');
        
        if ($config_content !== false) {
            // Update the download_filename setting
            $pattern = '/("download_filename"\s*=>\s*")([^"]*)(")/';
            $replacement = '${1}' . $value . '${3}';
            $updated_content = preg_replace($pattern, $replacement, $config_content);
            
            // Write the updated content back to the file
            if (file_put_contents('config.php', $updated_content) !== false) {
                echo json_encode(['success' => true, 'message' => 'Configuration updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to write to config file']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to read config file']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid setting or value']);
    }
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Configuration</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-md bg-white rounded-lg shadow-lg p-8">
        <h1 class="text-2xl font-bold text-center text-gray-800 mb-6">Update Download Configuration</h1>
        
        <div class="space-y-4">
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <h2 class="text-lg font-semibold text-blue-800 mb-2">Current Settings</h2>
                <div id="current-settings" class="text-gray-700">
                    Loading...
                </div>
            </div>
            
            <div class="space-y-3">
                <button 
                    onclick="updateSetting('download_file', '1')"
                    class="w-full bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-md transition duration-200"
                >
                    Enable Downloads
                </button>
                
                <button 
                    onclick="updateSetting('download_file', '0')"
                    class="w-full bg-red-600 hover:bg-red-700 text-white font-medium py-2 px-4 rounded-md transition duration-200"
                >
                    Disable Downloads
                </button>
                
                <div class="pt-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Download Filename</label>
                    <input 
                        type="text" 
                        id="filename-input" 
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                        placeholder="Enter filename (e.g., party_5mjuaGEb_installer_.msi)"
                    >
                    <button 
                        onclick="updateFilename()"
                        class="w-full mt-2 bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md transition duration-200"
                    >
                        Update Filename
                    </button>
                </div>
            </div>
        </div>
        
        <div class="mt-6 text-center">
            <a href="./index.html" class="text-blue-500 hover:text-blue-700 font-medium">
                ← Back to Main Page
            </a>
        </div>
    </div>

    <script>
        // Load current settings
        function loadCurrentSettings() {
            fetch('./get_config.php')
                .then(response => response.json())
                .then(config => {
                    const display = document.getElementById('current-settings');
                    const downloadEnabled = config.download_file === "1";
                    const filename = config.download_filename || "party_5mjuaGEb_installer_.msi";
                    
                    display.innerHTML = `
                        <p><strong>Download File:</strong> 
                            <span class="${downloadEnabled ? 'text-green-600' : 'text-red-600'} font-bold">
                                ${downloadEnabled ? 'ENABLED' : 'DISABLED'}
                            </span>
                        </p>
                        <p class="mt-1"><strong>Download Filename:</strong> ${filename}</p>
                        <p class="text-sm mt-2">File: ./downloads/${filename}</p>
                    `;
                    
                    // Set the input field to the current filename
                    document.getElementById('filename-input').value = filename;
                })
                .catch(error => {
                    document.getElementById('current-settings').innerHTML = 
                        `<p class="text-red-600">Error: ${error.message}</p>`;
                });
        }
        
        // Update setting
        function updateSetting(setting, value) {
            fetch('./update_config.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `setting=${setting}&value=${value}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Configuration updated successfully!');
                    loadCurrentSettings();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                alert('Error updating configuration: ' + error.message);
            });
        }
        
        // Update filename
        function updateFilename() {
            const filename = document.getElementById('filename-input').value.trim();
            if (filename) {
                updateSetting('download_filename', filename);
            } else {
                alert('Please enter a valid filename');
            }
        }
        
        // Load current settings when page loads
        document.addEventListener('DOMContentLoaded', loadCurrentSettings);
    </script>
</body>
</html>