<?php
require_once 'db.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

$userId = $_GET['user_id'] ?? $input['user_id'] ?? 0;

if (!$userId) {
    http_response_code(401);
    echo json_encode(['message' => 'User ID required']);
    exit;
}

if ($method === 'GET') {
    $stmt = $mysqli->prepare("SELECT color_blindness_type, color_blindness_enabled FROM users WHERE id = ?");
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        echo json_encode([
            'type' => $row['color_blindness_type'] ?? 'none',
            'enabled' => (bool)$row['color_blindness_enabled']
        ]);
    } else {
        http_response_code(404);
        echo json_encode(['message' => 'User not found']);
    }

} elseif ($method === 'POST') {
    $type = $input['type'] ?? null;
    $enabled = isset($input['enabled']) ? (int)$input['enabled'] : null;

    if ($type === null && $enabled === null) {
        http_response_code(400);
        echo json_encode(['message' => 'No data to update']);
        exit;
    }

    $query = "UPDATE users SET ";
    $params = [];
    $types = "";

    if ($type !== null) {
        $query .= "color_blindness_type = ?, ";
        $params[] = $type;
        $types .= "s";
    }

    if ($enabled !== null) {
        $query .= "color_blindness_enabled = ?, ";
        $params[] = $enabled;
        $types .= "i";
    }

    $query = rtrim($query, ", ") . " WHERE id = ?";
    $params[] = $userId;
    $types .= "i";

    $stmt = $mysqli->prepare($query);
    $stmt->bind_param($types, ...$params);

    if ($stmt->execute()) {
        echo json_encode(['message' => 'Settings updated']);
    } else {
        http_response_code(500);
        echo json_encode(['message' => 'Error updating settings']);
    }
}
?>
