<?php
require_once __DIR__ . '/../MPHX/common.php';

$user = check_user();
$bt = $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$user['btid']}'");

$bt_api = new bt_api();
$protocol = isset($bt['aqfw']) && $bt['aqfw'] == 'true' ? 'https' : 'http';
$bt_api->BT_PANEL = $protocol . '://' . $bt['ip'] . ':' . $bt['dk'];
$bt_api->BT_KEY = $bt['key'];

// 重置数据库密码
if (isset($_POST['reset_password'])) {
    $new_password = trim($_POST['new_password']);
    if (empty($new_password)) {
        $error = '请输入新密码';
    } else {
        $db_info = $bt_api->databascx($user['sqldb']);
        $db_id = null;
        if ($db_info && isset($db_info['data']) && is_array($db_info['data'])) {
            foreach ($db_info['data'] as $row) {
                if (isset($row['name']) && $row['name'] == $user['sqldb']) {
                    $db_id = $row['id'];
                    break;
                }
                if (isset($row['username']) && $row['username'] == $user['sqluser']) {
                    $db_id = $row['id'];
                    break;
                }
            }
        }
        if ($db_id === null) {
            $error = '数据库不存在';
        } else {
            $bt_result = $bt_api->setmysqlpass($db_id, $user['sqldb'], $new_password);
            if ($bt_result && isset($bt_result['status']) && $bt_result['status'] == true) {
                $new_password_escaped = $DB->escape($new_password);
                $user_id_escaped = intval($user['id']);
                $DB->query("UPDATE `zj` SET `sqlpass`='{$new_password_escaped}' WHERE `id`='{$user_id_escaped}'");
                $user['sqlpass'] = $new_password;
                $success = '密码重置成功';
            } else {
                $error = isset($bt_result['msg']) ? $bt_result['msg'] : '重置失败';
            }
        }
    }
}

// phpMyAdmin
$phpmyadmin_url = '';
$phpmyadmin_error = '';
$skip_api = false;

try {
    $data = $bt_api->api_sql_cf();
    if (!$data || !isset($data['status']) || $data['status'] !== true) {
        $set_result = $bt_api->api_sql_set('start');
        $data = $bt_api->api_sql_cf();
    }
    if ($data && isset($data['status']) && $data['status'] === true && isset($data['ext']['url'])) {
        $phpmyadmin_url = $data['ext']['url'];
    } else {
        $phpmyadmin_error = '无法获取phpMyAdmin地址';
        $skip_api = true;
    }
} catch (Exception $e) {
    $phpmyadmin_error = 'API调用异常';
    $skip_api = true;
}
?>
<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/all.min.css">
<link rel="stylesheet" href="css/style.css">
<script src="/static/js/jquery.min.js"></script>

<style>
    html, body { overflow-y: auto; }
    .page-container { padding: 15px; }
    .page-title { font-size: 16px; color: #202124; margin-bottom: 15px; display: flex; align-items: center; gap: 8px; font-weight: 500; }
    
    /* 数据库信息网格 - 三列并排显示 */
    .db-info-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 14px;
        margin-bottom: 18px;
    }
    
    @media (max-width: 576px) {
        /* 手机竖屏时减小间隙 */
        .db-info-grid {
            gap: 8px;
        }
        .db-info-card {
            padding: 12px 8px;
        }
        .db-info-card .value {
            font-size: 12px;
        }
    }
    
    .db-info-card {
        background: #fff;
        border-radius: 6px;
        padding: 16px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.06);
        border: 1px solid #e8eaed;
        text-align: center;
    }
    
    .db-info-card .icon {
        width: 40px;
        height: 40px;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        margin: 0 auto 10px;
        background: #e6f4ea;
        color: #188038;
    }
    
    .db-info-card .label {
        color: #5f6368;
        font-size: 12px;
        margin-bottom: 4px;
        font-weight: 400;
    }
    
    .db-info-card .value {
        font-size: 14px;
        font-weight: 600;
        color: #202124;
        word-break: break-all;
        font-family: 'Courier New', monospace;
    }
    
    /* 操作卡片 */
    .action-card {
        background: #fff;
        border-radius: 6px;
        padding: 16px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.06);
        border: 1px solid #e8eaed;
        margin-bottom: 14px;
    }
    
    .action-card .card-header {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        font-weight: 500;
        color: #202124;
        margin-bottom: 12px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e8eaed;
    }
    
    .action-card .card-header i {
        color: #188038;
    }
    
    /* phpMyAdmin区域 */
    .phpmyadmin-content {
        display: flex;
        align-items: center;
        gap: 20px;
        flex-wrap: wrap;
    }
    
    .credential-box {
        flex: 1;
        min-width: 250px;
        background: #f8f9fa;
        border-radius: 6px;
        padding: 12px 15px;
    }
    
    .credential-row {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 8px;
    }
    
    .credential-row:last-child {
        margin-bottom: 0;
    }
    
    .credential-label {
        font-size: 13px;
        color: #5f6368;
        min-width: 50px;
    }
    
    .credential-value {
        background: #fff;
        padding: 6px 12px;
        border-radius: 4px;
        font-family: 'Courier New', monospace;
        font-size: 13px;
        color: #202124;
        flex: 1;
        border: 1px solid #e8eaed;
    }
    
    /* 按钮样式 */
    .btn-group {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }
    
    .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.2s;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        font-weight: 500;
    }
    
    .btn-primary {
        background: #188038;
        color: #fff;
    }
    
    .btn-primary:hover {
        background: #137333;
    }
    
    .btn-secondary {
        background: #f1f3f4;
        color: #5f6368;
        border: 1px solid #dadce0;
    }
    
    .btn-secondary:hover {
        background: #e8eaed;
    }
    
    /* 表单样式 */
    .password-form {
        display: flex;
        gap: 10px;
        align-items: flex-end;
        flex-wrap: wrap;
    }
    
    .form-group {
        flex: 1;
        min-width: 200px;
    }
    
    .form-group label {
        display: block;
        font-size: 13px;
        color: #5f6368;
        margin-bottom: 6px;
    }
    
    .form-group input {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #dadce0;
        border-radius: 4px;
        font-size: 13px;
        box-sizing: border-box;
        transition: border-color 0.2s;
    }
    
    .form-group input:focus {
        outline: none;
        border-color: #188038;
    }
    
    /* 提示框 */
    .alert {
        padding: 10px 12px;
        border-radius: 4px;
        margin-bottom: 12px;
        font-size: 13px;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .alert-success { background: #e6f4ea; color: #137333; border: 1px solid #ceead6; }
    .alert-danger { background: #fce8e6; color: #c5221f; border: 1px solid #fad2cf; }
    .alert-info { background: #e8f0fe; color: #1967d2; border: 1px solid #d2e3fc; }
    .alert-warning { background: #fef7e0; color: #b06000; border: 1px solid #feefc3; }
    
    /* 响应式 */
    @media (max-width: 768px) {
        .phpmyadmin-content {
            flex-direction: column;
            align-items: stretch;
        }
        
        .credential-box {
            min-width: 100%;
        }
        
        .password-form {
            flex-direction: column;
        }
        
        .form-group {
            min-width: 100%;
        }
        
        .btn-group {
            width: 100%;
        }
        
        .btn {
            flex: 1;
            justify-content: center;
        }
    }
</style>

<div class="page-container">
    <div class="page-title">
        <i class="fas fa-database"></i> <?php echo L('title', 'sql'); ?>
    </div>
    
    <?php if (isset($success)): ?>
    <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo $success; ?></div>
    <?php endif; ?>
    
    <?php if (isset($error)): ?>
    <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?php echo $error; ?></div>
    <?php endif; ?>
    
    <!-- 数据库信息卡片 - 三列并排显示 -->
    <div class="db-info-grid">
        <div class="db-info-card">
            <div class="icon">
                <i class="fas fa-database"></i>
            </div>
            <div class="label"><?php echo L('database_name', 'dashboard'); ?></div>
            <div class="value"><?php echo $user['sqldb']; ?></div>
        </div>
        <div class="db-info-card">
            <div class="icon">
                <i class="fas fa-user"></i>
            </div>
            <div class="label"><?php echo L('database_user', 'sql'); ?></div>
            <div class="value"><?php echo $user['sqluser']; ?></div>
        </div>
        <div class="db-info-card">
            <div class="icon">
                <i class="fas fa-key"></i>
            </div>
            <div class="label"><?php echo L('database_password', 'sql'); ?></div>
            <div class="value"><?php echo $user['sqlpass']; ?></div>
        </div>
    </div>
    
    <!-- phpMyAdmin -->
    <div class="action-card">
        <div class="card-header">
            <i class="fas fa-external-link-alt"></i> phpMyAdmin
        </div>
        <div class="card-body">
            <?php if ($phpmyadmin_url && !$skip_api): ?>
            <div class="alert alert-info" style="margin-bottom: 12px;">
                <i class="fas fa-check-circle"></i> phpMyAdmin <?php echo L('operation_success', 'common'); ?>
            </div>
            <div class="phpmyadmin-content">
                <div class="credential-box">
                    <div class="credential-row">
                        <span class="credential-label">用户名</span>
                        <code class="credential-value"><?php echo $user['sqluser']; ?></code>
                    </div>
                    <div class="credential-row">
                        <span class="credential-label">密码</span>
                        <code class="credential-value"><?php echo $user['sqlpass']; ?></code>
                    </div>
                </div>
                <div class="btn-group">
                    <a href="<?php echo $phpmyadmin_url; ?>" target="_blank" class="btn btn-primary">
                        <i class="fas fa-external-link-alt"></i> 打开 phpMyAdmin
                    </a>
                    <button type="button" class="btn btn-secondary" onclick="copyCredentials()">
                        <i class="fas fa-copy"></i> 复制
                    </button>
                </div>
            </div>
            <?php else: ?>
            <div class="alert alert-warning" style="margin-bottom: 12px;">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $phpmyadmin_error ?: '正在加载...' ?>
            </div>
            <a href="<?php echo $protocol . '://' . $bt['ip'] . ':' . $bt['dk'] . '/phpmyadmin/'; ?>" target="_blank" class="btn btn-primary">
                <i class="fas fa-external-link-alt"></i> 打开 phpMyAdmin
            </a>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- 重置密码 -->
    <div class="action-card">
        <div class="card-header">
            <i class="fas fa-key"></i> 重置密码
        </div>
        <div class="card-body">
            <form method="post" class="password-form">
                <div class="form-group">
                    <label>新密码</label>
                    <input type="text" name="new_password" placeholder="请输入新密码" required>
                </div>
                <div class="btn-group">
                    <button type="submit" name="reset_password" class="btn btn-primary">
                        <i class="fas fa-save"></i> 保存
                    </button>
                    <button type="button" class="btn btn-secondary" data-action="generate-password">
                        <i class="fas fa-random"></i> 生成
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="/static/js/jquery.min.js"></script>
<script>
function generatePassword() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
    let password = '';
    for (let i = 0; i < 16; i++) {
        password += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    document.querySelector('input[name="new_password"]').value = password;
}

function copyCredentials() {
    const user = '<?php echo $user['sqluser']; ?>';
    const pass = '<?php echo $user['sqlpass']; ?>';
    // 从PHP变量获取数据库地址，避免硬编码
    const host = '<?php echo isset($bt['ip']) && !empty($bt['ip']) ? $bt['ip'] : 'localhost'; ?>';
    const text = '数据库地址: ' + host + '\n用户名: ' + user + '\n密码: ' + pass;
    
    // 使用现代的 Clipboard API，如果不支持则使用备用方案
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(function() {
            showCopySuccess();
        }, function(err) {
            console.error('复制失败: ', err);
            // 备用方案
            fallbackCopyText(text);
        });
    } else {
        // 使用备用方案
        fallbackCopyText(text);
    }
}

// 备用复制方案
function fallbackCopyText(text) {
    // 创建临时文本区域
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed';
    textarea.style.left = '-9999px';
    textarea.style.top = '0';
    document.body.appendChild(textarea);
    
    try {
        textarea.focus();
        textarea.select();
        const successful = document.execCommand('copy');
        if (successful) {
            showCopySuccess();
        } else {
            alert('复制失败，请手动复制');
        }
    } catch (err) {
        console.error('复制失败: ', err);
        alert('复制失败，请手动复制');
    } finally {
        document.body.removeChild(textarea);
    }
}

// 显示复制成功提示
function showCopySuccess() {
    // 使用 layer 消息提示（如果可用）
    if (typeof layer !== 'undefined' && layer.msg) {
        layer.msg('数据库连接信息已复制到剪贴板！', {icon: 1, time: 2000});
    } else {
        alert('数据库连接信息已复制到剪贴板！');
    }
}

$(document).on('click', '[data-action="generate-password"]', function(e){ 
    e.preventDefault(); 
    generatePassword(); 
});
</script>