<?php
require_once __DIR__ . '/layout.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $settings = [
        'email_verification_enabled' => $_POST['email_verification_enabled'] ?? '0',
        'mobile_verification_enabled' => $_POST['mobile_verification_enabled'] ?? '0',
        'universal_verification_code' => $_POST['universal_verification_code'] ?? '',
        'verification_api_config' => $_POST['verification_api_config'] ?? '',
        'mobile_api_config' => $_POST['mobile_api_config'] ?? '',
        'smtp_host' => $_POST['smtp_host'] ?? '',
        'smtp_port' => $_POST['smtp_port'] ?? '587',
        'smtp_user' => $_POST['smtp_user'] ?? '',
        'smtp_pass' => $_POST['smtp_pass'] ?? '',
        'smtp_secure' => $_POST['smtp_secure'] ?? 'tls',
        'mail_from_email' => $_POST['mail_from_email'] ?? '',
        'mail_from_name' => $_POST['mail_from_name'] ?? 'Byro Exchange',
        'usdt_trc20_address' => $_POST['usdt_trc20_address'] ?? '',
        'usdt_erc20_address' => $_POST['usdt_erc20_address'] ?? '',
        'usdt_bep20_address' => $_POST['usdt_bep20_address'] ?? '',
        'service_link' => $_POST['service_link'] ?? '',
        'site_name' => $_POST['site_name'] ?? 'Byro',
        'rate_MYR' => $_POST['rate_MYR'] ?? '',
        'rate_CNY' => $_POST['rate_CNY'] ?? '',
        'rate_EUR' => $_POST['rate_EUR'] ?? '',
        'ios_download_url' => $_POST['ios_download_url'] ?? '#',
        'android_download_url' => $_POST['android_download_url'] ?? '#',
        'apk_download_url' => $_POST['apk_download_url'] ?? '/downloads/byro.apk'
    ];
    
    foreach ($settings as $key => $val) {
        $stmt = db()->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->execute([$key, $val, $val]);
    }

    // Clear exchange rate cache
    $cache_file = __DIR__ . '/../db/exchange_rates.json';
    if (file_exists($cache_file)) {
        unlink($cache_file);
    }
    
    // Handle logo upload if provided
    if (isset($_FILES['logo_file']) && $_FILES['logo_file']['error'] === 0) {
        $ext = pathinfo($_FILES['logo_file']['name'], PATHINFO_EXTENSION);
        $filename = 'logo_' . time() . '.' . $ext;
        $target = __DIR__ . '/../assets/images/' . $filename;
        if (!is_dir(__DIR__ . '/../assets/images/')) {
            mkdir(__DIR__ . '/../assets/images/', 0777, true);
        }
        if (move_uploaded_file($_FILES['logo_file']['tmp_name'], $target)) {
            $logo_path = '/assets/images/' . $filename;
            $stmt = db()->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES ('site_logo', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->execute([$logo_path, $logo_path]);
        }
    }

    // Handle favicon upload if provided
    if (isset($_FILES['favicon_file']) && $_FILES['favicon_file']['error'] === 0) {
        $ext = pathinfo($_FILES['favicon_file']['name'], PATHINFO_EXTENSION);
        $filename = 'favicon_' . time() . '.' . $ext;
        $target = __DIR__ . '/../assets/images/' . $filename;
        if (!is_dir(__DIR__ . '/../assets/images/')) {
            mkdir(__DIR__ . '/../assets/images/', 0777, true);
        }
        if (move_uploaded_file($_FILES['favicon_file']['tmp_name'], $target)) {
            $favicon_path = '/assets/images/' . $filename;
            $stmt = db()->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES ('site_favicon', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->execute([$favicon_path, $favicon_path]);
        }
    }

    // Handle certificate upload if provided
    if (isset($_FILES['certificate_files']) && !empty($_FILES['certificate_files']['name'][0])) {
        $paths = [];
        foreach ($_FILES['certificate_files']['name'] as $i => $name) {
            if ($_FILES['certificate_files']['error'][$i] === 0) {
                $ext = pathinfo($name, PATHINFO_EXTENSION);
                $filename = 'certificate_' . time() . '_' . $i . '.' . $ext;
                $target = __DIR__ . '/../assets/images/' . $filename;
                if (!is_dir(__DIR__ . '/../assets/images/')) {
                    mkdir(__DIR__ . '/../assets/images/', 0777, true);
                }
                if (move_uploaded_file($_FILES['certificate_files']['tmp_name'][$i], $target)) {
                    $paths[] = '/assets/images/' . $filename;
                }
            }
        }
        if (!empty($paths)) {
            $certificate_path = json_encode($paths);
            $stmt = db()->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES ('site_certificate', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->execute([$certificate_path, $certificate_path]);
        }
    }
    
    $success = true;
}

$email_verify = getSetting('email_verification_enabled', '0');
$mobile_verify = getSetting('mobile_verification_enabled', '0');
$universal_code = getSetting('universal_verification_code', '');
$site_logo = getSetting('site_logo', '');
$site_favicon = getSetting('site_favicon', '');
$site_certificate = getSetting('site_certificate', '');
$trc20_addr = getSetting('usdt_trc20_address', '');
$erc20_addr = getSetting('usdt_erc20_address', '');
$bep20_addr = getSetting('usdt_bep20_address', '');
$service_link = getSetting('service_link', '');
$site_name = getSetting('site_name', 'Byro');
$ios_url = getSetting('ios_download_url', '#');
$android_url = getSetting('android_download_url', '#');
$apk_url = getSetting('apk_download_url', '/downloads/byro.apk');

$title = '后台设置';
ob_start();
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div class="d-flex align-items-center gap-3">
        <a href="index.php" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-left"></i> 返回</a>
        <h4 class="mb-0">系统设置</h4>
    </div>
</div>
<div class="row">
    <div class="col-md-8">
        <div class="table-container">
            <h5 class="fw-bold mb-4">系统全局配置</h5>
            
            <?php if (isset($success)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    设置已成功保存！
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data">
                <div class="mb-4">
                    <label class="form-label fw-bold">网站名称</label>
                    <input type="text" name="site_name" class="form-control" value="<?= htmlspecialchars($site_name) ?>">
                </div>

                <div class="mb-4">
                    <label class="form-label fw-bold">网站 LOGO</label>
                    <div class="d-flex align-items-center gap-3 mb-2">
                        <?php if ($site_logo): ?>
                            <div class="bg-dark p-2 rounded">
                                <img src="<?= $site_logo ?>?v=<?= time() ?>" height="40" class="d-block">
                            </div>
                        <?php endif; ?>
                        <input type="file" name="logo_file" class="form-control">
                    </div>
                    <div class="form-text">上传后将同步更新网站所有页面的 LOGO。建议使用透明 PNG。</div>
                </div>

                <div class="mb-4">
                    <label class="form-label fw-bold">网站图标 (Favicon)</label>
                    <div class="d-flex align-items-center gap-3 mb-2">
                        <?php if ($site_favicon): ?>
                            <div class="bg-white p-2 rounded border">
                                <img src="<?= $site_favicon ?>" height="32" width="32" class="d-block">
                            </div>
                        <?php endif; ?>
                        <input type="file" name="favicon_file" class="form-control">
                    </div>
                    <div class="form-text">上传后将同步更新浏览器标签页图标。建议使用 32x32 或 64x64 的正方形图片。</div>
                </div>

                <div class="mb-4">
                    <label class="form-label fw-bold">平台注册证书</label>
                    <div class="mb-2">
                        <?php 
                        if ($site_certificate): 
                            $certs = json_decode($site_certificate, true);
                            if (!is_array($certs)) $certs = [$site_certificate];
                            ?>
                            <div class="d-flex flex-wrap gap-2 mb-2">
                                <?php foreach ($certs as $cert): ?>
                                    <div class="bg-light p-1 rounded border position-relative">
                                        <img src="<?= $cert ?>" height="60" class="d-block shadow-sm">
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                        <input type="file" name="certificate_files[]" class="form-control" multiple>
                    </div>
                    <div class="form-text">支持多选。上传后，用户可在个人中心点击“注册证书”查看所有证书。</div>
                </div>

                <hr class="my-4">
                <h6 class="fw-bold mb-3 text-primary"><i class="bi bi-wallet2 me-2"></i>充值地址配置</h6>

                <div class="mb-3">
                    <label class="form-label fw-bold">USDT (TRC20) 地址</label>
                    <input type="text" name="usdt_trc20_address" class="form-control" value="<?= htmlspecialchars($trc20_addr) ?>" placeholder="请输入 TRC20 钱包地址">
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">USDT (ERC20) 地址</label>
                    <input type="text" name="usdt_erc20_address" class="form-control" value="<?= htmlspecialchars($erc20_addr) ?>" placeholder="请输入 ERC20 钱包地址">
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">USDT (BEP20) 地址</label>
                    <input type="text" name="usdt_bep20_address" class="form-control" value="<?= htmlspecialchars($bep20_addr) ?>" placeholder="请输入 BEP20 钱包地址">
                </div>

                <hr class="my-4">
                <h6 class="fw-bold mb-3 text-primary"><i class="bi bi-phone me-2"></i>APP 下载设置</h6>
                <div class="mb-3">
                    <label class="form-label fw-bold">iOS 下载/描述链接</label>
                    <input type="text" name="ios_download_url" class="form-control" value="<?= htmlspecialchars($ios_url) ?>" placeholder="https://...">
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">Android 下载链接 (Google Play)</label>
                    <input type="text" name="android_download_url" class="form-control" value="<?= htmlspecialchars($android_url) ?>" placeholder="https://...">
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">Android APK 直接下载链接</label>
                    <input type="text" name="apk_download_url" class="form-control" value="<?= htmlspecialchars($apk_url) ?>" placeholder="/downloads/byro.apk">
                </div>

                <hr class="my-4">
                <h6 class="fw-bold mb-3 text-primary"><i class="bi bi-currency-exchange me-2"></i>法币汇率配置 (1 USDT = ?)</h6>
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label small fw-bold">MYR (马来西亚林吉特)</label>
                        <input type="number" step="0.01" name="rate_MYR" class="form-control" value="<?= htmlspecialchars(getSetting('rate_MYR', '')) ?>" placeholder="例如: 4.45">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label small fw-bold">CNY (人民币)</label>
                        <input type="number" step="0.01" name="rate_CNY" class="form-control" value="<?= htmlspecialchars(getSetting('rate_CNY', '')) ?>" placeholder="例如: 7.25">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label small fw-bold">EUR (欧元)</label>
                        <input type="number" step="0.01" name="rate_EUR" class="form-control" value="<?= htmlspecialchars(getSetting('rate_EUR', '')) ?>" placeholder="例如: 0.95">
                    </div>
                    <div class="col-12 mt-2">
                        <div class="form-text text-warning"><i class="bi bi-exclamation-triangle-fill me-1"></i>留空则使用系统自动获取的实时汇率。建议在 API 延迟或汇率波动剧烈时手动设置。</div>
                    </div>
                </div>

                <hr class="my-4">
                <h6 class="fw-bold mb-3 text-primary"><i class="bi bi-shield-check me-2"></i>安全与功能</h6>

                <div class="mb-4">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <div class="form-check form-switch p-3 bg-light border rounded-3">
                                <input class="form-check-input ms-0 me-2" type="checkbox" name="email_verification_enabled" value="1" id="emailSwitch" <?= $email_verify == '1' ? 'checked' : '' ?> onchange="toggleVerifyUI()">
                                <label class="form-check-label fw-bold" for="emailSwitch">开启邮箱验证码</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check form-switch p-3 bg-light border rounded-3">
                                <input class="form-check-input ms-0 me-2" type="checkbox" name="mobile_verification_enabled" value="1" id="mobileSwitch" <?= $mobile_verify == '1' ? 'checked' : '' ?> onchange="toggleVerifyUI()">
                                <label class="form-check-label fw-bold" for="mobileSwitch">开启手机验证码</label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mt-3">
                        <label class="form-label fw-bold text-danger"><i class="bi bi-star-fill me-1"></i> 万能验证码 (设置后注册输入此码直接通过)</label>
                        <input type="text" name="universal_verification_code" class="form-control" value="<?= htmlspecialchars($universal_code) ?>" placeholder="例如: 882937 (建议6位不规则数字)">
                        <div class="form-text">用户注册时填写此码将跳过实际验证码校验，方便测试或特殊用户。</div>
                    </div>

                    <div id="emailVerifyBox" class="mt-3 p-3 bg-white border rounded-3" style="display: <?= $email_verify == '1' ? 'block' : 'none' ?>;">
                        <h6 class="fw-bold mb-3 text-primary"><i class="bi bi-envelope-at me-1"></i> 邮箱 SMTP 配置</h6>
                        <div class="row g-2 mb-3">
                            <div class="col-md-8">
                                <label class="form-label small text-muted mb-1">SMTP 主机</label>
                                <input type="text" name="smtp_host" class="form-control form-control-sm" value="<?= htmlspecialchars(getSetting('smtp_host', '')) ?>" placeholder="如: smtp.gmail.com">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label small text-muted mb-1">端口</label>
                                <input type="text" name="smtp_port" class="form-control form-control-sm" value="<?= htmlspecialchars(getSetting('smtp_port', '587')) ?>" placeholder="587">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small text-muted mb-1">账号 / 邮箱</label>
                                <input type="text" name="smtp_user" class="form-control form-control-sm" value="<?= htmlspecialchars(getSetting('smtp_user', '')) ?>" placeholder="your-email@example.com">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small text-muted mb-1">授权码 / 密码</label>
                                <input type="password" name="smtp_pass" class="form-control form-control-sm" value="<?= htmlspecialchars(getSetting('smtp_pass', '')) ?>" placeholder="********">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small text-muted mb-1">安全协议</label>
                                <?php $smtp_secure = getSetting('smtp_secure', 'tls'); ?>
                                <select name="smtp_secure" class="form-select form-select-sm">
                                    <option value="tls" <?= $smtp_secure === 'tls' ? 'selected' : '' ?>>TLS</option>
                                    <option value="ssl" <?= $smtp_secure === 'ssl' ? 'selected' : '' ?>>SSL</option>
                                    <option value="none" <?= $smtp_secure === 'none' ? 'selected' : '' ?>>无</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small text-muted mb-1">发件人姓名</label>
                                <input type="text" name="mail_from_name" class="form-control form-control-sm" value="<?= htmlspecialchars(getSetting('mail_from_name', 'Byro Exchange')) ?>">
                            </div>
                            <div class="col-md-12">
                                <label class="form-label small text-muted mb-1">发件人邮箱</label>
                                <input type="email" name="mail_from_email" class="form-control form-control-sm" value="<?= htmlspecialchars(getSetting('mail_from_email', 'no-reply@yourdomain.com')) ?>">
                            </div>
                        </div>
                        <label class="form-label small fw-bold text-muted mb-1">邮箱备选接口配置 (可选)</label>
                        <textarea name="verification_api_config" class="form-control form-control-sm" rows="2" placeholder="在此填写其他验证逻辑所需的参数..."><?= htmlspecialchars(getSetting('verification_api_config', '')) ?></textarea>
                    </div>

                    <div id="mobileVerifyBox" class="mt-3 p-3 bg-white border rounded-3" style="display: <?= $mobile_verify == '1' ? 'block' : 'none' ?>;">
                        <h6 class="fw-bold mb-3 text-success"><i class="bi bi-phone me-1"></i> 手机短信接口配置</h6>
                        <label class="form-label small fw-bold text-muted mb-1">短信 API 配置内容</label>
                        <textarea name="mobile_api_config" class="form-control form-control-sm" rows="4" placeholder="在此填写手机短信接口的 JSON 或 Key 等配置信息..."><?= htmlspecialchars(getSetting('mobile_api_config', '')) ?></textarea>
                        <div class="form-text small mt-1">请填写您的短信服务商提供的 API 密钥、签名等信息。</div>
                    </div>
                </div>

                <script>
                function toggleVerifyUI() {
                    const eBox = document.getElementById('emailVerifyBox');
                    const mBox = document.getElementById('mobileVerifyBox');
                    const eSw = document.getElementById('emailSwitch');
                    const mSw = document.getElementById('mobileSwitch');
                    eBox.style.display = eSw.checked ? 'block' : 'none';
                    mBox.style.display = mSw.checked ? 'block' : 'none';
                }
                </script>
                
                <div class="mb-4">
                    <label class="form-label fw-bold">在线客服链接</label>
                    <input type="text" name="service_link" class="form-control" value="<?= htmlspecialchars($service_link) ?>" placeholder="https://...">
                </div>

                <hr class="my-4">
                
                <button type="submit" class="btn btn-primary px-5 btn-lg">
                    <i class="bi bi-check-lg me-1"></i> 提交保存
                </button>
            </form>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card p-4 border-0 shadow-sm card-dismissible card-auto-dismiss" data-card-id="settings_instructions">
            <h6 class="fw-bold mb-3">使用说明</h6>
            <ul class="small text-muted ps-3 mb-0">
                <li class="mb-2"><strong>网站名称：</strong>影响浏览器标签页标题。</li>
                <li class="mb-2"><strong>LOGO：</strong>上传后会自动替换后台左上角及前端所有引用处。</li>
                <li class="mb-2"><strong>充值地址：</strong>对应前端充值页面的三个网络，请务必填写正确。</li>
                <li class="mb-2"><strong>验证码：</strong>若未配置 SMTP 邮件服务，建议保持关闭或使用固定验证码。</li>
            </ul>
        </div>
    </div>
</div>
<?php
$content = ob_get_clean();
renderAdminPage($content, $title);
?>