<?php
/**
 * 用户反馈处理接口
 */
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

// 检查是否是 POST 请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取反馈数据
    $questionId = isset($_POST['questionId']) ? (int)$_POST['questionId'] : 0;
    $questionTitle = isset($_POST['questionTitle']) ? $_POST['questionTitle'] : '';
    $isHelpful = isset($_POST['isHelpful']) ? (int)$_POST['isHelpful'] : 0;
    $categoryId = isset($_POST['categoryId']) ? (int)$_POST['categoryId'] : 0;
    
    // 验证数据
    if (empty($questionTitle)) {
        echo json_encode(['status' => 'error', 'message' => 'The question cannot be empty.']);
        exit;
    }
    
    try {
        // 获取数据库连接
        $db = Typecho_Db::get();

        $request = Typecho_Request::getInstance();

        // 获取用户IP
        $ip =  $request->getIp();
        
//        // 检查是否已经提交过反馈
//        $exists = $db->fetchRow($db->select()
//            ->from('table.article_feedbacks')
//            ->where('question_id = ?', $questionId)
//            ->where('ip = ?', $ip)
//            ->limit(1));
//
//        if ($exists) {
//            echo json_encode(['status' => 'error', 'message' => '您已经对此问题进行过评价']);
//            exit;
//        }
        
        // 准备插入数据
        $data = [
            'question_id' => $questionId,
            'question_title' => $questionTitle,
            'category_id' => $categoryId,
            'is_helpful' => $isHelpful,
            'ip' => $ip,
            'created' => time()
        ];
        
        // 插入数据到数据库
        $db->query($db->insert('table.article_feedbacks')->rows($data));
        
        // 返回成功响应
        echo json_encode(['status' => 'success', 'message' => 'Thank you for your feedback!']);
    } catch (Exception $e) {
        // 返回错误响应
        echo json_encode(['status' => 'error', 'message' => 'An error occurred while saving feedback.']);
    }
    exit;
}

// 如果不是 POST 请求，返回错误
echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
exit;
