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

$user = check_user();
if (!$user) {
    header('Location: /user/login.php');
    exit;
}

// 获取宝塔服务器信息
$bt = $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$user['btid']}'");

// 初始化宝塔API
$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'];

// 创建FTP账户
if (isset($_POST['action']) && $_POST['action'] == 'create_ftp') {
    $ftp_password = trim($_POST['ftp_password']);
    
    if (empty($ftp_password)) {
        $error = '请输入FTP密码';
    } else {
        // 获取网站信息
        $site_list = $bt_api->webcx($user['user']);
        $site_id = null;
        $site_path = '/www/wwwroot/' . $user['user'];
        
        if ($site_list && isset($site_list['data']) && is_array($site_list['data'])) {
            foreach ($site_list['data'] as $site) {
                if (isset($site['name']) && $site['name'] == $user['user']) {
                    $site_id = $site['id'];
                    $site_path = $site['path'] ?? $site_path;
                    break;
                }
            }
        }
        
        if ($site_id === null) {
            $error = '未找到网站，请先开通主机';
        } else {
            // 创建FTP账户
            $result = $bt_api->ftpcreate($user['user'], $ftp_password, $site_path);
            if ($result && isset($result['status']) && ($result['status'] === true || $result['status'] === 'true' || $result['status'] === 1)) {
                // 安全更新数据库
                $safe_user = $DB->escape($user['user']);
                $safe_pass = $DB->escape($ftp_password);
                $safe_id = intval($user['id']);
                $DB->query("UPDATE `zj` SET `ftpuser`='{$safe_user}', `ftppass`='{$safe_pass}' WHERE `id`='{$safe_id}'");
                $success = 'FTP账户创建成功';
                // 刷新页面
                header('Location: ' . $_SERVER['PHP_SELF']);
                exit;
            } else {
                $error = isset($result['msg']) ? $result['msg'] : '创建失败';
            }
        }
    }
}

// 修改FTP密码
if (isset($_POST['action']) && $_POST['action'] == 'update_ftp_password') {
    $new_password = trim($_POST['ftp_password']);
    
    if (empty($new_password)) {
        $error = '请输入新密码';
    } else {
        $ftp_list = $bt_api->ftpcx($user['user']);
        
        $ftp_id = null;
        $ftp_data = array();
        if ($ftp_list) {
            if (isset($ftp_list['data']) && is_array($ftp_list['data'])) {
                $ftp_data = $ftp_list['data'];
            } elseif (is_array($ftp_list) && isset($ftp_list[0])) {
                $ftp_data = $ftp_list;
            }
        }
        
        foreach ($ftp_data as $ftp) {
            if (isset($ftp['name']) && $ftp['name'] == $user['user']) {
                $ftp_id = $ftp['id'];
                break;
            }
        }
        
        if ($ftp_id === null) {
            $error = '未找到FTP账户，请先创建FTP';
        } else {
            $result = $bt_api->setftppass($ftp_id, $user['user'], $new_password);
            if ($result && isset($result['status']) && ($result['status'] === true || $result['status'] === 'true' || $result['status'] === 1)) {
                $new_password_escaped = $DB->escape($new_password);
                $user_id_escaped = intval($user['id']);
                $DB->query("UPDATE `zj` SET `ftppass`='{$new_password_escaped}' WHERE `id`='{$user_id_escaped}'");
                $success = '密码修改成功';
            } else {
                $error = isset($result['msg']) ? $result['msg'] : '修改失败';
            }
        }
    }
}

// 检查FTP是否存在
$ftp_list = $bt_api->ftpcx($user['user']);
$ftp_exists = false;
$ftp_data = array();
if ($ftp_list) {
    if (isset($ftp_list['data']) && is_array($ftp_list['data'])) {
        $ftp_data = $ftp_list['data'];
    } elseif (is_array($ftp_list) && isset($ftp_list[0])) {
        $ftp_data = $ftp_list;
    }
}
foreach ($ftp_data as $ftp) {
    if (isset($ftp['name']) && $ftp['name'] == $user['user']) {
        $ftp_exists = true;
        break;
    }
}

$ftp_username = $user['user'];
$ftp_password = $user['ftppass'];
$ftp_server = $bt['ip'];
$ftp_port = 21;
$ftp_directory = '/';
?>
<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; }
    .info-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 15px; }
    .info-box { background: #f8f9fa; padding: 12px; border-radius: 6px; text-align: center; }
    .info-box i { font-size: 20px; color: #188038; margin-bottom: 6px; display: block; }
    .info-box .label { font-size: 12px; color: #5f6368; }
    .info-box .value { font-size: 13px; color: #202124; font-weight: 500; margin-top: 4px; word-break: break-all; }
    .section { background: #fff; border: 1px solid #e8eaed; border-radius: 6px; margin-bottom: 12px; }
    .section-header { padding: 10px 15px; border-bottom: 1px solid #e8eaed; font-size: 14px; color: #202124; font-weight: 500; background: #f8f9fa; }
    .section-body { padding: 15px; }
    .form-row { display: flex; gap: 10px; margin-bottom: 12px; }
    .form-row .form-group { flex: 1; margin-bottom: 0; }
    .form-group { margin-bottom: 12px; }
    .form-group label { display: block; font-size: 13px; color: #5f6368; margin-bottom: 5px; }
    .form-group input { width: 100%; padding: 8px 10px; border: 1px solid #e8eaed; border-radius: 4px; font-size: 13px; box-sizing: border-box; }
    .form-group input:focus { outline: none; border-color: #188038; }
    .form-group input[readonly] { background: #f8f9fa; color: #5f6368; }
    .btn { padding: 8px 16px; border: none; border-radius: 4px; font-size: 13px; cursor: pointer; transition: background 0.2s; }
    .btn-primary { background: #188038; color: #fff; }
    .btn-primary:hover { background: #137333; }
    .btn-secondary { background: #5f6368; color: #fff; }
    .btn-secondary:hover { background: #3c4043; }
    .btn-success { background: #34a853; color: #fff; }
    .btn-success:hover { background: #2e8b47; }
    .alert { padding: 10px 12px; border-radius: 4px; margin-bottom: 12px; font-size: 13px; }
    .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: #fef3e8; color: #b06000; border: 1px solid #feefc3; }
    @media (max-width: 768px) {
        .page-container { padding: 10px; }
        .page-title { font-size: 15px; margin-bottom: 12px; }
        .info-grid { grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 12px; }
        .info-box { padding: 10px 6px; min-width: 0; }
        .info-box i { font-size: 18px; margin-bottom: 4px; }
        .info-box .label { font-size: 11px; }
        .info-box .value { font-size: 11px; margin-top: 2px; }
        .section { margin-bottom: 10px; }
        .section-header { padding: 8px 12px; font-size: 13px; }
        .section-body { padding: 12px; }
        .form-row { flex-direction: column; gap: 8px; }
        .form-group { margin-bottom: 10px; }
        .form-group label { font-size: 12px; margin-bottom: 4px; }
        .form-group input { padding: 6px 8px; font-size: 12px; }
        .btn { padding: 6px 12px; font-size: 12px; }
        .alert { padding: 8px 10px; font-size: 12px; margin-bottom: 10px; }
    }
</style>

<div class="page-container">
    <div class="page-title">
        <i class="fas fa-cog"></i> FTP设置
    </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; ?>
    
    <?php if (!$ftp_exists): ?>
    <div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> 未检测到FTP账户，请先创建FTP</div>
    <?php endif; ?>
    
    <div class="info-grid">
        <div class="info-box">
            <i class="fas fa-user"></i>
            <div class="content">
                <div class="label">用户名</div>
                <div class="value"><?php echo $ftp_username; ?></div>
            </div>
        </div>
        <div class="info-box">
            <i class="fas fa-server"></i>
            <div class="content">
                <div class="label">FTP主机</div>
                <div class="value"><?php echo $ftp_server; ?></div>
            </div>
        </div>
        <div class="info-box">
            <i class="fas fa-folder"></i>
            <div class="content">
                <div class="label">根目录</div>
                <div class="value"><?php echo $ftp_directory; ?></div>
            </div>
        </div>
    </div>
    
    <?php if (!$ftp_exists): ?>
    <!-- 创建FTP表单 -->
    <div class="section">
        <div class="section-header"><i class="fas fa-plus-circle"></i> 创建FTP账户</div>
        <div class="section-body">
            <form method="post" id="createFtpForm">
                <input type="hidden" name="action" value="create_ftp">
                <div class="form-row">
                    <div class="form-group">
                        <label>FTP密码</label>
                        <input type="password" name="ftp_password" id="create_ftp_password" placeholder="请输入FTP密码" required>
                    </div>
                    <div class="form-group">
                        <label>确认密码</label>
                        <input type="password" id="create_ftp_password_confirm" placeholder="再次输入" required>
                    </div>
                </div>
                <button type="submit" class="btn btn-success"><i class="fas fa-plus"></i> 创建FTP</button>
                <button type="button" class="btn btn-secondary" onclick="generatePassword('create_ftp_password', 'create_ftp_password_confirm')"><i class="fas fa-random"></i> 生成</button>
            </form>
        </div>
    </div>
    <?php else: ?>
    <!-- 修改密码表单 -->
    <div class="section">
        <div class="section-header"><i class="fas fa-key"></i> 修改密码</div>
        <div class="section-body">
            <form method="post" id="ftpForm">
                <input type="hidden" name="action" value="update_ftp_password">
                <div class="form-row">
                    <div class="form-group">
                        <label>新密码</label>
                        <input type="password" name="ftp_password" id="ftp_password" placeholder="请输入新密码" required>
                    </div>
                    <div class="form-group">
                        <label>确认密码</label>
                        <input type="password" id="ftp_password_confirm" placeholder="再次输入" required>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> 保存</button>
                <button type="button" class="btn btn-secondary" onclick="generatePassword('ftp_password', 'ftp_password_confirm')"><i class="fas fa-random"></i> 生成</button>
            </form>
        </div>
    </div>
    <?php endif; ?>
    
    <div class="section">
        <div class="section-header"><i class="fas fa-plug"></i> 连接信息</div>
        <div class="section-body">
            <div class="form-group" style="margin-bottom: 8px;">
                <label>地址</label>
                <input type="text" value="ftp://<?php echo $ftp_server; ?>:<?php echo $ftp_port; ?>" readonly>
            </div>
            <div class="form-group" style="margin-bottom: 8px;">
                <label>密码</label>
                <input type="text" value="<?php echo $ftp_password; ?>" readonly>
            </div>
            <div class="alert alert-info" style="margin: 0; padding: 8px;"><i class="fas fa-info-circle"></i> 可使用FileZilla等FTP客户端连接</div>
        </div>
    </div>
</div>

<script src="/static/js/jquery.min.js"></script>
<script>
function generatePassword(passwordId, confirmId) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+';
    let password = '';
    for (let i = 0; i < 12; i++) {
        password += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    document.getElementById(passwordId).value = password;
    document.getElementById(confirmId).value = password;
}

$('#ftpForm').on('submit', function(e) {
    const password = $('#ftp_password').val();
    const confirm = $('#ftp_password_confirm').val();
    if (password !== confirm) {
        e.preventDefault();
        alert('两次密码不一致');
        return false;
    }
    if (password.length < 6) {
        e.preventDefault();
        alert('密码至少6位');
        return false;
    }
    return true;
});

$('#createFtpForm').on('submit', function(e) {
    const password = $('#create_ftp_password').val();
    const confirm = $('#create_ftp_password_confirm').val();
    if (password !== confirm) {
        e.preventDefault();
        alert('两次密码不一致');
        return false;
    }
    if (password.length < 6) {
        e.preventDefault();
        alert('密码至少6位');
        return false;
    }
    return true;
});
</script>
