<?php
session_start();
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
$expire = 1800;
if (empty($_SESSION['user_id']) || (time() - $_SESSION['login_time'] > $expire)) {
    session_destroy();
    header("Location: login.php");
    exit;
}
$_SESSION['login_time'] = time();
$userName = htmlspecialchars($_SESSION['username']);

// 读取配置库
$dbHost = "10.150.117.190";
$dbUser = "root";
$dbPwd = "hp93000";
$dbName = "alert_mail_stat";
$conn = mysqli_connect($dbHost, $dbUser, $dbPwd, $dbName);
mysqli_set_charset($conn, "utf8mb4");
$currentLang = mysqli_fetch_assoc(mysqli_query($conn, "SELECT v FROM sys_config WHERE k='lang'"))['v'] ?? "zh";

// 多语言（统一侧边栏中英对照）
$langMap = [
    'zh' => [
        'page_subtitle' => '爱德万测试 · 系统通知配置',
        'menu_monitor' => '监控面板',
        'menu_workorder' => '工单系统',
        'menu_system' => '系统管理',
        'menu_admin' => '后台配置',
        'menu_smtp' => '邮箱SMTP配置',
        'menu_notify' => '工单通知告警配置',
        'smtp_config' => '邮箱SMTP配置',
        'smtp_host' => 'SMTP服务器',
        'smtp_port' => '端口',
        'smtp_ssl' => '启用SSL/TLS',
        'smtp_account' => '发件账号',
        'smtp_pwd' => '授权密码',
        'smtp_from' => '发件人邮箱',
        'save_smtp' => '保存邮箱配置',
        'save_success' => '保存成功',
        'notify_title' => '工单告警通知配置',
        'dingtalk_webhook' => '钉钉Webhook地址',
        'dingtalk_secret' => '钉钉加签密钥（可选）',
        'wecom_webhook' => '企业微信Webhook地址',
        'wecom_mention' => '企业微信@人员（多个用逗号分隔）',
        'notify_switch' => '开启工单自动推送告警',
        'save_notify' => '保存通知配置',
        'placeholder_webhook' => '请输入Webhook完整地址',
        'placeholder_secret' => '不使用加签留空',
        'placeholder_mention' => 'all代表所有人，或填写手机号'
    ],
    'en' => [
        'page_subtitle' => 'Advantest · System Notify Config',
        'menu_monitor' => 'Monitor Panel',
        'menu_workorder' => 'Work Order System',
        'menu_system' => 'System Manage',
        'menu_admin' => 'System Config',
        'menu_smtp' => 'SMTP Mail Config',
        'menu_notify' => 'Work Order Alert Notify',
        'smtp_config' => 'SMTP Mail Config',
        'smtp_host' => 'SMTP Host',
        'smtp_port' => 'Port',
        'smtp_ssl' => 'Enable SSL/TLS',
        'smtp_account' => 'SMTP Account',
        'smtp_pwd' => 'Auth Password',
        'smtp_from' => 'Sender Email',
        'save_smtp' => 'Save Mail Config',
        'save_success' => 'Saved successfully',
        'notify_title' => 'Work Order Alert Notification',
        'dingtalk_webhook' => 'DingTalk Webhook',
        'dingtalk_secret' => 'DingTalk Secret (Optional)',
        'wecom_webhook' => 'WeCom Webhook',
        'wecom_mention' => 'WeCom Mention User (split by comma)',
        'notify_switch' => 'Auto push work order alert',
        'save_notify' => 'Save Notify Config',
        'placeholder_webhook' => 'Input full webhook url',
        'placeholder_secret' => 'Leave empty if no secret',
        'placeholder_mention' => 'all for everyone, or mobile number'
    ]
];
$t = $langMap[$currentLang];

// 保存提交处理
if ($_POST['act'] === "save_smtp") {
    $host = trim($_POST['smtp_host'] ?? '');
    $port = intval($_POST['smtp_port'] ?? 25);
    $ssl = intval($_POST['smtp_ssl'] ?? 0);
    $user = trim($_POST['smtp_user'] ?? '');
    $pwd = trim($_POST['smtp_pass'] ?? '');
    $from = trim($_POST['smtp_from'] ?? '');
    mysqli_query($conn, "UPDATE sys_smtp_config SET smtp_host='$host',smtp_port=$port,smtp_ssl=$ssl,smtp_user='$user',smtp_pass='$pwd',send_from='$from' WHERE id=1");
    echo "<script>alert('".$t['save_success']."');location.href='smtp_config.php';</script>";
    exit;
}
if ($_POST['act'] === "save_notify") {
    $ding_webhook = trim($_POST['dingtalk_webhook'] ?? '');
    $ding_secret = trim($_POST['dingtalk_secret'] ?? '');
    $wecom_webhook = trim($_POST['wecom_webhook'] ?? '');
    $wecom_mention = trim($_POST['wecom_mention'] ?? '');
    $notify_open = intval($_POST['notify_open'] ?? 0);
    mysqli_query($conn, "CREATE TABLE IF NOT EXISTS sys_workorder_notify (
        id INT PRIMARY KEY AUTO_INCREMENT,
        dingtalk_webhook VARCHAR(500) NOT NULL DEFAULT '',
        dingtalk_secret VARCHAR(200) NOT NULL DEFAULT '',
        wecom_webhook VARCHAR(500) NOT NULL DEFAULT '',
        wecom_mention VARCHAR(300) NOT NULL DEFAULT '',
        notify_open TINYINT NOT NULL DEFAULT 0,
        update_time DATETIME NOT NULL DEFAULT NOW()
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    $exist = mysqli_fetch_assoc(mysqli_query($conn, "SELECT id FROM sys_workorder_notify LIMIT 1"));
    if ($exist) {
        mysqli_query($conn, "UPDATE sys_workorder_notify SET
            dingtalk_webhook='$ding_webhook',
            dingtalk_secret='$ding_secret',
            wecom_webhook='$wecom_webhook',
            wecom_mention='$wecom_mention',
            notify_open=$notify_open,
            update_time=NOW()
        WHERE id = {$exist['id']}");
    } else {
        mysqli_query($conn, "INSERT INTO sys_workorder_notify
            (dingtalk_webhook,dingtalk_secret,wecom_webhook,wecom_mention,notify_open)
            VALUES ('$ding_webhook','$ding_secret','$wecom_webhook','$wecom_mention',$notify_open)");
    }
    echo "<script>alert('".$t['save_success']."');location.href='smtp_config.php';</script>";
    exit;
}

// 读取SMTP配置
$smtpRow = [];
$sql = "SELECT * FROM sys_smtp_config WHERE id = 1";
$res = mysqli_query($conn, $sql);
if ($res instanceof mysqli_result) {
    $smtpRow = mysqli_fetch_assoc($res) ?: [];
}
$smtpConfig = $smtpRow;

// 读取工单通知配置
$notifyConfig = [];
$notifyRes = mysqli_query($conn, "SELECT * FROM sys_workorder_notify LIMIT 1");
if ($notifyRes instanceof mysqli_result) {
    $notifyConfig = mysqli_fetch_assoc($notifyRes) ?: [];
}
?>
<!DOCTYPE html>
<html lang="<?php echo $currentLang==='zh'?'zh-CN':'en'; ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>System Notify Config - Advantest</title>
<link rel="stylesheet" href="/static/css/font-awesome.min.css">
<script src="/static/js/jquery.min.js"></script>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{
    background:#f9fafc;
    font-family:"Inter","PingFang SC","Microsoft YaHei";
    color:#1d2939;
    line-height:1.6;
    display:flex;
    flex-direction:column;
    height:100vh;
    overflow:hidden;
}
.wrap-main{display:flex;flex:1;overflow:hidden;}

/* 侧边栏 */
.sidebar{
    width:240px;
    background:#152c5b;
    color:#e2e8f0;
    flex-shrink:0;
    overflow-y:auto;
}
.sidebar-brand{
    padding:28px 24px;
    border-bottom:1px solid rgba(255,255,255,0.08);
}
.sidebar-brand-en{
    font-size:20px;
    font-weight:700;
    letter-spacing:1px;
    color:#fff;
}
.sidebar-brand-cn{
    font-size:12px;
    color:#a5b4fc;
    margin-top:6px;
    line-height:1.4;
}
.sidebar-menu{padding:16px 0 30px;}
.menu-title{
    padding:12px 24px 8px;
    font-size:12px;
    color:#94a3b8;
    letter-spacing:1px;
    text-transform:uppercase;
}
.menu-item{
    display:flex;
    align-items:center;
    gap:12px;
    padding:14px 24px;
    cursor:pointer;
    font-size:14px;
    transition:all 0.22s ease;
    color:#cbd5e1;
}
.menu-item i{
    font-size:16px;
    width:20px;
    text-align:center;
}
.menu-item.active{
    background:rgba(255,255,255,0.12);
    color:#fff;
    border-left:4px solid #3b82f6;
}
.menu-item:hover:not(.active){
    background:rgba(255,255,255,0.06);
    color:#fff;
}

/* 主内容区 */
.main-content{
    flex:1;
    overflow-y:auto;
    display:flex;
    flex-direction:column;
}
.header{
    background:#ffffff;
    border-bottom:1px solid #eef2fb;
    color:#152c5b;
    padding:20px 40px;
    display:flex;
    justify-content:space-between;
    align-items:center;
    box-shadow:0 2px 12px rgba(21,44,91,0.05);
    flex-shrink:0;
}
.header-left{display:flex;align-items:center;gap:14px;}
.header-brand-en{
    font-size:24px;
    font-weight:700;
    letter-spacing:2px;
    color:#152c5b;
}
.header-brand-cn{font-size:13px;color:#64748b;line-height:1.4;}
.header-right{display:flex;align-items:center;gap:20px;font-size:14px;flex-wrap:wrap;}
.user-info{color:#475569;display:flex;align-items:center;gap:6px;}

/* 按钮统一规范：圆角10px，统一尺寸，无夸张圆润 */
.btn-base{
    border:none;
    padding:10px 22px;
    border-radius:10px;
    cursor:pointer;
    font-size:14px;
    display:flex;
    align-items:center;
    gap:8px;
    transition:all 0.2s ease;
}
.btn-primary{
    background:#152c5b;
    color:#fff;
}
.btn-primary:hover{
    background:#0f1e42;
    box-shadow:0 4px 12px rgba(21,44,91,0.12);
}

/* 容器 */
.container{padding:36px 40px;flex:1;}
/* 卡片核心修改：圆角12px，摒弃大圆，轻薄阴影 */
.base-card{
    background:#fff;
    border-radius:12px;
    padding:32px;
    box-shadow:0 2px 12px rgba(21,44,91,0.04);
    border:1px solid #eef2fb;
    max-width:780px;
    margin-bottom:28px;
}
.title-wrap{
    display:flex;
    align-items:center;
    gap:12px;
    font-size:18px;
    font-weight:600;
    color:#152c5b;
    margin-bottom:24px;
    padding-bottom:16px;
    border-bottom:1px solid #eef2fb;
}
.title-wrap i{font-size:19px;color:#3b82f6;}

/* 表单全局统一，端口/密码/文本框完全一致 */
.form-row{margin-bottom:22px;}
.form-row label{
    display:block;
    margin-bottom:8px;
    color:#344054;
    font-weight:500;
    font-size:13px;
}
/* 所有输入框统一样式，无差异化 */
.form-row input[type="text"],
.form-row input[type="password"],
.form-row input[type="number"]{
    width:100%;
    padding:11px 14px;
    border:1px solid #cbd5e1;
    border-radius:10px;
    font-size:14px;
    transition:border 0.2s,box-shadow 0.2s;
    background:#fff;
}
.form-row input:focus{
    outline:none;
    border-color:#3b82f6;
    box-shadow:0 0 0 3px rgba(59,130,246,0.12);
}
.form-row input::placeholder{color:#98a2b3;font-size:13px;}

.checkbox-wrap{
    display:flex;
    align-items:center;
    gap:10px;
}
.checkbox-wrap input[type="checkbox"]{
    width:18px;height:18px;
    cursor:pointer;
}
.form-submit{margin-top:8px;}
</style>
</head>
<body>
<div class="wrap-main">
    <div class="sidebar">
        <div class="sidebar-brand">
            <div class="sidebar-brand-en">Advantest</div>
            <div class="sidebar-brand-cn"><?php echo $t['page_subtitle']; ?></div>
        </div>
        <div class="sidebar-menu">
            <div class="menu-title"><?php echo $t['menu_monitor']; ?></div>
            <div class="menu-item" onclick="location.href='dashboard.php'">
                <i class="fa fa-line-chart"></i><span><?php echo $t['menu_monitor']; ?></span>
            </div>
            <div class="menu-item" onclick="location.href='work_order.php'">
                <i class="fa fa-ticket"></i><span><?php echo $t['menu_workorder']; ?></span>
            </div>

            <div class="menu-title"><?php echo $t['menu_system']; ?></div>
            <div class="menu-item" onclick="location.href='admin.php'">
                <i class="fa fa-cog"></i><span><?php echo $t['menu_admin']; ?></span>
            </div>
            <div class="menu-item active">
                <i class="fa fa-envelope-o"></i><span><?php echo $t['menu_smtp']; ?></span>
            </div>
            <div class="menu-item" onclick="location.href='smtp_config.php#notify'">
                <i class="fa fa-bell"></i><span><?php echo $t['menu_notify']; ?></span>
            </div>
        </div>
    </div>
    <div class="main-content">
        <div class="header">
            <div class="header-left">
                <div>
                    <div class="header-brand-en">Advantest</div>
                    <div class="header-brand-cn"><?php echo $t['page_subtitle']; ?></div>
                </div>
            </div>
            <div class="header-right">
                <span class="user-info"><i class="fa fa-user-circle"></i>User: <?php echo $userName; ?></span>
                <button class="btn-base btn-primary" onclick="location.href='logout.php'"><i class="fa fa-sign-out"></i>Logout</button>
            </div>
        </div>
        <div class="container">
            <!-- SMTP邮箱配置 -->
            <div class="base-card">
                <div class="title-wrap"><i class="fa fa-envelope-o"></i><?php echo $t['smtp_config']; ?></div>
                <form method="post">
                    <input type="hidden" name="act" value="save_smtp">
                    <div class="form-row">
                        <label><?php echo $t['smtp_host']; ?></label>
                        <input name="smtp_host" value="<?php echo htmlspecialchars($smtpConfig['smtp_host'] ?? ''); ?>">
                    </div>
                    <div class="form-row">
                        <label><?php echo $t['smtp_port']; ?></label>
                        <input name="smtp_port" type="number" value="<?php echo intval($smtpConfig['smtp_port'] ?? 25); ?>">
                    </div>
                    <div class="form-row checkbox-wrap">
                        <input type="checkbox" name="smtp_ssl" value="1" <?php echo ($smtpConfig['smtp_ssl'] ?? 0)==1?'checked':''; ?>>
                        <label><?php echo $t['smtp_ssl']; ?></label>
                    </div>
                    <div class="form-row">
                        <label><?php echo $t['smtp_account']; ?></label>
                        <input name="smtp_user" value="<?php echo htmlspecialchars($smtpConfig['smtp_user'] ?? ''); ?>">
                    </div>
                    <div class="form-row">
                        <label><?php echo $t['smtp_pwd']; ?></label>
                        <input name="smtp_pass" type="password" value="<?php echo htmlspecialchars($smtpConfig['smtp_pass'] ?? ''); ?>">
                    </div>
                    <div class="form-row">
                        <label><?php echo $t['smtp_from']; ?></label>
                        <input name="smtp_from" value="<?php echo htmlspecialchars($smtpConfig['send_from'] ?? ''); ?>">
                    </div>
                    <div class="form-submit">
                        <button class="btn-base btn-primary" type="submit"><i class="fa fa-save"></i><?php echo $t['save_smtp']; ?></button>
                    </div>
                </form>
            </div>

            <!-- 工单钉钉/企业微信通知配置 -->
            <div class="base-card" id="notify">
                <div class="title-wrap"><i class="fa fa-bell"></i><?php echo $t['notify_title']; ?></div>
                <form method="post">
                    <input type="hidden" name="act" value="save_notify">
                    <div class="form-row checkbox-wrap">
                        <input type="checkbox" name="notify_open" value="1" <?php echo ($notifyConfig['notify_open'] ?? 0)==1?'checked':''; ?>>
                        <label><?php echo $t['notify_switch']; ?></label>
                    </div>
                    <div class="form-row">
                        <label><?php echo $t['dingtalk_webhook']; ?></label>
                        <input name="dingtalk_webhook" placeholder="<?php echo $t['placeholder_webhook']; ?>" value="<?php echo htmlspecialchars($notifyConfig['dingtalk_webhook'] ?? ''); ?>">
                    </div>
                    <div class="form-row">
                        <label><?php echo $t['dingtalk_secret']; ?></label>
                        <input name="dingtalk_secret" placeholder="<?php echo $t['placeholder_secret']; ?>" value="<?php echo htmlspecialchars($notifyConfig['dingtalk_secret'] ?? ''); ?>">
                    </div>
                    <div class="form-row">
                        <label><?php echo $t['wecom_webhook']; ?></label>
                        <input name="wecom_webhook" placeholder="<?php echo $t['placeholder_webhook']; ?>" value="<?php echo htmlspecialchars($notifyConfig['wecom_webhook'] ?? ''); ?>">
                    </div>
                    <div class="form-row">
                        <label><?php echo $t['wecom_mention']; ?></label>
                        <input name="wecom_mention" placeholder="<?php echo $t['placeholder_mention']; ?>" value="<?php echo htmlspecialchars($notifyConfig['wecom_mention'] ?? ''); ?>">
                    </div>
                    <div class="form-submit">
                        <button class="btn-base btn-primary" type="submit"><i class="fa fa-save"></i><?php echo $t['save_notify']; ?></button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</body>
</html>
