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

$user = check_user();
$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'];

// 调试日志
$debug_file = __DIR__ . '/../debug.log';
$log_msg = date('Y-m-d H:i:s') . ' [sql_permission] BT API - ip: ' . $bt['ip'] . ', dk: ' . $bt['dk'] . ', key: ' . $bt['key'] . ', protocol: ' . $protocol . "\n";
@file_put_contents($debug_file, $log_msg, FILE_APPEND);

// AJAX 接口：获取 / 设置 SQL 权限
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json; charset=UTF-8');

    $action = $_POST['action'];

    // 获取当前权限
    if ($action === 'getsqlpermission') {
        $db_name = isset($user['sqldb']) ? $user['sqldb'] : '';
        $db_user = isset($user['sqluser']) ? $user['sqluser'] : '';
        
        if (!$db_name && !$db_user) {
            echo json_encode(array('code' => '数据库信息不存在'));
            exit;
        }
        
        // 使用GetDatabaseAccess API获取数据库权限，需要使用数据库用户名
        $result = $bt_api->GetDatabaseAccess($db_user);

        // 调试日志 - 输出完整结果
        $debug_msg = date('Y-m-d H:i:s') . ' [sql_permission] GetDatabaseAccess result: ' . print_r($result, true) . "\n";
        @file_put_contents($debug_file, $debug_msg, FILE_APPEND);

        if ($result && isset($result['status']) && ($result['status'] === true || $result['status'] === 'true' || $result['status'] === 1 || $result['status'] === '1')) {
            // 兼容不同返回格式
            $access = '';
            if (isset($result['data']['access'])) {
                $access = $result['data']['access'];
            } elseif (isset($result['access'])) {
                $access = $result['access'];
            } elseif (isset($result['data']) && is_array($result['data'])) {
                if (isset($result['data'][0]['access'])) {
                    $access = $result['data'][0]['access'];
                }
            } elseif (isset($result['msg'])) {
                // GetDatabaseAccess API返回访问权限在msg字段中
                $access = $result['msg'];
            }

            // 调试日志 - 输出获取到的access值
            $debug_msg = date('Y-m-d H:i:s') . ' [sql_permission] 获取权限成功, access: ' . $access . "\n";
            @file_put_contents($debug_file, $debug_msg, FILE_APPEND);

            echo json_encode(array('code' => 'success', 'access' => $access));
            exit;
        }

        // 如果GetDatabaseAccess失败，尝试使用GetDatabaseInfo
        if ($db_name) {
            // 首先获取数据库ID
            $db_list = $bt_api->databascx($db_name);
            $db_id = null;
            if ($db_list && isset($db_list['data']) && is_array($db_list['data'])) {
                foreach ($db_list['data'] as $db) {
                    if (isset($db['name']) && $db['name'] == $db_name) {
                        $db_id = isset($db['id']) ? $db['id'] : null;
                        break;
                    }
                }
            }
            
            // 尝试使用数据库ID获取信息
            if ($db_id) {
                $result = $bt_api->sqlkjhq($db_id);
            } else {
                $result = $bt_api->sqlkjhq($db_name);
            }

            if ($result && isset($result['status']) && ($result['status'] === true || $result['status'] === 'true' || $result['status'] === 1)) {
                $access = '';
                if (isset($result['data']['access'])) {
                    $access = $result['data']['access'];
                } elseif (isset($result['access'])) {
                    $access = $result['access'];
                } elseif (isset($result['data']) && is_array($result['data'])) {
                    if (isset($result['data'][0]['access'])) {
                        $access = $result['data'][0]['access'];
                    }
                }

                $debug_msg = date('Y-m-d H:i:s') . ' [sql_permission] GetDatabaseInfo成功, access: ' . $access . "\n";
                @file_put_contents($debug_file, $debug_msg, FILE_APPEND);

                echo json_encode(array('code' => 'success', 'access' => $access));
                exit;
            }
        }

        // 调试日志 - 输出失败信息
        $debug_msg = date('Y-m-d H:i:s') . ' [sql_permission] 获取权限失败, result: ' . print_r($result, true) . "\n";
        @file_put_contents($debug_file, $debug_msg, FILE_APPEND);

        $msg = isset($result['msg']) ? $result['msg'] : '获取权限失败';
        echo json_encode(array('code' => $msg));
        exit;
    }

    // 设置权限
    if ($action === 'setsqlpermission') {
        $ip = isset($_POST['ip']) ? trim($_POST['ip']) : '';

        // 默认仅本地访问
        if ($ip === '') {
            $ip = 'localhost';
        }

        $db_user = isset($user['sqluser']) ? $user['sqluser'] : '';
        if (!$db_user) {
            echo json_encode(array('code' => '数据库用户不存在'));
            exit;
        }

        $result = $bt_api->mysqlqx($db_user, $ip);

        if ($result && isset($result['status']) && ($result['status'] === true || $result['status'] === 'true' || $result['status'] === 1)) {
            echo json_encode(array('code' => 'success', 'access' => $ip));
            exit;
        }

        $msg = isset($result['msg']) ? $result['msg'] : '设置权限失败';
        echo json_encode(array('code' => $msg));
        exit;
    }

    echo json_encode(array('code' => '未知操作'));
    exit;
}
?>

<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">

<style>
    .access-type {
        display: flex;
        gap: 16px;
        margin-bottom: 16px;
        flex-wrap: wrap;
    }
    .access-type label {
        display: flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
        font-weight: normal;
    }
    .access-type input[type="radio"] {
        width: auto;
        margin: 0;
    }
    @media (max-width: 768px) {
        .access-type {
            flex-direction: column;
            gap: 12px;
        }
    }
</style>

<div class="content-area">
    <div id="alertContainer"></div>
    
    <div class="page-header">
        <h2><i class="fas fa-shield-alt"></i> SQL权限设置</h2>
        <p>管理您的数据库访问权限</p>
    </div>
    
    <div class="card">
        <h3><i class="fas fa-database"></i> 数据库信息</h3>
        
        <div class="form-group">
            <label>数据库名</label>
            <input type="text" class="form-control" value="<?php echo $user['sqldb']; ?>" readonly>
        </div>
        
        <div class="form-group">
            <label>数据库用户</label>
            <input type="text" class="form-control" value="<?php echo $user['sqluser']; ?>" readonly>
        </div>
    </div>
    
    <div class="card">
        <h3><i class="fas fa-lock"></i> 访问权限设置</h3>
        
        <div class="access-type">
            <label>
                <input type="radio" name="accessType" value="local" checked> 仅本地访问
            </label>
            <label>
                <input type="radio" name="accessType" value="all"> 允许所有IP访问
            </label>
            <label>
                <input type="radio" name="accessType" value="custom"> 自定义IP访问
            </label>
        </div>
        
        <div class="form-group" id="customIpGroup" style="display: none;">
            <label for="customIp">允许访问的IP地址</label>
            <input type="text" id="customIp" class="form-control" placeholder="多个IP地址请用逗号分隔，例如：192.168.1.1,10.0.0.1">
            <small class="text-muted">留空表示仅本地访问</small>
        </div>
        
        <button type="button" class="btn btn-primary" data-action="save-permission">
            <i class="fas fa-save"></i> 保存设置
        </button>
    </div>
</div>

<script src="/static/js/jquery.min.js"></script>
<script>
function showAlert(message, type) {
    var alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    var icon = type === 'success' ? '<i class="fas fa-check-circle"></i> ' : '<i class="fas fa-exclamation-circle"></i> ';
    var alertHtml = '<div class="alert ' + alertClass + '">' + icon + message + '</div>';
    $('#alertContainer').html(alertHtml);
    setTimeout(function() {
        $('#alertContainer').html('');
    }, 3000);
}

$(document).ready(function() {
    // 切换自定义IP输入框显示
    $('input[name="accessType"]').change(function() {
        if ($(this).val() === 'custom') {
            $('#customIpGroup').show();
        } else {
            $('#customIpGroup').hide();
        }
    });

    // 初始化当前权限状态
    $.ajax({
        type: 'POST',
        url: 'sql_permission.php',
        data: {
            action: 'getsqlpermission'
        },
        dataType: 'json',
        success: function(data) {
            if (data.code === 'success' && data.access !== undefined) {
                var access = (data.access || '').toLowerCase();
                if (access === '%' || access === 'all') {
                    $('input[name=\"accessType\"][value=\"all\"]').prop('checked', true);
                    $('#customIpGroup').hide();
                } else if (access === 'localhost' || access === '127.0.0.1') {
                    $('input[name=\"accessType\"][value=\"local\"]').prop('checked', true);
                    $('#customIpGroup').hide();
                } else if (access) {
                    $('input[name=\"accessType\"][value=\"custom\"]').prop('checked', true);
                    $('#customIpGroup').show();
                    $('#customIp').val(access);
                }
            }
        }
    });
});

function savePermission(btn) {
    var $btn = $(btn);
    var originalText = $btn.html();
    $btn.addClass('btn-loading').prop('disabled', true);
    
    var accessType = $('input[name="accessType"]:checked').val();
    var ip = '';
    
    if (accessType === 'local') {
        ip = 'localhost';
    } else if (accessType === 'all') {
        ip = '%';
    } else if (accessType === 'custom') {
        ip = $('#customIp').val().trim();
    }
    
    $.ajax({
        type: 'POST',
        url: 'sql_permission.php',
        data: {
            action: 'setsqlpermission',
            ip: ip
        },
        dataType: 'json',
        success: function(data) {
            $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
            if (data.code === 'success') {
                showAlert('权限设置成功', 'success');
            } else {
                showAlert(data.code, 'error');
            }
        },
        error: function() {
            $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
            showAlert('操作失败，请重试', 'error');
        }
    });
}

$(document).on('click', '[data-action="save-permission"]', function(e){ e.preventDefault(); savePermission(this); });
</script>