<?php

if (!defined('EMLOG_ROOT')) {
    die('err');
}

if (!class_exists('EmToolKit', false)) {
    include __DIR__ . '/em_toolkit.php';
}

function plugin_setting_view()
{
    $toolKit = EmToolKit::getInstance();
?>
    <?php if (isset($_GET['suc'])): ?>
        <div class="alert alert-success">保存成功</div>
    <?php endif; ?>
    <?php if (isset($_GET['rss_ok'])): ?>
        <div class="alert alert-success">导入成功</div>
    <?php endif; ?>
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">工具箱</h1>
    </div>

    <div class="row">
        <div class="col-2">
            <div class="list-group" id="list-tab">
                <a class="list-group-item list-group-item-action" id="list-messages-list" data-toggle="list" href="#list-messages">数据表修复</a>
                <a class="list-group-item list-group-item-action active" id="list-home-list" data-toggle="list" href="#list-home">更换域名</a>
                <a class="list-group-item list-group-item-action" id="list-home-list" data-toggle="list" href="#list-rss">RSS内容导入</a>
                <a class="list-group-item list-group-item-action" id="list-home-list" data-toggle="list" href="#list-cookie">重置登录Cookie</a>
                <a class="list-group-item list-group-item-action" id="list-home-list" data-toggle="list" href="#list-mdimport">Markdown导入</a>
                <a class="list-group-item list-group-item-action" id="list-settings-list" data-toggle="list" href="#list-settings">代码注入</a>
            </div>
        </div>
        <div class="col-10">
            <div class="tab-content" id="nav-tabContent">
                <div class="tab-pane fade show active" id="list-home" role="tabpanel" aria-labelledby="list-home-list">
                    <div class="col-md-6">
                        <div class="card shadow mb-4 mt-2">
                            <h6 class="card-header">更换域名</h6>
                            <div class="card-body">
                                <form action="plugin.php?plugin=em_toolkit" method="post" name="changeDomain_form" id="changeDomain_form">
                                    <div class="form-group form-check">
                                        <div class="alert alert-info">将替换所有文章中的原站点地址为新的地址（包括图片链接等）</div>
                                        <div class="form-group">
                                            <label>原站点地址（例如： https://www.emlog.net）</label>
                                            <input type="url" class="form-control" value="<?= BLOG_URL ?>" name="olddomain" id="olddomain" required>
                                        </div>
                                        <div class="form-group">
                                            <label>新的站点地址（例如： https://www.emlog.cn）</label>
                                            <input type="url" class="form-control" value="" name="newdomain" id="newdomain" required>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <button type="submit" class="btn btn-sm btn-success">开始更换</button>
                                            <input name="tool_action" id="tool_action" value="change_domain" type="hidden" />
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="tab-pane fade" id="list-messages" role="tabpanel" aria-labelledby="list-messages-list">
                    <div class="col-md-6">
                        <div class="card shadow mb-4 mt-2">
                            <h6 class="card-header">数据表修复</h6>
                            <div class="card-body">
                                <div class="form-group form-check">
                                    <div class="alert alert-primary">
                                        修复emlog数据库中所有出错的数据表，包括数据库表字段缺失。<br /><br />
                                        如站点页面出现SQL错误提示："try to repair it" 或 "Unknown column 'xxx' in 'field list' "，说明数据库表需要修复。
                                    </div>
                                    <button id="repairTableBtn" class="btn btn-sm btn-success">开始修复</button>
                                    <div id="repairTableStatusMsg" class="mt-3"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="tab-pane fade" id="list-cookie">
                    <div class="col-md-6">
                        <div class="card shadow mb-4 mt-2">
                            <h6 class="card-header">重置登录Cookie名称和密钥</h6>
                            <div class="card-body">
                                <div class="form-group form-check">
                                    <div class="alert alert-warning">
                                        1. 🚨重置后所有用户都需要重新登录🚨。<br>
                                        2. 每隔几个月重置一次，可能会让系统安全那么一点点。<br>
                                        3. 也可用于密码被盗，修改密码后，强制恶意用户下线。
                                    </div>
                                    <button id="resetCookieBtn" class="btn btn-sm btn-danger">我已了解，开始重置</button>
                                    <div id="resetCookieMsg" class="mt-3"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="tab-pane fade" id="list-settings" role="tabpanel" aria-labelledby="list-settings-list">
                    <div class="col-md-6">
                        <div class="card shadow mb-4 mt-2">
                            <h6 class="card-header">代码注入</h6>
                            <div class="card-body">
                                <form action="plugin.php?plugin=em_toolkit" method="post" name="importCode_form" id="importCode_form">
                                    <div class="form-group form-check">
                                        <div class="alert alert-warning">推荐使用：<a href="https://www.emlog.net/plugin/detail/903" target="_blank">自定义head标签插件</a>。</div>
                                        <div class="form-group">
                                            <label>全局head标签</label>
                                            <textarea class="form-control" name="header_code" id="header_code" rows="10"><?= $toolKit->getHeadCode(); ?></textarea>
                                            <small>注入代码到所有页面的 head 标签部分，可用于添加网站统计代码、站长平台验证等代码</small>
                                        </div>
                                        <div class="form-group">
                                            <label>页脚</label>
                                            <textarea class="form-control" name="footer_code" id="footer_code" rows="10"><?= $toolKit->getFooterCode(); ?></textarea>
                                            <small>注入代码到所有页面的页脚部分，可用于添加版权、备案等信息</small>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <button class="btn btn-sm btn-success" type="submit">保存</button>
                                            <input name="tool_action" id="tool_action" value="import_code" type="hidden" />
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="tab-pane fade" id="list-rss" role="tabpanel" aria-labelledby="list-settings-list">
                    <div class="col-md-6">
                        <div class="card shadow mb-4 mt-2">
                            <h6 class="card-header">RSS数据导入</h6>
                            <div class="card-body" id="admindex_msg">
                                <div class="form-group form-check">
                                    <div class="alert alert-info">从其他类型站点的 RSS 导入数据，如何导出数据：
                                        <br>WordPress： （工具-导出-选择文章，导出xml文件）
                                        <br>Typecho：（打开文章rss页面，点击浏览器 文件-页面存储）
                                        <br>其他支持rss的系统参考 Typecho 导出数据文件。
                                    </div>
                                    <form action="plugin.php?plugin=em_toolkit" enctype="multipart/form-data" method="post">
                                        <div id="import">
                                            <input type="file" name="rss_file" required />
                                            <input name="tool_action" id="tool_action" value="import_rss" type="hidden" />
                                            <button id="importRssBtn" class="btn btn-sm btn-success">开始导入</button>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div id="importRssStatusMsg" class="mt-2"></div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="tab-pane fade" id="list-mdimport" role="tabpanel" aria-labelledby="list-mdimport-list">
                    <div class="col-md-6">
                        <div class="card shadow mb-4 mt-2">
                            <h6 class="card-header">Markdown批量导入</h6>
                            <div class="card-body" id="mdimport_msg">
                                <div class="form-group form-check">
                                    <div class="alert alert-info">选择.md文件上传导入，支持多选批量上传。</div>
                                    <form action="plugin.php?plugin=em_toolkit" enctype="multipart/form-data" method="post">
                                        <input type="file" name="md_files[]" multiple accept=".md" required />
                                        <input name="tool_action" value="import_md" type="hidden" />
                                        <button class="btn btn-sm btn-success">开始导入</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        setTimeout(hideActived, 3600);
        $("#menu_category_ext").addClass('active');
        $("#menu_ext").addClass('show');
        $("#menu_plug_em_toolkit").addClass('active');

        $("#importCode_form").submit(function(event) {
            event.preventDefault();
            submitForm("#importCode_form");
        });

        $("#changeDomain_form").submit(function(event) {
            event.preventDefault();
            submitForm("#changeDomain_form", '域名更换成功');
        });

        $(document).ready(function() {
            $('#repairTableBtn').click(function(e) {
                e.preventDefault();

                $('#repairTableStatusMsg').html('<div class="spinner-border text-success" role="status"><span class="sr-only">Loading...</span></div>');

                $.ajax({
                    url: './plugin.php?plugin=em_toolkit',
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        tool_action: 'repair_table'
                    },
                    success: function(data) {
                        if (data.code === 0) {
                            $('#repairTableStatusMsg').html('<div class="text-success">' + data.data + '</div>');
                        } else {
                            $('#repairTableStatusMsg').html('<div class="text-danger">' + data.data + '</div>');
                        }
                    },
                    error: function(xhr, status, error) {
                        if (xhr.responseText) {
                            var responseJson = JSON.parse(xhr.responseText);
                            $('#repairTableStatusMsg').html('<div class="text-danger">' + responseJson.msg + '</div>');
                        } else {
                            $('#repairTableStatusMsg').html('<div class="text-danger">' + error + '</div>');
                        }
                    }
                });
            });

            $('#resetCookieBtn').click(function(e) {
                e.preventDefault();

                $('#resetCookieMsg').html('<div class="spinner-border text-danger" role="status"><span class="sr-only">Loading...</span></div>');

                $.ajax({
                    url: './plugin.php?plugin=em_toolkit',
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        tool_action: 'reset_cookie'
                    },
                    success: function(data) {
                        if (data.code === 0) {
                            $('#resetCookieMsg').html('<div class="text-success">' + data.data + '</div>');
                        } else {
                            $('#resetCookieMsg').html('<div class="text-danger">' + data.data + '</div>');
                        }
                    },
                    error: function(xhr, status, error) {
                        if (xhr.responseText) {
                            var responseJson = JSON.parse(xhr.responseText);
                            $('#resetCookieMsg').html('<div class="text-danger">' + responseJson.msg + '</div>');
                        } else {
                            $('#resetCookieMsg').html('<div class="text-danger">' + error + '</div>');
                        }
                    }
                });
            });
        });
    </script>
<?php }

$toolAction = Input::postStrVar('tool_action');
$toolKit = EmToolKit::getInstance();

if ($toolAction === 'change_domain') {
    $oldDomain = Input::postStrVar('olddomain');
    $newDomain = Input::postStrVar('newdomain');

    $toolKit->changeDomain($oldDomain, $newDomain);
}

if ($toolAction === 'repair_table') {
    $toolKit->repairTables();
}

if ($toolAction === 'reset_cookie') {
    $toolKit->resetCookie();
}

if ($toolAction === 'import_code') {
    $headerCode = Input::postStrVar('header_code');
    $footerCode = Input::postStrVar('footer_code');

    $toolKit->importCode($headerCode, $footerCode);
}

if ($toolAction === 'import_md') {
    $md_files = isset($_FILES['md_files']) ? $_FILES['md_files'] : null;
    if (!$md_files || !is_array($md_files['tmp_name'])) {
        emMsg('未检测到上传的Markdown文件');
    }
    $toolKit->importMarkdowns($md_files);
}

if ($toolAction === 'import_rss') {
    $rss_file = isset($_FILES['rss_file']) ? $_FILES['rss_file'] : '';
    if (!$rss_file) {
        emMsg('上传文件失败');
    }
    if ($rss_file['error'] == 1) {
        emMsg('文件大小超过系统' . ini_get('upload_max_filesize') . '限制');
    } elseif ($rss_file['error'] > 1) {
        emMsg('上传文件失败,错误码：' . $rss_file['error']);
    }

    $toolKit->rssImport($rss_file['tmp_name']);
}
