<?php
require_once dirname(__DIR__) . '/core/lib/session.php';
cmsStartSession();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

require_once dirname(__DIR__) . '/core/db/db.php';
require_once dirname(__DIR__) . '/core/lib/common.php';

$db = \Core\Db\DB::getInstance();
$favoriteTable = $db->table('favorite');
cmsEnsureFavoriteTable($db);

$memberId = intval($_SESSION['member_id'] ?? 0);
if ($memberId <= 0) {
    echo json_encode(['code' => 401, 'msg' => '请先登录', 'data' => []], JSON_UNESCAPED_UNICODE);
    exit;
}

$action = trim((string) ($_POST['action'] ?? $_GET['action'] ?? 'status'));
if (in_array($action, ['add', 'remove', 'toggle'], true)) {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['code' => 405, 'msg' => '璇锋敹鍒板悎鍙厑璁?POST', 'data' => []], JSON_UNESCAPED_UNICODE);
        exit;
    }
    requireMemberCsrfToken(true);
}
$type = trim((string) ($_POST['type'] ?? $_GET['type'] ?? ''));
$contentId = intval($_POST['content_id'] ?? $_GET['content_id'] ?? 0);

$typeMap = [
    'product_id' => 'product',
    'article_id' => 'article',
    'download_id' => 'download',
    'recruit_id' => 'recruit',
];
foreach ($typeMap as $param => $mappedType) {
    $value = intval($_POST[$param] ?? $_GET[$param] ?? 0);
    if ($value > 0) {
        $type = $mappedType;
        $contentId = $value;
        break;
    }
}
if ($type === '') {
    $type = 'product';
}

$allowedTypes = ['product', 'article', 'download', 'recruit'];
if (!in_array($type, $allowedTypes, true) || $contentId <= 0) {
    echo json_encode(['code' => 400, 'msg' => '参数错误', 'data' => []], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($type === 'product' && $action !== 'remove' && intval(getSiteConfig('product_page_favorite', '1')) !== 1) {
    echo json_encode(['code' => 403, 'msg' => '收藏功能未开启', 'data' => []], JSON_UNESCAPED_UNICODE);
    exit;
}

$tableMap = [
    'product' => 'product',
    'article' => 'article',
    'download' => 'download',
    'recruit' => 'recruit',
];
$table = $tableMap[$type];
$item = $db->fetch("SELECT id FROM {$db->table($table)} WHERE id = ? LIMIT 1", [$contentId]);
if (!$item) {
    echo json_encode(['code' => 404, 'msg' => '内容不存在', 'data' => []], JSON_UNESCAPED_UNICODE);
    exit;
}

$favoriteRow = $db->fetch(
    "SELECT id FROM {$favoriteTable} WHERE member_id = ? AND content_id = ? AND content_type = ?",
    [$memberId, $contentId, $type]
);

if ($action === 'status') {
    echo json_encode(['code' => 200, 'msg' => 'ok', 'data' => ['favorited' => !empty($favoriteRow)]], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'add') {
    if (!$favoriteRow) {
        $db->insert('favorite', [
            'member_id' => $memberId,
            'content_id' => $contentId,
            'content_type' => $type,
            'create_time' => time(),
        ]);
    }
    echo json_encode(['code' => 200, 'msg' => '收藏成功', 'data' => ['favorited' => true]], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'remove') {
    if ($favoriteRow) {
        $db->delete('favorite', 'id = ?', [$favoriteRow['id']]);
    }
    echo json_encode(['code' => 200, 'msg' => '已取消收藏', 'data' => ['favorited' => false]], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'toggle') {
    if ($favoriteRow) {
        $db->delete('favorite', 'id = ?', [$favoriteRow['id']]);
        echo json_encode(['code' => 200, 'msg' => '已取消收藏', 'data' => ['favorited' => false]], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $db->insert('favorite', [
        'member_id' => $memberId,
        'content_id' => $contentId,
        'content_type' => $type,
        'create_time' => time(),
    ]);
    echo json_encode(['code' => 200, 'msg' => '收藏成功', 'data' => ['favorited' => true]], JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode(['code' => 404, 'msg' => '未知操作', 'data' => []], JSON_UNESCAPED_UNICODE);
