<?php
/**
 * 微信客服管理（修复版）
 * 修复：POST/AJAX处理移到header.php之前，修复PHP标签错乱
 */
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
admin_check_login();
check_permission('admin');

// ===== AJAX POST 请求处理（必须在任何HTML输出之前） =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json; charset=utf-8');

    if (!isset($_SESSION['admin_id']) || !$_SESSION['admin_id']) {
        echo json_encode(['success' => false, 'message' => '请先登录']);
        exit;
    }

    $action = $_POST['action'];

    if ($action === 'save_config') {
        $app_id = trim($_POST['app_id'] ?? '');
        $app_secret = trim($_POST['app_secret'] ?? '');
        $token = trim($_POST['token'] ?? '');
        $encoding_aes_key = trim($_POST['encoding_aes_key'] ?? '');
        $customer_service_enabled = intval($_POST['customer_service_enabled'] ?? 0);
        $notification_admins = trim($_POST['notification_admins'] ?? '');
        $auto_reply = trim($_POST['auto_reply'] ?? '');

        update_setting('wechat_app_id', $app_id);
        update_setting('wechat_app_secret', $app_secret);
        update_setting('wechat_token', $token);
        update_setting('wechat_encoding_aes_key', $encoding_aes_key);
        update_setting('wechat_customer_service_enabled', $customer_service_enabled);
        update_setting('wechat_notification_admins', $notification_admins);
        update_setting('wechat_auto_reply', $auto_reply);

        echo json_encode(['success' => true, 'message' => '配置保存成功']);
        exit;
    }

    if ($action === 'get_messages') {
        $page = max(1, intval($_POST['page'] ?? 1));
        $pageSize = 20;
        $offset = ($page - 1) * $pageSize;

        $total = db_count('wechat_messages');
        $messages = db_query("SELECT wm.*, wa.realname as reply_admin_name FROM `wechat_messages` wm LEFT JOIN `admins` wa ON wm.reply_admin_id = wa.id ORDER BY wm.created_at DESC LIMIT {$offset}, {$pageSize}");

        echo json_encode([
            'success' => true,
            'data' => [
                'list' => $messages,
                'total' => $total,
                'page' => $page,
                'total_page' => ceil($total / $pageSize)
            ]
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    if ($action === 'reply_message') {
        $message_id = intval($_POST['message_id'] ?? 0);
        $reply_content = trim($_POST['reply_content'] ?? '');

        if ($message_id === 0 || empty($reply_content)) {
            echo json_encode(['success' => false, 'message' => '参数错误']);
            exit;
        }

        db_exec(
            "UPDATE `wechat_messages` SET `reply`=?, `reply_admin_id`=?, `status`='replied', `updated_at`=NOW() WHERE `id`=?",
            [$reply_content, $_SESSION['admin_id'], $message_id]
        );

        echo json_encode(['success' => true, 'message' => '回复成功']);
        exit;
    }

    echo json_encode(['success' => false, 'message' => '未知操作']);
    exit;
}

// ===== GET 请求：渲染页面 =====
$admin = current_admin();
$pageTitle = '微信客服管理';

// 获取微信配置
$wechat_config = [
    'app_id' => get_setting('wechat_app_id', ''),
    'app_secret' => get_setting('wechat_app_secret', ''),
    'token' => get_setting('wechat_token', ''),
    'encoding_aes_key' => get_setting('wechat_encoding_aes_key', ''),
    'customer_service_enabled' => get_setting('wechat_customer_service_enabled', 0),
    'notification_admins' => get_setting('wechat_notification_admins', ''),
    'auto_reply' => get_setting('wechat_auto_reply', '')
];

// 获取消息统计
$message_stats = [
    'total' => db_count('wechat_messages'),
    'pending' => db_count('wechat_messages', "status='pending'"),
    'replied' => db_count('wechat_messages', "status='replied'"),
    'today' => db_count('wechat_messages', "DATE(created_at) = CURDATE()")
];

require_once __DIR__ . '/header.php';
?>
<div class="wechat-container" style="max-width:1200px;margin:0 auto;padding:20px;">
    <div class="page-header">
        <h1>微信客服管理</h1>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:20px;margin-bottom:30px;">
        <div class="stat-card" style="padding:20px;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);color:white;border-radius:8px;text-align:center;">
            <h3 style="font-size:36px;margin-bottom:5px;"><?php echo $message_stats['total']; ?></h3>
            <p style="opacity:0.9;">总消息数</p>
        </div>
        <div class="stat-card" style="padding:20px;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);color:white;border-radius:8px;text-align:center;">
            <h3 style="font-size:36px;margin-bottom:5px;"><?php echo $message_stats['pending']; ?></h3>
            <p style="opacity:0.9;">待回复</p>
        </div>
        <div class="stat-card" style="padding:20px;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);color:white;border-radius:8px;text-align:center;">
            <h3 style="font-size:36px;margin-bottom:5px;"><?php echo $message_stats['replied']; ?></h3>
            <p style="opacity:0.9;">已回复</p>
        </div>
        <div class="stat-card" style="padding:20px;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);color:white;border-radius:8px;text-align:center;">
            <h3 style="font-size:36px;margin-bottom:5px;"><?php echo $message_stats['today']; ?></h3>
            <p style="opacity:0.9;">今日消息</p>
        </div>
    </div>

    <!-- 配置部分 -->
    <div class="config-section" style="background:white;padding:30px;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,0.1);margin-bottom:30px;">
        <h2>微信配置</h2>
        <p>配置微信公众号信息，启用微信客服功能。</p>

        <form id="configForm" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:20px;margin-top:20px;">
            <div class="form-group">
                <label>微信公众号 AppID</label>
                <input type="text" name="app_id" value="<?php echo htmlspecialchars($wechat_config['app_id']); ?>">
            </div>
            <div class="form-group">
                <label>微信公众号 AppSecret</label>
                <input type="password" name="app_secret" value="<?php echo htmlspecialchars($wechat_config['app_secret']); ?>">
            </div>
            <div class="form-group">
                <label>Token（令牌）</label>
                <input type="text" name="token" value="<?php echo htmlspecialchars($wechat_config['token']); ?>">
                <small>用于微信服务器验证</small>
            </div>
            <div class="form-group">
                <label>EncodingAESKey</label>
                <input type="text" name="encoding_aes_key" value="<?php echo htmlspecialchars($wechat_config['encoding_aes_key']); ?>">
                <small>43位随机字符串</small>
            </div>
            <div class="form-group">
                <label>
                    <input type="checkbox" name="customer_service_enabled" value="1" <?php echo $wechat_config['customer_service_enabled']?'checked':''; ?>>
                    启用微信客服
                </label>
            </div>
            <div class="form-group">
                <label>接收通知的管理员ID</label>
                <input type="text" name="notification_admins" value="<?php echo htmlspecialchars($wechat_config['notification_admins']); ?>" placeholder="多个ID用逗号分隔">
            </div>
            <div class="form-group" style="grid-column:1/-1;">
                <label>自动回复内容</label>
                <textarea name="auto_reply" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:4px;min-height:80px;resize:vertical;"><?php echo htmlspecialchars($wechat_config['auto_reply']); ?></textarea>
            </div>
            <div class="form-group" style="grid-column:1/-1;">
                <button type="submit" class="btn btn-primary">保存配置</button>
            </div>
        </form>

        <div class="help-box" style="padding:20px;background:#fff3cd;border-radius:4px;border-left:4px solid #ffc107;margin-top:20px;">
            <h4 style="margin-bottom:10px;color:#856404;">配置说明</h4>
            <ol style="padding-left:20px;color:#856404;">
                <li>在微信公众平台获取 AppID 和 AppSecret</li>
                <li>在"设置与开发" -> "基本配置"中配置服务器</li>
                <li>URL 填写：<code><?php echo SITE_URL; ?>/wechat/callback.php</code></li>
                <li>Token 需与微信公众平台一致</li>
            </ol>
        </div>
    </div>

    <!-- 消息管理 -->
    <div class="messages-section" style="background:white;padding:30px;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,0.1);">
        <h2>消息管理</h2>
        <p>查看和回复用户通过微信公众号发送的消息。</p>
        <div id="messageList" style="margin-top:20px;">
            <p style="text-align:center;color:#999;">加载中...</p>
        </div>
        <div id="messagePagination"></div>
    </div>
</div>

<!-- 回复模态框 -->
<div id="replyModal" class="modal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:1000;">
    <div style="background:white;padding:30px;border-radius:8px;width:90%;max-width:600px;margin:auto;position:relative;top:50%;transform:translateY(-50%);">
        <h3>回复消息</h3>
        <form id="replyForm">
            <input type="hidden" id="replyMessageId" name="message_id" value="0">
            <div class="form-group">
                <label>用户消息</label>
                <div id="originalMessage" style="padding:10px;background:#f8f9fa;border-radius:4px;"></div>
            </div>
            <div class="form-group">
                <label>回复内容</label>
                <textarea name="reply_content" required style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:4px;min-height:100px;resize:vertical;"></textarea>
            </div>
            <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:20px;">
                <button type="button" class="btn btn-secondary" onclick="closeReplyModal()">取消</button>
                <button type="submit" class="btn btn-primary">发送回复</button>
            </div>
        </form>
    </div>
</div>

<script>
var currentPage = 1;

document.getElementById('configForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    formData.append('action', 'save_config');
    fetch('', {method:'POST', body:new URLSearchParams(formData)})
    .then(function(r){return r.json();})
    .then(function(data){
        if(data.success){alert('配置保存成功！');}
        else{alert('保存失败：'+data.message);}
    })
    .catch(function(){alert('网络错误，请稍后重试！');});
});

function loadMessages(page) {
    page = page || 1;
    fetch('', {
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'action=get_messages&page=' + page
    })
    .then(function(r){return r.json();})
    .then(function(data){
        if(data.success){
            renderMessages(data.data.list);
            renderPagination(data.data.total, data.data.page, data.data.total_page);
            currentPage = page;
        }
    });
}

function renderMessages(messages) {
    var container = document.getElementById('messageList');
    if(!messages || messages.length===0){
        container.innerHTML = '<p style="text-align:center;color:#999;">暂无消息</p>';
        return;
    }
    var html = '';
    messages.forEach(function(msg){
        var statusText = msg.status==='pending' ? '待回复' : '已回复';
        var statusColor = msg.status==='pending' ? '#dc3545' : '#28a745';
        html += '<div style="padding:15px;margin-bottom:15px;background:#f8f9fa;border-radius:8px;border-left:4px solid #667eea;">';
        html += '<div style="display:flex;justify-content:space-between;margin-bottom:10px;font-size:13px;color:#6c757d;">';
        html += '<span><strong>'+esc(msg.nickname||msg.open_id)+'</strong></span>';
        html += '<span>'+esc(msg.created_at)+'</span>';
        html += '<span style="color:'+statusColor+';">'+statusText+'</span>';
        html += '</div>';
        html += '<div style="margin-bottom:10px;line-height:1.6;"><strong>用户消息：</strong>'+esc(msg.content)+'</div>';
        if(msg.reply){
            html += '<div style="padding:10px;background:white;border-radius:4px;margin-top:10px;"><strong>回复：</strong>'+esc(msg.reply)+'</div>';
        }
        if(msg.status==='pending'){
            html += '<div style="margin-top:10px;"><button class="btn btn-sm btn-primary" onclick="openReplyModal('+msg.id+',\''+esc(msg.content).replace(/'/g,'\\\'')+'\')">回复</button></div>';
        }
        html += '</div>';
    });
    container.innerHTML = html;
}

function esc(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}

function renderPagination(total, page, totalPage) {
    var container = document.getElementById('messagePagination');
    if(totalPage<=1){container.innerHTML='';return;}
    var html = '<div class="pagination">';
    if(page>1){html += '<a href="javascript:void(0)" onclick="loadMessages('+(page-1)+')">上一页</a>';}
    for(var i=Math.max(1,page-2);i<=Math.min(totalPage,page+2);i++){
        if(i===page){html += '<span class="current">'+i+'</span>';}
        else{html += '<a href="javascript:void(0)" onclick="loadMessages('+i+')">'+i+'</a>';}
    }
    if(page<totalPage){html += '<a href="javascript:void(0)" onclick="loadMessages('+(page+1)+')">下一页</a>';}
    html += '</div>';
    container.innerHTML = html;
}

function openReplyModal(messageId, content) {
    document.getElementById('replyMessageId').value = messageId;
    document.getElementById('originalMessage').textContent = content;
    document.getElementById('replyModal').style.display = 'flex';
}
function closeReplyModal() {
    document.getElementById('replyModal').style.display = 'none';
}

document.getElementById('replyForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    formData.append('action', 'reply_message');
    fetch('', {method:'POST', body:new URLSearchParams(formData)})
    .then(function(r){return r.json();})
    .then(function(data){
        if(data.success){alert('回复成功！');closeReplyModal();loadMessages(currentPage);}
        else{alert('回复失败：'+data.message);}
    })
    .catch(function(){alert('网络错误！');});
});

document.getElementById('replyModal').addEventListener('click', function(e) {
    if(e.target===this){closeReplyModal();}
});

loadMessages(1);
</script>
<?php require_once __DIR__ . '/footer.php'; ?>
