<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */


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);
}

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

$db = \Core\Db\DB::getInstance();
$result = ['code' => 0, 'msg' => ''];

// 提交留言
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'submit') {
        $title = trim($_POST['title'] ?? '');
        $content = trim($_POST['content'] ?? '');
        $name = trim($_POST['name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $company = trim($_POST['company'] ?? '');
        
        if (empty($title) || empty($content)) {
            $result = ['code' => 400, 'msg' => '标题和内容不能为空'];
        } else {
            $ip = getClientIp();
            $db->insert('guestbook', [
                'title' => $title,
                'content' => $content,
                'name' => $name,
                'phone' => $phone,
                'email' => $email,
                'company' => $company,
                'ip' => $ip,
                'status' => 0,
                'create_time' => time()
            ]);
            sendAdminMessage('💬 新留言：' . ($title ?: '无标题'), "姓名：{$name}\n联系方式：{$phone}\n邮箱：{$email}\n公司：{$company}\nIP：{$ip}\n内容：{$content}", $name);
            $result = ['code' => 200, 'msg' => '提交成功，我们会尽快回复您！'];
        }
    }
    
    // 搜索
    elseif ($action === 'search') {
        $keyword = trim($_POST['keyword'] ?? '');
        $type = $_POST['type'] ?? 'article';
        
        if (empty($keyword)) {
            $result = ['code' => 400, 'msg' => '请输入搜索关键词'];
        } else {
            $keyword = '%' . $keyword . '%';
            
            if ($type === 'article') {
                $list = $db->fetchAll(
                    "SELECT a.*, c.channel_name FROM {$db->table('article')} a 
                     LEFT JOIN {$db->table('channel')} c ON a.channel_id = c.id 
                     WHERE a.status = 1 AND (a.title LIKE ? OR a.summary LIKE ?) 
                     ORDER BY a.create_time DESC LIMIT 10",
                    [$keyword, $keyword]
                );
            } else {
                $list = $db->fetchAll(
                    "SELECT * FROM {$db->table('product')} WHERE status = 1 AND (title LIKE ? OR summary LIKE ?) 
                     ORDER BY create_time DESC LIMIT 10",
                    [$keyword, $keyword]
                );
            }
            
            $result = ['code' => 200, 'msg' => '搜索成功', 'data' => $list];
        }
    }
    
    // 获取评论
    elseif ($action === 'get_comments') {
        $target_id = intval($_POST['target_id'] ?? 0);
        $type = $_POST['type'] ?? 'article';
        
        $table = $type === 'article' ? 'article' : 'product';
        $comments = $db->fetchAll(
            "SELECT * FROM {$db->table('comment')} WHERE target_id = ? AND target_type = ? AND status = 1 ORDER BY id DESC LIMIT 20",
            [$target_id, $type]
        );
        
        $result = ['code' => 200, 'msg' => '', 'data' => $comments];
    }
    
    // 提交评论
    elseif ($action === 'add_comment') {
        $target_id = intval($_POST['target_id'] ?? 0);
        $type = $_POST['type'] ?? 'article';
        $content = trim($_POST['content'] ?? '');
        $author = trim($_POST['author'] ?? '游客');
        
        if (empty($content)) {
            $result = ['code' => 400, 'msg' => '评论内容不能为空'];
        } elseif ($target_id <= 0) {
            $result = ['code' => 400, 'msg' => '参数错误'];
        } else {
            $db->insert('comment', [
                'target_id' => $target_id,
                'target_type' => $type,
                'content' => $content,
                'author' => $author,
                'ip' => getClientIp(),
                'create_time' => time()
            ]);
            sendAdminMessage('💬 新评论来自：' . $author, "评论对象ID：{$target_id}（类型：{$type}）\n评论者：{$author}\nIP：" . getClientIp() . "\n内容：{$content}", $author);
            $result = ['code' => 200, 'msg' => '评论成功'];
        }
    }
    
    // 会员注册
    elseif ($action === 'register') {
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');
        $email = trim($_POST['email'] ?? '');
        
        if (empty($username) || empty($password)) {
            $result = ['code' => 400, 'msg' => '用户名和密码不能为空'];
        } elseif (strlen($username) < 4 || strlen($username) > 20) {
            $result = ['code' => 400, 'msg' => '用户名长度必须在4-20个字符之间'];
        } else {
            // 检查是否已存在
            $exists = $db->fetch("SELECT id FROM {$db->table('member')} WHERE username = ?", [$username]);
            if ($exists) {
                $result = ['code' => 400, 'msg' => '用户名已被注册'];
            } else {
                $defaultGroup = $db->fetch("SELECT id FROM {$db->table('member_group')} WHERE is_default = 1 LIMIT 1");
                $groupId = $defaultGroup ? $defaultGroup['id'] : 1;
                
                $db->insert('member', [
                    'username' => $username,
                    'password' => password_hash($password, PASSWORD_DEFAULT),
                    'email' => $email,
                    'group_id' => $groupId,
                    'reg_ip' => getClientIp(),
                    'reg_time' => time(),
                    'is_enabled' => 1
                ]);
                
                $result = ['code' => 200, 'msg' => '注册成功'];
            }
        }
    }
    
    // 会员登录
    elseif ($action === 'login') {
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');
        
        if (empty($username) || empty($password)) {
            $result = ['code' => 400, 'msg' => '请输入用户名和密码'];
        } else {
            $member = $db->fetch("SELECT * FROM {$db->table('member')} WHERE username = ? AND is_enabled = 1", [$username]);
            if (!$member) {
                $result = ['code' => 400, 'msg' => '用户不存在或已被禁用'];
            } elseif (!password_verify($password, $member['password']) && md5($password) !== $member['password']) {
                $result = ['code' => 400, 'msg' => '密码错误'];
            } else {
                $_SESSION['member_id'] = $member['id'];
                $_SESSION['member_name'] = $member['username'];
                $_SESSION['member_nickname'] = $member['nickname'];
                $_SESSION['member_group_id'] = $member['group_id'];
                
                $db->update('member', [
                    'last_login_time' => time(),
                    'last_login_ip' => getClientIp()
                ], 'id = ?', [$member['id']]);
                
                $result = ['code' => 200, 'msg' => '登录成功'];
            }
        }
    }
    
    // 退出登录
    elseif ($action === 'logout') {
        unset($_SESSION['member_id']);
        unset($_SESSION['member_name']);
        unset($_SESSION['member_nickname']);
        unset($_SESSION['member_group_id']);
        
        $result = ['code' => 200, 'msg' => '退出成功'];
    }
    
    else {
        $result = ['code' => 404, 'msg' => '未知操作'];
    }
} else {
    $result = ['code' => 405, 'msg' => '请求方法不允许'];
}

echo json_encode($result, JSON_UNESCAPED_UNICODE);