<?php
require_once '../includes/auth.php';
require_once '../config/database.php';

$auth = new Auth();
$auth->requireLogin();

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

$database = new Database();
$db = $database->getConnection();

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'save_settings':
            $result = saveSettings($db, $input);
            break;
            
        case 'get_settings':
            $result = getSettings($db);
            break;
            
        default:
            throw new Exception('無效的操作');
    }
    
    echo json_encode($result);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

function saveSettings($db, $data) {
    $user_id = $_SESSION['user_id'];
    
    // 更新用戶設定
    $query = "UPDATE users SET 
              gpt_api_key = :gpt_api_key,
              default_language = :default_language,
              notification_email = :notification_email,
              updated_at = NOW()
              WHERE id = :user_id";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(':gpt_api_key', $data['gpt_api_key']);
    $stmt->bindParam(':default_language', $data['default_language']);
    $stmt->bindParam(':notification_email', $data['notification_email']);
    $stmt->bindParam(':user_id', $user_id);
    
    if ($stmt->execute()) {
        return [
            'success' => true,
            'message' => '設定保存成功'
        ];
    } else {
        throw new Exception('設定保存失敗');
    }
}

function getSettings($db) {
    $user_id = $_SESSION['user_id'];
    
    $query = "SELECT gpt_api_key, default_language, notification_email 
              FROM users WHERE id = :user_id";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(':user_id', $user_id);
    $stmt->execute();
    
    $settings = $stmt->fetch(PDO::FETCH_ASSOC);
    
    return [
        'success' => true,
        'data' => $settings
    ];
}
?>
