<?php
/**
 * HuSNS - 一款免费开源的社交平台
 * 
 * @author  HYR
 * @QQ      281900864
 * @website https://huyourui.com
 * @license MIT
 * @声明    严禁用于违法违规用途
 */
?>
<?php if (isset($_SESSION['user_id'])): ?>
<?php 
$maxPostLength = Setting::getMaxPostLength(); 
$maxAttachmentSize = Setting::getMaxAttachmentSize();
$maxImageSize = Setting::getMaxImageSize();
$maxImageCount = Setting::getMaxImageCount();
$allowedExtensions = Setting::getAllowedAttachmentExtensions();
$maxAttachmentCount = Setting::getMaxAttachmentCount();
$maxVideoSize = Setting::getMaxVideoSize();
$maxVideoCount = Setting::getMaxVideoCount();
$publishPlaceholder = Setting::getPublishPlaceholder();
$hideTagAdminOnly = Setting::isHideTagAdminOnly();
$isAdmin = isset($_SESSION['is_admin']) && $_SESSION['is_admin'];
$showHideBtn = !$hideTagAdminOnly || $isAdmin;
if (empty($publishPlaceholder)) {
    $publishPlaceholder = '有什么新鲜事想分享给大家？';
}

$phpPostMaxSize = ini_get('post_max_size');
$phpUploadMaxSize = ini_get('upload_max_filesize');
$phpMaxSize = min(
    (int)preg_replace('/[^0-9]/', '', $phpPostMaxSize),
    (int)preg_replace('/[^0-9]/', '', $phpUploadMaxSize)
);
$effectiveMaxVideoSize = min($maxVideoSize, $phpMaxSize);
?>
<div class="publish-box" style="background:#fff;border-radius:12px;padding:16px;margin-bottom:15px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
    <form id="publishForm" action="<?php echo $this->url('post/publish'); ?>" method="post" enctype="multipart/form-data">
        <?php echo $this->csrf(); ?>
        <textarea name="content" placeholder="<?php echo $this->escape($publishPlaceholder); ?>" rows="3" data-max-length="<?php echo $maxPostLength; ?>" id="publishContent" style="width:100%;border:1px solid #eee;border-radius:8px;padding:12px 14px;resize:none;outline:none;font-size:14px;line-height:1.6;margin-bottom:10px;"><?php echo isset($topic) ? '#' . $this->escape($topic) . '# ' : ''; ?></textarea>
        <div class="publish-actions" style="display:flex;align-items:center;gap:16px;color:#999;flex-wrap:wrap;padding-top:10px;border-top:1px solid #f0f0f0;">
            <div class="publish-tools-left" style="display:flex;align-items:center;gap:16px;">
            <div class="upload-btn" title="图片">
                <input type="file" name="images[]" multiple accept="image/*" id="imageUpload" data-max-count="<?php echo $maxImageCount; ?>" style="display:none;">
                <label for="imageUpload" style="cursor:pointer;display:flex;align-items:center;color:#666;">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                </label>
                <span id="imageCount" style="font-size:12px;color:#999;"></span>
            </div>
            <div class="upload-btn" title="视频">
                <input type="file" name="videos[]" multiple accept="video/*" id="videoUpload" data-max-size="<?php echo $effectiveMaxVideoSize; ?>" data-max-count="<?php echo $maxVideoCount; ?>" style="display:none;">
                <label for="videoUpload" style="cursor:pointer;display:flex;align-items:center;color:#666;">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg>
                </label>
                <span id="videoCount" style="font-size:12px;color:#999;"></span>
            </div>
            <div class="upload-btn" title="表情">
                <button type="button" id="emojiBtn" style="background:none;border:none;cursor:pointer;display:flex;align-items:center;color:#666;">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>
                </button>
            </div>
            <div class="upload-btn" title="附件">
                <input type="file" name="attachments[]" multiple id="attachmentUpload" data-max-size="<?php echo $maxAttachmentSize; ?>" data-extensions="<?php echo implode(',', $allowedExtensions); ?>" data-max-count="<?php echo $maxAttachmentCount; ?>" style="display:none;">
                <label for="attachmentUpload" style="cursor:pointer;display:flex;align-items:center;color:#666;">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/></svg>
                </label>
                <span id="attachmentCount" style="font-size:12px;color:#999;"></span>
            </div>
            <?php if ($showHideBtn): ?>
            <div class="upload-btn" title="隐藏内容">
                <button type="button" id="insertHideBtn" style="background:none;border:none;cursor:pointer;display:flex;align-items:center;color:#666;">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
                </button>
            </div>
            <?php endif; ?>
            </div>
            <div class="publish-tools-right" style="display:flex;align-items:center;gap:12px;margin-left:auto;">
                <div class="char-counter" style="font-size:13px;color:#999;">
                    <span id="postCharCount">0</span>/<span id="postMaxChars"><?php echo $maxPostLength; ?></span>
                </div>
                <button type="submit" class="btn btn-primary" style="padding:8px 20px;border-radius:6px;">发布</button>
            </div>
        </div>
        <div id="previewImages" class="preview-images" style="display:flex;gap:8px;flex-wrap:wrap;margin-top:10px;"></div>
        <div id="videoList" class="video-list" style="display:none;margin-top:10px;"></div>
        <div id="attachmentList" class="attachment-list" style="display:none;margin-top:10px;"></div>
        
        <div id="emojiPanel" class="emoji-panel" style="display:none;position:absolute;z-index:100;background:#fff;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,0.15);padding:12px;max-width:320px;">
            <div class="emoji-panel-header" style="display:flex;gap:10px;margin-bottom:10px;border-bottom:1px solid #eee;padding-bottom:8px;">
                <span class="emoji-tab active" data-category="default" style="cursor:pointer;padding:4px 8px;border-radius:4px;font-size:13px;">默认</span>
                <span class="emoji-tab" data-category="hot" style="cursor:pointer;padding:4px 8px;border-radius:4px;font-size:13px;">热门</span>
                <span class="emoji-tab" data-category="emoji" style="cursor:pointer;padding:4px 8px;border-radius:4px;font-size:13px;">Emoji</span>
            </div>
            <div class="emoji-panel-content" id="emojiContent" style="max-height:200px;overflow-y:auto;display:flex;flex-wrap:wrap;gap:4px;"></div>
        </div>
    </form>
</div>

<style>
.publish-box { position: relative; }
.preview-item { position: relative; width: 80px; height: 80px; }
.preview-item img { width: 100%; height: 100%; object-fit: cover; border-radius: 8px; }
.preview-item .remove-btn { position: absolute; top: -6px; right: -6px; width: 20px; height: 20px; background: rgba(0,0,0,0.6); color: #fff; border-radius: 50%; text-align: center; line-height: 20px; font-size: 14px; cursor: pointer; }
.emoji-item { width: 28px; height: 28px; cursor: pointer; border-radius: 4px; }
.emoji-item:hover { background: #f5f7fa; transform: scale(1.2); }
.emoji-tab.active { background: #1677ff; color: #fff; }
body.dark-mode .publish-box { background: #16213e; }
body.dark-mode #publishContent { background: #1e293b; border-color: #334155; color: #e0e0e0; }
body.dark-mode #emojiPanel { background: #16213e; }
body.dark-mode .emoji-panel-header { border-color: #334155; }
body.dark-mode .emoji-tab { color: #e0e0e0; }
body.dark-mode .emoji-tab.active { background: #4096ff; }
</style>

<script>
(function() {
    var maxImageSize = <?php echo $maxImageSize; ?> * 1024 * 1024;
    var maxImageCount = <?php echo $maxImageCount; ?>;
    var maxAttachmentSize = <?php echo $maxAttachmentSize; ?> * 1024 * 1024;
    var maxVideoSize = <?php echo $effectiveMaxVideoSize; ?> * 1024 * 1024;
    var allowedExtensions = <?php echo json_encode($allowedExtensions); ?>;
    var maxAttachmentCount = <?php echo $maxAttachmentCount; ?>;
    var maxVideoCount = <?php echo $maxVideoCount; ?>;
    
    var imageInput = document.getElementById('imageUpload');
    var videoInput = document.getElementById('videoUpload');
    var attachmentInput = document.getElementById('attachmentUpload');
    var previewContainer = document.getElementById('previewImages');
    var videoList = document.getElementById('videoList');
    var attachmentList = document.getElementById('attachmentList');
    var imageCount = document.getElementById('imageCount');
    var videoCount = document.getElementById('videoCount');
    var attachmentCount = document.getElementById('attachmentCount');
    var publishContent = document.getElementById('publishContent');
    var postCharCount = document.getElementById('postCharCount');
    
    window.selectedImages = window.selectedImages || [];
    window.selectedVideos = window.selectedVideos || [];
    window.selectedAttachments = window.selectedAttachments || [];
    
    // 字符计数
    publishContent.addEventListener('input', function() {
        postCharCount.textContent = this.value.length;
    });
    
    function updateImageCount() {
        imageCount.textContent = window.selectedImages.length > 0 ? '(' + window.selectedImages.length + '/' + maxImageCount + ')' : '';
    }
    
    function updateVideoCount() {
        videoCount.textContent = window.selectedVideos.length > 0 ? '(' + window.selectedVideos.length + '/' + maxVideoCount + ')' : '';
    }
    
    function updateAttachmentCount() {
        attachmentCount.textContent = window.selectedAttachments.length > 0 ? '(' + window.selectedAttachments.length + '/' + maxAttachmentCount + ')' : '';
    }
    
    function addImagePreview(file) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var div = document.createElement('div');
            div.className = 'preview-item';
            div.innerHTML = '<img src="' + e.target.result + '" alt="预览"><span class="remove-btn" data-type="image">&times;</span>';
            previewContainer.appendChild(div);
        };
        reader.readAsDataURL(file);
    }
    
    function addVideoItem(file) {
        videoList.style.display = 'flex';
        var div = document.createElement('div');
        div.className = 'video-upload-item';
        div.style.cssText = 'display:flex;align-items:center;gap:10px;padding:8px;background:#f5f7fa;border-radius:6px;margin-bottom:8px;';
        div.innerHTML = '<span style="font-size:20px;">🎬</span><div style="flex:1;min-width:0;"><div style="font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' + file.name + '</div><div style="font-size:12px;color:#999;">' + formatSize(file.size) + '</div></div><span class="remove-btn" data-type="video" style="background:#ff4d4f;width:20px;height:20px;border-radius:50%;color:#fff;text-align:center;line-height:20px;cursor:pointer;">×</span>';
        videoList.appendChild(div);
        return div;
    }
    
    function addAttachmentItem(file) {
        attachmentList.style.display = 'flex';
        var div = document.createElement('div');
        div.className = 'attachment-item';
        div.style.cssText = 'display:flex;align-items:center;gap:10px;padding:8px;background:#f5f7fa;border-radius:6px;margin-bottom:8px;';
        div.innerHTML = '<span style="font-size:20px;">📄</span><div style="flex:1;min-width:0;"><div style="font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' + file.name + '</div><div style="font-size:12px;color:#999;">' + formatSize(file.size) + '</div></div><span class="remove-btn" data-type="attachment" style="background:#ff4d4f;width:20px;height:20px;border-radius:50%;color:#fff;text-align:center;line-height:20px;cursor:pointer;">×</span>';
        attachmentList.appendChild(div);
    }
    
    function formatSize(bytes) {
        if (bytes < 1024) return bytes + ' B';
        if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
        return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
    }
    
    function handleImageFile(file) {
        if (!file.type.startsWith('image/')) return false;
        if (file.size > maxImageSize) {
            alert('图片 "' + file.name + '" 超过大小限制（最大<?php echo $maxImageSize; ?>MB）');
            return false;
        }
        if (window.selectedImages.length >= maxImageCount) {
            alert('最多上传' + maxImageCount + '张图片');
            return false;
        }
        var ext = 'png';
        if (file.type === 'image/jpeg' || file.type === 'image/jpg') ext = 'jpg';
        else if (file.type === 'image/gif') ext = 'gif';
        else if (file.type === 'image/webp') ext = 'webp';
        if (!file.name || file.name === 'image.png' || file.name.indexOf('.') === -1) {
            file = new File([file], 'paste_' + Date.now() + '.' + ext, { type: file.type });
        }
        window.selectedImages.push(file);
        addImagePreview(file);
        updateImageCount();
        return true;
    }
    
    function handleVideoFile(file) {
        if (!file.type.startsWith('video/')) {
            alert('请选择视频文件');
            return false;
        }
        if (file.size > maxVideoSize) {
            alert('视频 "' + file.name + '" 超过大小限制（最大<?php echo $effectiveMaxVideoSize; ?>MB）');
            return false;
        }
        if (window.selectedVideos.length >= maxVideoCount) {
            alert('最多上传' + maxVideoCount + '个视频');
            return false;
        }
        addVideoItem(file);
        window.selectedVideos.push({ file: file });
        updateVideoCount();
        return true;
    }
    
    function handleAttachmentFile(file) {
        var ext = file.name.split('.').pop().toLowerCase();
        if (allowedExtensions.length > 0 && allowedExtensions.indexOf(ext) === -1) {
            alert('不支持的文件类型：' + ext);
            return false;
        }
        if (file.size > maxAttachmentSize) {
            alert('附件 "' + file.name + '" 超过大小限制（最大<?php echo $maxAttachmentSize; ?>MB）');
            return false;
        }
        if (window.selectedAttachments.length >= maxAttachmentCount) {
            alert('最多上传' + maxAttachmentCount + '个附件');
            return false;
        }
        window.selectedAttachments.push(file);
        addAttachmentItem(file);
        updateAttachmentCount();
        return true;
    }
    
    // 粘贴上传
    publishContent.addEventListener('paste', function(e) {
        var items = e.clipboardData.items;
        if (!items) return;
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if (item.kind === 'file') {
                var file = item.getAsFile();
                if (file.type.startsWith('image/')) {
                    e.preventDefault();
                    handleImageFile(file);
                } else if (file.type.startsWith('video/')) {
                    e.preventDefault();
                    handleVideoFile(file);
                } else {
                    e.preventDefault();
                    handleAttachmentFile(file);
                }
            }
        }
    });
    
    imageInput.addEventListener('change', function(e) {
        Array.from(e.target.files).forEach(handleImageFile);
        imageInput.value = '';
    });
    
    videoInput.addEventListener('change', function(e) {
        Array.from(e.target.files).forEach(handleVideoFile);
        videoInput.value = '';
    });
    
    attachmentInput.addEventListener('change', function(e) {
        Array.from(e.target.files).forEach(handleAttachmentFile);
        attachmentInput.value = '';
    });
    
    previewContainer.addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-btn')) {
            var index = Array.from(previewContainer.children).indexOf(e.target.parentElement);
            window.selectedImages.splice(index, 1);
            e.target.parentElement.remove();
            updateImageCount();
        }
    });
    
    videoList.addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-btn')) {
            var index = Array.from(videoList.children).indexOf(e.target.parentElement);
            window.selectedVideos.splice(index, 1);
            e.target.parentElement.remove();
            updateVideoCount();
            if (window.selectedVideos.length === 0) videoList.style.display = 'none';
        }
    });
    
    attachmentList.addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-btn')) {
            var index = Array.from(attachmentList.children).indexOf(e.target.parentElement);
            window.selectedAttachments.splice(index, 1);
            e.target.parentElement.remove();
            updateAttachmentCount();
            if (window.selectedAttachments.length === 0) attachmentList.style.display = 'none';
        }
    });
    
    // 表情面板
    var emojiData = {
        default: [],
        hot: [],
        emoji: ['😀','😃','😄','😁','😆','😅','🤣','😂','🙂','🙃','😉','😊','😇','🥰','😍','🤩','😘','😗','😚','😙','🥲','😋','😛','😜','🤪','😝','🤑','🤗','🤭','🤫','🤔','🤐','🤨','😐','😑','😶','😏','😒','🙄','😬','😮','🤯','😱','😨','😰','😥','😢','😭','😤','😡','🤬','👍','👎','👏','🙌','🤝','❤️','🧡','💛','💚','💙','💜','🖤','🤍','💔','💕','💖','💗','💘','💝']
    };
    
    var localEmojiMap = <?php echo json_encode(Helper::getEmojiList()); ?>;
    var emojiBaseUrl = '<?php echo Helper::asset("emoji/"); ?>';
    
    ['微笑', '嘻嘻', '哈哈', '可爱', '可怜', '挤眼', '害羞', '闭嘴', '鄙视', '爱你', '泪', '偷笑', '亲亲', '生病', '太开心', '白眼', '右哼哼', '左哼哼', '嘘', '衰', '吐', '哈欠', '抱抱', '怒', '疑问', '馋嘴', '拜拜', '思考', '汗', '打脸', '惊恐', '失望', '酷', '厉害', '弱', '握手', '胜利', '抱拳', '鼓励', '抠鼻'].forEach(function(name) {
        var code = '[' + name + ']';
        if (localEmojiMap[code]) {
            emojiData.default.push({ name: name, code: code, url: emojiBaseUrl + localEmojiMap[code] });
        }
    });
    
    ['doge', '二哈', '喵喵', '笑cry', '并不简单', '摊手', '跪了', '费解', '憧憬', '悲伤', '允悲', '赞', 'no', 'ok', 'haha', '哼', '666', 'awsl', '吃瓜', '打call'].forEach(function(name) {
        var code = '[' + name + ']';
        if (localEmojiMap[code]) {
            emojiData.hot.push({ name: name, code: code, url: emojiBaseUrl + localEmojiMap[code] });
        }
    });
    
    var emojiPanel = document.getElementById('emojiPanel');
    var emojiBtn = document.getElementById('emojiBtn');
    var emojiContent = document.getElementById('emojiContent');
    var currentCategory = 'default';
    
    function renderEmojiPanel(category) {
        currentCategory = category;
        var emojis = emojiData[category] || [];
        var html = '';
        emojis.forEach(function(emoji) {
            if (category === 'emoji') {
                html += '<span class="emoji-item emoji-text" data-code="' + emoji + '" title="' + emoji + '">' + emoji + '</span>';
            } else {
                html += '<img class="emoji-item emoji-img" src="' + emoji.url + '" data-code="[' + emoji.name + ']" title="' + emoji.name + '" alt="' + emoji.name + '">';
            }
        });
        emojiContent.innerHTML = html;
    }
    
    emojiBtn.addEventListener('click', function(e) {
        e.preventDefault();
        emojiPanel.style.display = emojiPanel.style.display === 'none' ? 'flex' : 'none';
        if (emojiPanel.style.display === 'flex') renderEmojiPanel(currentCategory);
    });
    
    document.addEventListener('click', function(e) {
        if (!emojiPanel.contains(e.target) && e.target !== emojiBtn) {
            emojiPanel.style.display = 'none';
        }
    });
    
    document.querySelectorAll('.emoji-tab').forEach(function(tab) {
        tab.addEventListener('click', function() {
            document.querySelectorAll('.emoji-tab').forEach(function(t) { t.classList.remove('active'); });
            this.classList.add('active');
            renderEmojiPanel(this.dataset.category);
        });
    });
    
    emojiContent.addEventListener('click', function(e) {
        if (e.target.classList.contains('emoji-item')) {
            var code = e.target.dataset.code;
            var start = publishContent.selectionStart;
            var end = publishContent.selectionEnd;
            var value = publishContent.value;
            publishContent.value = value.substring(0, start) + code + value.substring(end);
            publishContent.selectionStart = publishContent.selectionEnd = start + code.length;
            publishContent.focus();
            postCharCount.textContent = publishContent.value.length;
        }
    });
    
    renderEmojiPanel('default');
        
        // ========== Form Submit ==========
        document.getElementById('publishForm').addEventListener('submit', function(e) {
            e.preventDefault();
            var form = e.target;
            var submitBtn = form.querySelector('button[type="submit"]');
            var content = publishContent.value.trim();
            
            if (!content && window.selectedImages.length === 0 && window.selectedVideos.length === 0) {
                alert('请输入内容或上传文件');
                return false;
            }
            
            submitBtn.disabled = true;
            submitBtn.textContent = '发布中...';
            
            var formData = new FormData(form);
            
            // 添加选中的文件
            window.selectedImages.forEach(function(file) {
                formData.append('images[]', file);
            });
            window.selectedVideos.forEach(function(item) {
                formData.append('videos[]', item.file);
            });
            window.selectedAttachments.forEach(function(file) {
                formData.append('attachments[]', file);
            });
            
            fetch(form.action, {
                method: 'POST',
                body: formData
            }).then(function(r) { return r.json(); })
              .then(function(data) {
                if (data.code === 0) {
                    showToast('发布成功', 'success');
                    // 清空表单
                    publishContent.value = '';
                    window.selectedImages = [];
                    window.selectedVideos = [];
                    window.selectedAttachments = [];
                    previewContainer.innerHTML = '';
                    videoList.innerHTML = '';
                    videoList.style.display = 'none';
                    attachmentList.innerHTML = '';
                    attachmentList.style.display = 'none';
                    postCharCount.textContent = '0';
                    updateImageCount();
                    updateVideoCount();
                    updateAttachmentCount();
                    // 刷新页面
                    setTimeout(function() { location.reload(); }, 500);
                } else {
                    showToast(data.message || '发布失败', 'error');
                }
                submitBtn.disabled = false;
                submitBtn.textContent = '发布';
            }).catch(function(err) {
                showToast('网络错误，请重试', 'error');
                submitBtn.disabled = false;
                submitBtn.textContent = '发布';
            });
            
            return false;
        });
})();
</script>
<?php endif; ?>
