<?php
/**
 * 在线客服系统 - 前端API接口（需登录）
 * 记录用户咨询日志
 */
// 开启输出缓冲，防止common.php输出空白字符
ob_start();
include(dirname(__DIR__) . '/includes/common.php');
ob_end_clean();

@header('Content-Type: application/json; charset=UTF-8');

// 登录验证
if($islogin2 != 1) {
    exit(json_encode(array('code' => -1, 'msg' => '请先登录')));
}

$act = isset($_GET['act']) ? daddslashes($_GET['act']) : null;
$user_id = intval($userrow['zid']);
$user_qq = daddslashes($userrow['qq'] ?? '');

switch($act) {

// ==================== 获取配置 ====================
case 'get_config':
    // 处理顶部信息（支持PHP代码执行和变量替换）
    $topInfo = '';
    if (!empty($conf['cs_top_info'])) {
        $content = $conf['cs_top_info'];
        // 如果没有 <?php 标签，进行变量替换
        if (strpos($content, '<?php') === false && strpos($content, '<?') === false) {
            // 替换 $date 变量
            $content = str_replace('$date', '<?php echo $date; ?>', $content);
            // 替换 $conf['xxx'] 变量
            $content = preg_replace_callback('/\$conf\[\'(\w+)\'\]/', function($m) {
                return '<?php echo isset($conf[\'' . $m[1] . '\']) ? $conf[\'' . $m[1] . '\'] : \'\'; ?>';
            }, $content);
            // 替换 $userrow['xxx'] 变量
            $content = preg_replace_callback('/\$userrow\[\'(\w+)\'\]/', function($m) {
                return '<?php echo isset($userrow[\'' . $m[1] . '\']) ? $userrow[\'' . $m[1] . '\'] : \'\'; ?>';
            }, $content);
        }
        ob_start();
        eval('?>' . $content);
        $topInfo = ob_get_clean();
    }

    exit(json_encode(array(
        'code' => 1,
        'data' => array(
            'enabled' => $conf['cs_enabled'] ?? '1',
            'icon' => $conf['cs_bubble_icon'] ?? '',
            'welcome' => $conf['cs_welcome_msg'] ?? '您好，欢迎咨询！请选择下方问题或直接输入。',
            'position' => $conf['cs_bubble_position'] ?? 'right',
            'noMatchMsg' => $conf['cs_no_match_msg'] ?? '',
            'topInfo' => $topInfo
        )
    )));
break;

// ==================== 获取热键列表 ====================
case 'get_hotkeys':
    // 获取普通问答热键
    $rs = $DB->query("SELECT id, question, trigger_keyword FROM pre_customer_service_qa WHERE status='1' AND is_hotkey='1' AND type='0' ORDER BY sort ASC, id ASC");
    $data = array();
    while($res = $rs->fetch(PDO::FETCH_ASSOC)) {
        $data[] = $res;
    }
    // 获取连续问答入口热键
    $rs2 = $DB->query("SELECT id, question, trigger_keyword, chain_id FROM pre_customer_service_qa WHERE status='1' AND is_hotkey='1' AND type='1' AND step_number='0' ORDER BY sort ASC, id ASC");
    while($res = $rs2->fetch(PDO::FETCH_ASSOC)) {
        $res['is_chain'] = true;
        $data[] = $res;
    }
    exit(json_encode(array('code' => 1, 'data' => $data)));
break;

// ==================== 发送消息 ====================
case 'send_message':
    $message = isset($_POST['message']) ? trim($_POST['message']) : '';
    $chain_id = isset($_POST['chain_id']) ? trim($_POST['chain_id']) : '';
    $current_step = isset($_POST['current_step']) ? intval($_POST['current_step']) : 0;

    if($message === '') {
        exit(json_encode(array('code' => -1, 'msg' => '消息不能为空')));
    }

    $safe_message = daddslashes($message);
    $safe_chain_id = daddslashes($chain_id);

    // 记录用户消息日志
    $log_message = daddslashes($message);
    $DB->exec("INSERT INTO pre_customer_service_log (user_id, user_qq, message, direction, addtime) VALUES ('{$user_id}', '{$user_qq}', '{$log_message}', 'user', NOW())");

    // 1. 如果处于连续问答中，尝试匹配下一步
    if($safe_chain_id !== '' && $current_step > 0) {
        $next = $DB->getRow("SELECT * FROM pre_customer_service_qa WHERE chain_id='{$safe_chain_id}' AND step_number='{$current_step}' AND type='1' AND status='1' LIMIT 1");
        if($next) {
            // 检查触发词是否匹配
            $trigger = trim($next['trigger_keyword']);
            if($trigger === '' || mb_stripos($message, $trigger) !== false) {
                // 检查是否有更多步骤
                $further = $DB->getRow("SELECT * FROM pre_customer_service_qa WHERE chain_id='{$safe_chain_id}' AND step_number='" . ($current_step + 1) . "' AND type='1' AND status='1' LIMIT 1");
                // 获取下一步的触发词
                $next_trigger = '';
                if($further) {
                    $next_trigger = trim($further['trigger_keyword']);
                }
                // 记录回复日志
                $log_answer = daddslashes($next['answer']);
                $DB->exec("INSERT INTO pre_customer_service_log (user_id, user_qq, message, direction, addtime) VALUES ('{$user_id}', '{$user_qq}', '{$log_answer}', 'bot', NOW())");
                
                // 解码HTML实体
                $answer = html_entity_decode($next['answer'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                
                exit(json_encode(array(
                    'code' => 1,
                    'data' => array(
                        'answer' => $answer,
                        'chain_id' => $safe_chain_id,
                        'chain_continue' => $further ? true : false,
                        'next_step' => $further ? ($current_step + 1) : 0,
                        'next_trigger' => $next_trigger
                    )
                ), JSON_UNESCAPED_UNICODE));
            }
        }
    }

    // 2. 精确匹配普通问答
    $qa = $DB->getRow("SELECT * FROM pre_customer_service_qa WHERE status='1' AND type='0' AND match_type='0' AND question='{$safe_message}' LIMIT 1");
    if($qa) {
        // 记录回复日志
        $log_answer = daddslashes($qa['answer']);
        $DB->exec("INSERT INTO pre_customer_service_log (user_id, user_qq, message, direction, addtime) VALUES ('{$user_id}', '{$user_qq}', '{$log_answer}', 'bot', NOW())");
        
        // 解码HTML实体
        $answer = html_entity_decode($qa['answer'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
        
        exit(json_encode(array(
            'code' => 1,
            'data' => array(
                'answer' => $answer,
                'chain_id' => '',
                'chain_continue' => false,
                'next_step' => 0,
                'next_trigger' => ''
            )
        ), JSON_UNESCAPED_UNICODE));
    }

    // 3. 模糊匹配普通问答（trigger_keyword）
    $rs = $DB->query("SELECT * FROM pre_customer_service_qa WHERE status='1' AND type='0' AND match_type='1' AND trigger_keyword != '' ORDER BY sort ASC LIMIT 50");
    while($res = $rs->fetch(PDO::FETCH_ASSOC)) {
        if(mb_stripos($message, $res['trigger_keyword']) !== false) {
            // 记录回复日志
            $log_answer = daddslashes($res['answer']);
            $DB->exec("INSERT INTO pre_customer_service_log (user_id, user_qq, message, direction, addtime) VALUES ('{$user_id}', '{$user_qq}', '{$log_answer}', 'bot', NOW())");
            
            // 解码HTML实体
            $answer = html_entity_decode($res['answer'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
            
            exit(json_encode(array(
                'code' => 1,
                'data' => array(
                    'answer' => $answer,
                    'chain_id' => '',
                    'chain_continue' => false,
                    'next_step' => 0,
                    'next_trigger' => ''
                )
            ), JSON_UNESCAPED_UNICODE));
        }
    }

    // 4. 匹配连续问答入口
    $chain_entry = $DB->getRow("SELECT * FROM pre_customer_service_qa WHERE status='1' AND type='1' AND step_number='0' AND (question='{$safe_message}' OR trigger_keyword='{$safe_message}') LIMIT 1");
    if($chain_entry) {
        $next_step_row = $DB->getRow("SELECT * FROM pre_customer_service_qa WHERE chain_id='{$chain_entry['chain_id']}' AND step_number='1' AND type='1' AND status='1' LIMIT 1");
        $next_trigger = '';
        if($next_step_row) {
            $next_trigger = trim($next_step_row['trigger_keyword']);
        }
        // 记录回复日志
        $log_answer = daddslashes($chain_entry['answer']);
        $DB->exec("INSERT INTO pre_customer_service_log (user_id, user_qq, message, direction, addtime) VALUES ('{$user_id}', '{$user_qq}', '{$log_answer}', 'bot', NOW())");
        
        // 解码HTML实体
        $answer = html_entity_decode($chain_entry['answer'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
        
        exit(json_encode(array(
            'code' => 1,
            'data' => array(
                'answer' => $answer,
                'chain_id' => $chain_entry['chain_id'],
                'chain_continue' => $next_step_row ? true : false,
                'next_step' => $next_step_row ? 1 : 0,
                'next_trigger' => $next_trigger
            )
        ), JSON_UNESCAPED_UNICODE));
    }

    // 5. 默认回复
    $no_match = $conf['cs_no_match_msg'] ?? '';
    if($no_match === '') {
        $qq = $conf['qq'] ?? '';
        $no_match = '抱歉，没有找到相关问题的答案。' . ($qq ? '如需帮助请联系QQ：' . $qq : '请尝试其他问题。');
    }
    
    // 记录默认回复日志
    $log_answer = daddslashes($no_match);
    $DB->exec("INSERT INTO pre_customer_service_log (user_id, user_qq, message, direction, addtime) VALUES ('{$user_id}', '{$user_qq}', '{$log_answer}', 'bot', NOW())");
    
    // 解码HTML实体
    $no_match = html_entity_decode($no_match, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    
    exit(json_encode(array(
        'code' => 1,
        'data' => array(
            'answer' => $no_match,
            'chain_id' => '',
            'chain_continue' => false,
            'next_step' => 0,
            'next_trigger' => ''
        )
    ), JSON_UNESCAPED_UNICODE));
break;

// ==================== 获取历史记录 ====================
case 'get_history':
    $limit = isset($_POST['limit']) ? intval($_POST['limit']) : 50;
    $rs = $DB->query("SELECT message, direction, addtime FROM pre_customer_service_log WHERE user_id='{$user_id}' ORDER BY id DESC LIMIT {$limit}");
    $data = array();
    while($res = $rs->fetch(PDO::FETCH_ASSOC)) {
        $data[] = $res;
    }
    // 反转顺序，使最早的在前面
    $data = array_reverse($data);
    exit(json_encode(array('code' => 1, 'data' => $data)));
break;

// ==================== 提交留言 ====================
case 'submit_feedback':
    // 检查留言功能是否开启
    if(($conf['cs_feedback_enabled'] ?? '1') != '1') {
        exit(json_encode(array('code' => -1, 'msg' => '留言功能已关闭')));
    }

    $content = isset($_POST['content']) ? trim($_POST['content']) : '';
    $images = isset($_POST['images']) ? json_decode($_POST['images'], true) : array();

    if($content === '' && empty($images)) {
        exit(json_encode(array('code' => -1, 'msg' => '请输入留言内容或添加图片')));
    }

    // 处理图片，转换为HTML
    $imagesHtml = '';
    if(!empty($images) && is_array($images)) {
        foreach($images as $img) {
            $imagesHtml .= '<br><img src="' . htmlspecialchars($img) . '" style="max-width:100%;border-radius:6px;margin:5px 0;">';
        }
    }

    // 用户邮箱优先级：用户表email字段 > QQ@qq.com > 用户输入
    $user_email = trim($userrow['email'] ?? '');
    $user_qq = trim($userrow['qq'] ?? '');
    $input_email = isset($_POST['email']) ? trim($_POST['email']) : '';

    // 如果没有email字段，使用QQ邮箱
    if($user_email === '' && $user_qq !== '') {
        $user_email = $user_qq . '@qq.com';
    }

    // 如果还是没有，使用用户输入的邮箱
    if($user_email === '' && $input_email !== '') {
        $user_email = $input_email;
    }

    if($user_email === '') {
        exit(json_encode(array('code' => -2, 'msg' => '请填写邮箱地址')));
    }

    // 组合完整内容
    $fullContent = $content . $imagesHtml;
    $safe_content = daddslashes($fullContent);
    $safe_email = daddslashes($user_email);
    $user_name = daddslashes($userrow['name'] ?? $userrow['qq'] ?? ('用户' . $user_id));

    try {
        // 插入留言
        $DB->exec("INSERT INTO pre_customer_service_feedback (user_id, user_name, user_email, content, status, addtime) VALUES ('{$user_id}', '{$user_name}', '{$safe_email}', '{$safe_content}', '0', NOW())");
        $feedback_id = $DB->lastInsertId();

        // 发送邮件通知管理员
        if(!empty($conf['cs_feedback_email'])) {
            global $date;
            $sitename = $conf['sitename'] ?? '在线客服';
            $admin_email = $conf['cs_feedback_email'];
            $email_content = '<html><body style="font-family:Arial,sans-serif;">
                <div style="max-width:600px;margin:0 auto;padding:20px;background:#f5f5f5;">
                    <div style="background:#fff;padding:30px;border-radius:8px;">
                        <h2 style="color:#e74c3c;border-bottom:2px solid #e74c3c;padding-bottom:10px;">新留言通知 - ' . $sitename . '</h2>
                        <p style="color:#333;"><strong>用户：</strong>' . htmlspecialchars($user_name) . ' (ID:' . $user_id . ')</p>
                        <p style="color:#333;"><strong>邮箱：</strong>' . htmlspecialchars($user_email) . '</p>
                        <div style="background:#f8f9fa;padding:15px;border-radius:6px;margin:15px 0;">
                            <p style="color:#888;font-size:12px;margin-bottom:5px;">留言内容：</p>
                            <p style="color:#333;">' . nl2br(htmlspecialchars($content)) . '</p>
                            ' . $imagesHtml . '
                        </div>
                        <p style="color:#999;font-size:12px;">时间：' . $date . '</p>
                        <p style="margin-top:20px;"><a href="' . $_scheme . $_SERVER['HTTP_HOST'] . '/admin/customer_service.php" style="background:#3b82f6;color:#fff;padding:10px 20px;text-decoration:none;border-radius:5px;">前往处理</a></p>
                    </div>
                </div>
            </body></html>';
            send_mail($admin_email, '新留言通知 - ' . $sitename, $email_content);
        }

        exit(json_encode(array('code' => 1, 'msg' => '留言提交成功，我们会尽快回复您')));
    } catch (Exception $e) {
        exit(json_encode(array('code' => -1, 'msg' => '留言功能暂不可用，请联系管理员')));
    }
break;

// ==================== 检查用户邮箱 ====================
case 'check_user_email':
    $user_email = trim($userrow['email'] ?? '');
    $user_qq = trim($userrow['qq'] ?? '');
    // 如果没有email字段但有QQ，则使用QQ邮箱
    if($user_email === '' && $user_qq !== '') {
        $user_email = $user_qq . '@qq.com';
    }
    exit(json_encode(array('code' => 1, 'has_email' => $user_email !== '', 'email' => $user_email)));
break;

// ==================== 获取我的留言列表 ====================
case 'get_my_feedback':
    try {
        $rs = $DB->query("SELECT * FROM pre_customer_service_feedback WHERE user_id='{$user_id}' ORDER BY id DESC LIMIT 20");
        $data = array();
        while($res = $rs->fetch(PDO::FETCH_ASSOC)){
            // 解码HTML实体
            $res['content'] = html_entity_decode($res['content'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
            $res['reply'] = $res['reply'] ? html_entity_decode($res['reply'], ENT_QUOTES | ENT_HTML5, 'UTF-8') : '';
            $data[] = $res;
        }
        exit(json_encode(array('code' => 1, 'data' => $data)));
    } catch (Exception $e) {
        exit(json_encode(array('code' => 1, 'data' => array(), 'msg' => '留言表不存在')));
    }
break;

default:
    exit(json_encode(array('code' => -1, 'msg' => '无效操作')));
break;
}
