<?php
/**
 * Theme Toggle API
 *
 * Manages user theme preference (light/dark mode)
 * Stores preference in session (similar to font-size toggle)
 *
 * Actions:
 * - get: Get current theme preference
 * - set: Set theme preference (light/dark/auto)
 * - reset: Reset to auto (system preference)
 */

require_once __DIR__ . '/../auto-prepend.php';

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

// Verify user is authenticated (WHP uses AUTH_USER constant)
if (!defined('AUTH_USER')) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit;
}

// Verify CSRF token for state-changing operations
$action = $_POST['action'] ?? $_GET['action'] ?? 'get';
if ($action !== 'get') {
    // Check for CSRF token in POST data first, then in X-CSRF-Token header
    $csrfToken = $_POST['csrf_token'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '');
    if (empty($csrfToken) || !hash_equals($_SESSION['csrf_token'] ?? '', $csrfToken)) {
        http_response_code(403);
        echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
        exit;
    }
}

try {
    switch ($action) {
        case 'get':
            // Get current theme preference
            $theme = $_SESSION['theme_preference'] ?? 'auto';
            echo json_encode([
                'success' => true,
                'theme' => $theme
            ]);
            break;

        case 'set':
            // Set theme preference
            $theme = $_POST['theme'] ?? '';

            // Validate theme value
            $validThemes = ['light', 'dark', 'auto'];
            if (!in_array($theme, $validThemes)) {
                http_response_code(400);
                echo json_encode([
                    'success' => false,
                    'error' => 'Invalid theme. Must be one of: light, dark, auto'
                ]);
                exit;
            }

            // Store in session
            $_SESSION['theme_preference'] = $theme;

            echo json_encode([
                'success' => true,
                'theme' => $theme,
                'message' => 'Theme preference updated'
            ]);
            break;

        case 'reset':
            // Reset to auto (system preference)
            $_SESSION['theme_preference'] = 'auto';

            echo json_encode([
                'success' => true,
                'theme' => 'auto',
                'message' => 'Theme preference reset to auto'
            ]);
            break;

        default:
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => 'Invalid action. Must be one of: get, set, reset'
            ]);
            break;
    }
} catch (Exception $e) {
    error_log("Theme toggle error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Internal server error'
    ]);
}
