<?php
/**
 * 点赞/取消点赞 API
 */

// 记录错误日志
function logError($message) {
    $logFile = __DIR__ . '/../logs/api_error.log';
    $dir = dirname($logFile);
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
    $time = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$time] $message\n", FILE_APPEND);
}

try {
    // 禁用所有错误输出，确保只返回 JSON
    ini_set('display_errors', 0);
    ini_set('display_startup_errors', 0);
    error_reporting(0);
    
    // 清除任何之前的输出
    while (ob_get_level()) {
        ob_end_clean();
    }
    
    // 开始新的输出缓冲
    ob_start();
    
    // 设置 JSON 响应头
    header('Content-Type: application/json');
    
    $response = ['success' => false, 'message' => '未知错误'];
    
    // 检查必要的文件
    if (!file_exists(__DIR__ . '/../includes/functions.php')) {
        throw new Exception('必要的文件不存在');
    }
    
    require_once __DIR__ . '/../includes/functions.php';
    
    // 检查是否登录
    if (!isLoggedIn()) {
        $response = ['success' => false, 'message' => '请先登录'];
        echo json_encode($response);
        exit;
    }

    $user = getCurrentUser();
    if (!$user) {
        $response = ['success' => false, 'message' => '用户信息获取失败'];
        echo json_encode($response);
        exit;
    }
    
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    $targetType = isset($_POST['target_type']) ? $_POST['target_type'] : '';
    $targetId = isset($_POST['target_id']) ? intval($_POST['target_id']) : 0;

    if (!in_array($targetType, ['post', 'reply']) || $targetId <= 0) {
        $response = ['success' => false, 'message' => '参数错误'];
        echo json_encode($response);
        exit;
    }

    // 检查 likes 表是否存在
    try {
        $tableExists = db()->queryOne("SHOW TABLES LIKE 'likes'");
        if (!$tableExists) {
            db()->execute("CREATE TABLE IF NOT EXISTS likes (
                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                user_id INT UNSIGNED NOT NULL,
                target_type ENUM('post', 'reply') NOT NULL,
                target_id INT UNSIGNED NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY uk_user_target (user_id, target_type, target_id),
                INDEX idx_target (target_type, target_id),
                INDEX idx_user_id (user_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
        }
    } catch (Exception $e) {
        logError('创建 likes 表失败: ' . $e->getMessage());
        $response = ['success' => false, 'message' => '数据库错误'];
        echo json_encode($response);
        exit;
    }

    if ($action === 'like') {
        // 检查是否已经点赞
        try {
            $existing = db()->queryOne(
                "SELECT id FROM likes WHERE user_id = ? AND target_type = ? AND target_id = ?",
                [$user['id'], $targetType, $targetId]
            );
        } catch (Exception $e) {
            logError('查询点赞状态失败: ' . $e->getMessage());
            $existing = null;
        }
        
        if ($existing) {
            $response = ['success' => false, 'message' => '已经点赞过了'];
            echo json_encode($response);
            exit;
        }
        
        // 添加点赞
        try {
            db()->execute(
                "INSERT INTO likes (user_id, target_type, target_id) VALUES (?, ?, ?)",
                [$user['id'], $targetType, $targetId]
            );
        } catch (Exception $e) {
            logError('添加点赞失败: ' . $e->getMessage());
            $response = ['success' => false, 'message' => '点赞失败，请重试'];
            echo json_encode($response);
            exit;
        }
        
        // 获取目标作者ID并发送通知（不影响点赞成功）
        try {
            $targetUserId = null;
            $content = '';
            if ($targetType === 'post') {
                $target = db()->queryOne("SELECT user_id, title FROM posts WHERE id = ?", [$targetId]);
                if ($target && $target['user_id'] != $user['id']) {
                    $targetUserId = $target['user_id'];
                    $title = $target['title'];
                    $content = mb_substr($title, 0, 50) . (mb_strlen($title) > 50 ? '...' : '');
                }
            } else {
                $target = db()->queryOne("SELECT r.user_id, r.content, p.title FROM replies r JOIN posts p ON r.post_id = p.id WHERE r.id = ?", [$targetId]);
                if ($target && $target['user_id'] != $user['id']) {
                    $targetUserId = $target['user_id'];
                    $replyContent = $target['content'];
                    $content = '回复: ' . mb_substr($replyContent, 0, 50) . (mb_strlen($replyContent) > 50 ? '...' : '');
                }
            }
            
            // 发送通知
            if ($targetUserId) {
                try {
                    $tableExists = db()->queryOne("SHOW TABLES LIKE 'notifications'");
                    if (!$tableExists) {
                        db()->execute("CREATE TABLE IF NOT EXISTS notifications (
                            id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                            user_id INT UNSIGNED NOT NULL,
                            sender_id INT UNSIGNED DEFAULT NULL,
                            type ENUM('like', 'favorite', 'reply', 'follow') NOT NULL,
                            target_type ENUM('post', 'reply') DEFAULT NULL,
                            target_id INT UNSIGNED DEFAULT NULL,
                            content VARCHAR(255) DEFAULT NULL,
                            is_read TINYINT UNSIGNED DEFAULT 0,
                            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                            INDEX idx_user_id (user_id),
                            INDEX idx_is_read (is_read)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
                    }
                    
                    db()->execute(
                        "INSERT INTO notifications (user_id, sender_id, type, target_type, target_id, content) VALUES (?, ?, 'like', ?, ?, ?)",
                        [$targetUserId, $user['id'], $targetType, $targetId, $content]
                    );
                } catch (Exception $e) {
                    logError('发送通知失败: ' . $e->getMessage());
                }
            }
        } catch (Exception $e) {
            logError('获取目标信息失败: ' . $e->getMessage());
        }
        
        // 获取最新的点赞数
        try {
            $likeCount = db()->queryOne(
                "SELECT COUNT(*) as count FROM likes WHERE target_type = ? AND target_id = ?",
                [$targetType, $targetId]
            );
            $count = $likeCount ? intval($likeCount['count']) : 0;
        } catch (Exception $e) {
            logError('获取点赞数失败: ' . $e->getMessage());
            $count = 1;
        }

        // 检查勋章解锁条件并发送通知（给被点赞的用户）
        if ($targetType === 'post' && isset($targetUserId)) {
            try {
                checkAndNotifyMedalUnlock($targetUserId);
            } catch (Exception $e) {
                logError('检查勋章失败: ' . $e->getMessage());
            }
        }

        $response = [
            'success' => true,
            'message' => '点赞成功',
            'liked' => true,
            'count' => $count
        ];
        
    } elseif ($action === 'unlike') {
        // 取消点赞
        try {
            db()->execute(
                "DELETE FROM likes WHERE user_id = ? AND target_type = ? AND target_id = ?",
                [$user['id'], $targetType, $targetId]
            );
        } catch (Exception $e) {
            logError('取消点赞失败: ' . $e->getMessage());
            $response = ['success' => false, 'message' => '取消点赞失败'];
            echo json_encode($response);
            exit;
        }
        
        // 获取最新的点赞数
        try {
            $likeCount = db()->queryOne(
                "SELECT COUNT(*) as count FROM likes WHERE target_type = ? AND target_id = ?",
                [$targetType, $targetId]
            );
            $count = $likeCount ? intval($likeCount['count']) : 0;
        } catch (Exception $e) {
            logError('获取点赞数失败: ' . $e->getMessage());
            $count = 0;
        }

        $response = [
            'success' => true,
            'message' => '取消点赞成功',
            'liked' => false,
            'count' => $count
        ];
        
    } elseif ($action === 'check') {
        // 检查是否已点赞
        try {
            $existing = db()->queryOne(
                "SELECT id FROM likes WHERE user_id = ? AND target_type = ? AND target_id = ?",
                [$user['id'], $targetType, $targetId]
            );
            
            $likeCount = db()->queryOne(
                "SELECT COUNT(*) as count FROM likes WHERE target_type = ? AND target_id = ?",
                [$targetType, $targetId]
            );
            
            $response = [
                'success' => true,
                'liked' => !!$existing,
                'count' => $likeCount ? $likeCount['count'] : 0
            ];
        } catch (Exception $e) {
            logError('检查点赞状态失败: ' . $e->getMessage());
            $response = ['success' => false, 'message' => '检查失败'];
        }
        
    } else {
        $response = ['success' => false, 'message' => '未知操作: ' . $action];
    }

} catch (Exception $e) {
    logError('全局错误: ' . $e->getMessage() . '\n' . $e->getTraceAsString());
    $response = ['success' => false, 'message' => '服务器内部错误'];
}

// 清除缓冲区并输出 JSON
$output = ob_get_contents();
if ($output && strlen($output) > 0) {
    logError('意外的输出: ' . substr($output, 0, 500));
}
ob_clean();
echo json_encode($response);
ob_end_flush();
