<?php
ob_start();
include(dirname(__DIR__) . '/includes/common.php');
ob_end_clean();

if($islogin==1){}else exit('{"code":-1,"msg":"请先登录"}');

@header('Content-Type: application/json; charset=UTF-8');
$act = isset($_GET['act']) ? daddslashes($_GET['act']) : null;

switch($act) {

case 'cs_save_config':
    foreach($_POST as $k=>$v){
        $k = preg_replace('/[^a-zA-Z0-9_]/', '', (string)$k);
        if($k === '') continue;
        if(is_array($v)) $v = json_encode($v, JSON_UNESCAPED_UNICODE);
        if($k === 'cs_top_info'){
            $v = trim((string)$v);
            $v = preg_replace('/<\?=\s*(.+?)\s*\?>/s', '<?php echo $1; ?>', $v);
            $v = preg_replace('/<\?(?!php)/i', '<?php ', $v);
        }
        $v = addslashes(trim((string)$v));
        $DB->query("REPLACE INTO pre_config SET v='".$v."',k='".$k."'");
    }
    exit('{"code":1,"msg":"保存成功"}');
break;

case 'cs_upload_icon':
    if(!isset($_FILES['file']) || $_FILES['file']['error'] != 0){
        exit('{"code":-1,"msg":"请选择图片文件"}');
    }
    $allowedTypes = array('image/jpeg','image/png','image/gif','image/svg+xml','image/webp');
    if(!in_array($_FILES['file']['type'], $allowedTypes)){
        exit('{"code":-1,"msg":"只支持 JPG、PNG、GIF、SVG、WebP 格式"}');
    }
    if($_FILES['file']['size'] > 5 * 1024 * 1024){
        exit('{"code":-1,"msg":"文件大小不能超过5MB"}');
    }
    $uploadDir = dirname(__DIR__) . '/assets/upload/cs/';
    if(!is_dir($uploadDir)){
        mkdir($uploadDir, 0755, true);
    }
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    $filename = 'bubble_' . date('YmdHis') . '_' . uniqid() . '.' . $ext;
    $filepath = $uploadDir . $filename;
    if(move_uploaded_file($_FILES['file']['tmp_name'], $filepath)){
        $url = '/assets/upload/cs/' . $filename;
        $DB->query("REPLACE INTO pre_config SET v='".$url."',k='cs_bubble_icon'");
        exit('{"code":1,"msg":"上传成功","url":"'.$url.'"}');
    }else{
        exit('{"code":-1,"msg":"上传失败"}');
    }
break;

case 'cs_upload_content_image':
    if(!isset($_FILES['file']) || $_FILES['file']['error'] != 0){
        exit('{"code":-1,"msg":"请选择图片文件"}');
    }
    $allowedTypes = array('image/jpeg','image/png','image/gif','image/webp');
    if(!in_array($_FILES['file']['type'], $allowedTypes)){
        exit('{"code":-1,"msg":"只支持 JPG、PNG、GIF、WebP 格式"}');
    }
    if($_FILES['file']['size'] > 5 * 1024 * 1024){
        exit('{"code":-1,"msg":"文件大小不能超过5MB"}');
    }
    $uploadDir = dirname(__DIR__) . '/assets/upload/cs/';
    if(!is_dir($uploadDir)){
        mkdir($uploadDir, 0755, true);
    }
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    $filename = 'content_' . date('YmdHis') . '_' . uniqid() . '.' . $ext;
    $filepath = $uploadDir . $filename;
    if(move_uploaded_file($_FILES['file']['tmp_name'], $filepath)){
        $url = '/assets/upload/cs/' . $filename;
        exit('{"code":1,"msg":"上传成功","url":"'.$url.'"}');
    }else{
        exit('{"code":-1,"msg":"上传失败"}');
    }
break;

case 'cs_get_qa_list':
    $pagesize = isset($_POST['pagesize'])?intval($_POST['pagesize']):10;
    $page = isset($_POST['page'])?intval($_POST['page']):1;
    $offset = $pagesize * ($page - 1);
    $kw = isset($_POST['kw'])?daddslashes($_POST['kw']):'';
    $sql_where = " type='0'";
    if($kw != ''){
        $sql_where .= " AND (question LIKE '%{$kw}%' OR answer LIKE '%{$kw}%')";
    }
    $rs = $DB->query("SELECT * FROM pre_customer_service_qa WHERE{$sql_where} ORDER BY sort ASC, id DESC LIMIT $offset,$pagesize");
    $data = array();
    while($res = $rs->fetch(PDO::FETCH_ASSOC)){
        $data[] = $res;
    }
    $total = $DB->getColumn("SELECT count(*) FROM pre_customer_service_qa WHERE{$sql_where}");
    $pages = $total > 0 ? ceil($total/$pagesize) : 1;
    exit(json_encode(array('total'=>intval($total),'page'=>$page,'end'=>$pages,'data'=>$data)));
break;

case 'cs_add_qa':
    $question = addslashes(trim($_POST['question']));
    $answer = addslashes(trim($_POST['answer']));
    $match_type = intval($_POST['match_type']);
    $trigger_keyword = addslashes(trim($_POST['trigger_keyword'] ?? ''));
    $is_hotkey = intval($_POST['is_hotkey']);
    $sort = intval($_POST['sort']);
    if($question == '' || $answer == '') exit('{"code":-1,"msg":"问题和回答不能为空"}');
    $sql = "INSERT INTO pre_customer_service_qa (type,question,answer,match_type,trigger_keyword,is_hotkey,sort,status,addtime) VALUES ('0','{$question}','{$answer}','{$match_type}','{$trigger_keyword}','{$is_hotkey}','{$sort}','1',NOW())";
    if($DB->exec($sql)){
        exit('{"code":1,"msg":"添加成功"}');
    }else{
        exit('{"code":-1,"msg":"添加失败'.$DB->error().'"}');
    }
break;

case 'cs_edit_qa':
    $id = intval($_POST['id']);
    $question = addslashes(trim($_POST['question']));
    $answer = addslashes(trim($_POST['answer']));
    $match_type = intval($_POST['match_type']);
    $trigger_keyword = addslashes(trim($_POST['trigger_keyword'] ?? ''));
    $is_hotkey = intval($_POST['is_hotkey']);
    $sort = intval($_POST['sort']);
    if($question == '' || $answer == '') exit('{"code":-1,"msg":"问题和回答不能为空"}');
    $row = $DB->getRow("SELECT * FROM pre_customer_service_qa WHERE id='{$id}' LIMIT 1");
    if(!$row) exit('{"code":-1,"msg":"数据不存在"}');
    $sql = "UPDATE pre_customer_service_qa SET question='{$question}',answer='{$answer}',match_type='{$match_type}',trigger_keyword='{$trigger_keyword}',is_hotkey='{$is_hotkey}',sort='{$sort}' WHERE id='{$id}'";
    if($DB->exec($sql) !== false){
        exit('{"code":1,"msg":"修改成功"}');
    }else{
        exit('{"code":-1,"msg":"修改失败'.$DB->error().'"}');
    }
break;

case 'cs_delete_qa':
    $id = intval($_POST['id']);
    $row = $DB->getRow("SELECT * FROM pre_customer_service_qa WHERE id='{$id}' LIMIT 1");
    if(!$row) exit('{"code":-1,"msg":"数据不存在"}');
    $DB->exec("DELETE FROM pre_customer_service_qa WHERE id='{$id}'");
    exit('{"code":1,"msg":"删除成功"}');
break;

case 'cs_toggle_status':
    $id = intval($_POST['id']);
    $status = intval($_POST['status']);
    $DB->exec("UPDATE pre_customer_service_qa SET status='{$status}' WHERE id='{$id}'");
    exit('{"code":1,"msg":"已操作"}');
break;

case 'cs_get_chain_list':
    $rs = $DB->query("SELECT chain_id, chain_name, MIN(status) as status, COUNT(*) as step_count FROM pre_customer_service_qa WHERE type='1' AND step_number='0' GROUP BY chain_id ORDER BY id DESC");
    $data = array();
    while($res = $rs->fetch(PDO::FETCH_ASSOC)){
        $total_steps = $DB->getColumn("SELECT count(*) FROM pre_customer_service_qa WHERE chain_id='{$res['chain_id']}' AND type='1'");
        $res['step_count'] = intval($total_steps);
        $data[] = $res;
    }
    exit(json_encode(array('code'=>1,'data'=>$data)));
break;

case 'cs_toggle_chain_status':
    $chain_id = daddslashes($_POST['chain_id']);
    $status = intval($_POST['status']);
    if($chain_id == '') exit('{"code":-1,"msg":"参数错误"}');
    $DB->exec("UPDATE pre_customer_service_qa SET status='{$status}' WHERE chain_id='{$chain_id}' AND type='1'");
    exit('{"code":1,"msg":"已操作"}');
break;

case 'cs_get_chain_detail':
    $chain_id = daddslashes($_POST['chain_id']);
    if($chain_id == '') exit('{"code":-1,"msg":"参数错误"}');
    $rs = $DB->query("SELECT * FROM pre_customer_service_qa WHERE chain_id='{$chain_id}' AND type='1' ORDER BY step_number ASC");
    $data = array();
    while($res = $rs->fetch(PDO::FETCH_ASSOC)){
        $data[] = $res;
    }
    exit(json_encode(array('code'=>1,'data'=>$data)));
break;

case 'cs_save_chain':
    $chain_id = daddslashes($_POST['chain_id'] ?? '');
    $chain_name = addslashes(trim($_POST['chain_name'] ?? ''));
    $steps = isset($_POST['steps']) ? $_POST['steps'] : array();
    $is_hotkey = intval($_POST['is_hotkey'] ?? 1);
    $status = intval($_POST['status'] ?? 1);
    if($chain_name == '') exit('{"code":-1,"msg":"链名称不能为空"}');
    if(count($steps) < 1) exit('{"code":-1,"msg":"至少需要一个步骤"}');
    $is_new = ($chain_id == '');
    if($is_new){
        $chain_id = 'chain_' . date('YmdHis') . '_' . substr(uniqid(), -4);
    }else{
        $DB->exec("DELETE FROM pre_customer_service_qa WHERE chain_id='{$chain_id}' AND type='1'");
    }
    $entry_question = addslashes(trim($chain_name));
    $entry_answer = addslashes(trim($steps[0]['answer'] ?? ''));
    $entry_trigger = addslashes(trim($steps[0]['trigger_keyword'] ?? $chain_name));
    if($entry_answer == '') exit('{"code":-1,"msg":"入口步骤的回答不能为空"}');
    $DB->exec("INSERT INTO pre_customer_service_qa (type,chain_id,chain_name,step_number,trigger_keyword,question,answer,is_hotkey,sort,status,addtime) VALUES ('1','{$chain_id}','{$chain_name}','0','{$entry_trigger}','{$entry_question}','{$entry_answer}','{$is_hotkey}','50','{$status}',NOW())");
    for($i = 1; $i < count($steps); $i++){
        $s_trigger = addslashes(trim($steps[$i]['trigger_keyword'] ?? '下一步'));
        $s_question = addslashes(trim($steps[$i]['question'] ?? '第'.($i).'步'));
        $s_answer = addslashes(trim($steps[$i]['answer'] ?? ''));
        if($s_answer == '') continue;
        $DB->exec("INSERT INTO pre_customer_service_qa (type,chain_id,step_number,trigger_keyword,question,answer,is_hotkey,sort,status,addtime) VALUES ('1','{$chain_id}','{$i}','{$s_trigger}','{$s_question}','{$s_answer}','0','50','{$status}',NOW())");
    }
    exit('{"code":1,"msg":"保存成功"}');
break;

case 'cs_delete_chain':
    $chain_id = daddslashes($_POST['chain_id']);
    if($chain_id == '') exit('{"code":-1,"msg":"参数错误"}');
    $DB->exec("DELETE FROM pre_customer_service_qa WHERE chain_id='{$chain_id}' AND type='1'");
    exit('{"code":1,"msg":"删除成功"}');
break;

case 'cs_get_feedback_list':
    $pagesize = isset($_POST['pagesize'])?intval($_POST['pagesize']):10;
    $page = isset($_POST['page'])?intval($_POST['page']):1;
    $offset = $pagesize * ($page - 1);
    $status = isset($_POST['status']) && $_POST['status'] !== '' ? intval($_POST['status']) : -1;
    $sql_where = "1=1";
    if($status >= 0) $sql_where .= " AND status='{$status}'";

    $rs = $DB->query("SELECT * FROM pre_customer_service_feedback WHERE {$sql_where} ORDER BY id DESC LIMIT $offset,$pagesize");
    if($rs === false) {
        $err = $DB->error();
        exit(json_encode(array('code'=>1,'total'=>0,'page'=>1,'end'=>1,'data'=>array(),'msg'=>'查询失败: ' . $err)));
    }
    $data = array();
    while($res = $rs->fetch(PDO::FETCH_ASSOC)){
        $data[] = $res;
    }
    $total = $DB->getColumn("SELECT count(*) FROM pre_customer_service_feedback WHERE {$sql_where}");
    if($total === false) $total = 0;
    $pages = $total > 0 ? ceil($total/$pagesize) : 1;
    exit(json_encode(array('code'=>1,'total'=>intval($total),'page'=>$page,'end'=>$pages,'data'=>$data)));
break;

case 'cs_get_feedback_detail':
    $id = intval($_POST['id']);
    $row = $DB->getRow("SELECT * FROM pre_customer_service_feedback WHERE id='{$id}' LIMIT 1");
    if(!$row) exit('{"code":-1,"msg":"留言不存在"}');
    $row['user_qq'] = $DB->getColumn("SELECT qq FROM pre_user WHERE zid='{$row['user_id']}' LIMIT 1");
    $row['content'] = html_entity_decode($row['content'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $row['reply'] = $row['reply'] ? html_entity_decode($row['reply'], ENT_QUOTES | ENT_HTML5, 'UTF-8') : '';
    exit(json_encode(array('code'=>1,'data'=>$row)));
break;

case 'cs_set_feedback_status':
    $id = intval($_POST['id']);
    $status = intval($_POST['status']);
    $DB->exec("UPDATE pre_customer_service_feedback SET status='{$status}' WHERE id='{$id}'");
    exit('{"code":1,"msg":"状态已更新"}');
break;

case 'cs_delete_feedback':
    $ids = daddslashes($_POST['ids']);
    if($ids == '') exit('{"code":-1,"msg":"参数错误"}');
    $rows = $DB->getAll("SELECT content, reply FROM pre_customer_service_feedback WHERE id IN ({$ids})");
    if($rows) {
        $siteRoot = dirname(dirname(__FILE__));
        foreach($rows as $row) {
            $content = html_entity_decode($row['content'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
            $reply = $row['reply'] ? html_entity_decode($row['reply'], ENT_QUOTES | ENT_HTML5, 'UTF-8') : '';
            if(preg_match_all('/<img[^>]+src=["\']([^"\']+)["\']/i', $content, $matches)) {
                foreach($matches[1] as $imgPath) {
                    if(strpos($imgPath, '/assets/upload/cs/feedback/') === 0) {
                        $fullPath = $siteRoot . $imgPath;
                        if(file_exists($fullPath)) @unlink($fullPath);
                    }
                }
            }
            if($reply && preg_match_all('/<img[^>]+src=["\']([^"\']+)["\']/i', $reply, $matches)) {
                foreach($matches[1] as $imgPath) {
                    if(strpos($imgPath, '/assets/upload/cs/feedback/') === 0) {
                        $fullPath = $siteRoot . $imgPath;
                        if(file_exists($fullPath)) @unlink($fullPath);
                    }
                }
            }
        }
    }
    $DB->exec("DELETE FROM pre_customer_service_feedback WHERE id IN ({$ids})");
    exit('{"code":1,"msg":"删除成功"}');
break;

case 'cs_reply_feedback':
    $id = intval($_POST['id']);
    $reply_raw = trim($_POST['reply']);
    $reply = addslashes($reply_raw);
    $status = intval($_POST['status']);
    if(!in_array($status, array(1, 2), true)) $status = 1;
    $row = $DB->getRow("SELECT * FROM pre_customer_service_feedback WHERE id='{$id}' LIMIT 1");
    if(!$row) exit('{"code":-1,"msg":"留言不存在"}');
    $reply_block = '<div style="margin-bottom:10px;"><div style="color:#3b82f6;font-size:12px;margin-bottom:4px;">客服回复（'.$date.'）</div><div>'.$reply_raw.'</div></div>';
    $old_reply = $row['reply'] ? html_entity_decode($row['reply'], ENT_QUOTES | ENT_HTML5, 'UTF-8') : '';
    $new_reply = $old_reply === '' ? $reply_block : ($old_reply . '<hr style="border:none;border-top:1px dashed #d1d5db;margin:10px 0;">' . $reply_block);
    $safe_new_reply = addslashes($new_reply);
    $DB->exec("UPDATE pre_customer_service_feedback SET reply='{$safe_new_reply}', status='{$status}', reply_time=NOW() WHERE id='{$id}'");
    if(!empty($row['user_email']) && !empty($reply)){
        global $conf, $date;
        $sitename = $conf['sitename'] ?? '在线客服';
        $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:#333;border-bottom:2px solid #3b82f6;padding-bottom:10px;">' . $sitename . ' - 留言回复</h2>
                    <p style="color:#666;">您好，您的留言已收到回复：</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;">' . htmlspecialchars($row['content']) . '</p>
                    </div>
                    <div style="background:#e8f4fd;padding:15px;border-radius:6px;margin:15px 0;">
                        <p style="color:#3b82f6;font-size:12px;margin-bottom:5px;">客服回复：</p>
                        <div style="color:#333;">' . $reply_raw . '</div>
                    </div>
                    <p style="color:#999;font-size:12px;text-align:right;margin-top:20px;">' . $date . '</p>
                </div>
            </div>
        </body></html>';
        send_mail($row['user_email'], '您的留言已收到回复 - ' . $sitename, $email_content);
    }
    exit('{"code":1,"msg":"回复成功"}');
break;

default:
    exit('{"code":-1,"msg":"无效操作"}');
break;
}