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

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

session_start();
$pdo = require_once __DIR__ . '/../../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];

function response($data, $status = 200) {
    http_response_code($status);
    echo json_encode($data);
    exit;
}

function getJsonInput() {
    return json_decode(file_get_contents('php://input'), true);
}

function checkAuth() {
    if (empty($_SESSION['user_id'])) {
        response(['error' => 'Unauthorized'], 401);
    }
    return $_SESSION['user_id'];
}

// Get settings
if ($method === 'GET') {
    $userId = checkAuth();
    
    $stmt = $pdo->prepare('SELECT * FROM settings WHERE user_id = ?');
    $stmt->execute([$userId]);
    $settings = $stmt->fetch();
    
    if (!$settings) {
        // Create default settings
        $stmt = $pdo->prepare('INSERT INTO settings (user_id) VALUES (?)');
        $stmt->execute([$userId]);
        
        $stmt = $pdo->prepare('SELECT * FROM settings WHERE user_id = ?');
        $stmt->execute([$userId]);
        $settings = $stmt->fetch();
    }
    
    // Don't return API key in plain text
    unset($settings['gemini_api_key']);
    
    response(['settings' => $settings]);
}

// Update settings
elseif ($method === 'PUT') {
    $userId = checkAuth();
    $data = getJsonInput();
    
    $updates = [];
    $values = [];
    
    if (isset($data['dark_mode'])) {
        $updates[] = 'dark_mode = ?';
        $values[] = (bool)$data['dark_mode'];
    }
    
    if (isset($data['animations_enabled'])) {
        $updates[] = 'animations_enabled = ?';
        $values[] = (bool)$data['animations_enabled'];
    }
    
    if (isset($data['notifications_enabled'])) {
        $updates[] = 'notifications_enabled = ?';
        $values[] = (bool)$data['notifications_enabled'];
    }
    
    if (isset($data['default_session_length'])) {
        $updates[] = 'default_session_length = ?';
        $values[] = (int)$data['default_session_length'];
    }
    
    if (isset($data['gemini_api_key'])) {
        $updates[] = 'gemini_api_key = ?';
        $values[] = $data['gemini_api_key'];
    }
    
    if (empty($updates)) {
        response(['error' => 'Nothing to update'], 400);
    }
    
    $updates[] = 'updated_at = NOW()';
    $values[] = $userId;
    
    $sql = 'UPDATE settings SET ' . implode(', ', $updates) . ' WHERE user_id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($values);
    
    response([
        'success' => true,
        'message' => 'Settings updated successfully'
    ]);
}

else {
    response(['error' => 'Method not allowed'], 405);
}
?>
