<?php
/**
 * Save Theme Preference
 */

session_start();
require_once '../config/database_optimized.php';

if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    http_response_code(401);
    exit('Unauthorized');
}

$db = DatabaseOptimized::getInstance();
$conn = $db->getConnection();

$current_user_id = $_SESSION['admin_user_id'] ?? null;
$theme = $_POST['theme'] ?? 'light';

if ($current_user_id && in_array($theme, ['light', 'dark'])) {
    try {
        $stmt = $conn->prepare("UPDATE admin_users SET theme = ? WHERE id = ?");
        $stmt->execute([$theme, $current_user_id]);
        
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid parameters']);
}
?>