<?php
require_once dirname(__DIR__, 2) . '/wizwizxui-timebot/services/PanelBridge.php';
$xuiEnv = PanelBridge::loadXuiEnv();
$envPath = PanelBridge::envFilePath();
$envExists = file_exists($envPath);
?>

<div class="grid gap-4 mt-4 mb-6">
    <!-- تنظیمات سراسری 3x-ui -->
    <div class="shadow-md min-w-0 p-4 bg-white rounded-lg dark:bg-gray-800 border dark:border-gray-700">
        <h3 class="text-sm font-bold text-gray-700 dark:text-gray-200 mb-1">تنظیمات سراسری 3x-ui (env)</h3>
        <p class="text-xs text-gray-500 mb-3">
            فایل env در این مسیر ساخته می‌شود:
            <code dir="ltr" class="text-purple-700"><?php echo htmlspecialchars($envPath); ?></code>
            <?php if ($envExists): ?>
                <span class="text-green-600"> — موجود</span>
            <?php else: ?>
                <span class="text-orange-600"> — هنوز ساخته نشده</span>
            <?php endif; ?>
        </p>
        <form id="xui-env-form" class="grid gap-2 md:grid-cols-2">
            <div class="flex relative md:col-span-2">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs">Panel URL (پیش‌فرض)</span>
                <input name="XUI_BASE_URL" value="<?php echo htmlspecialchars($xuiEnv['XUI_BASE_URL'] ?? ''); ?>" type="text" dir="ltr" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200" placeholder="https://panel.example.com"/>
            </div>
            <div class="flex relative">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs">Auth mode</span>
                <select name="XUI_AUTH_MODE" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200">
                    <option value="auto" <?php echo ($xuiEnv['XUI_AUTH_MODE'] ?? '') === 'auto' ? 'selected' : ''; ?>>auto (token یا user/pass)</option>
                    <option value="bearer" <?php echo in_array($xuiEnv['XUI_AUTH_MODE'] ?? '', ['bearer', 'token'], true) ? 'selected' : ''; ?>>bearer (فقط Token)</option>
                    <option value="cookie" <?php echo ($xuiEnv['XUI_AUTH_MODE'] ?? '') === 'cookie' ? 'selected' : ''; ?>>cookie (login)</option>
                </select>
            </div>
            <div class="flex relative">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs">API Token</span>
                <input name="XUI_API_TOKEN" value="<?php echo htmlspecialchars($xuiEnv['XUI_API_TOKEN'] ?? ''); ?>" type="text" dir="ltr" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200" placeholder="از Settings → Security در پنل"/>
            </div>
            <div class="flex relative md:col-span-2">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs">Sub URL</span>
                <input name="XUI_SUBSCRIPTION_BASE_URL" value="<?php echo htmlspecialchars($xuiEnv['XUI_SUBSCRIPTION_BASE_URL'] ?? ''); ?>" type="text" dir="ltr" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200" placeholder="https://sub.example.com:10882"/>
            </div>
            <div class="flex relative">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs">Sub path</span>
                <input name="XUI_SUB_PATH" value="<?php echo htmlspecialchars($xuiEnv['XUI_SUB_PATH'] ?? '/sub/'); ?>" type="text" dir="ltr" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
            </div>
            <div class="flex relative">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs">Timeout</span>
                <input name="XUI_HTTP_TIMEOUT_SECONDS" value="<?php echo htmlspecialchars($xuiEnv['XUI_HTTP_TIMEOUT_SECONDS'] ?? '15'); ?>" type="number" min="5" max="60" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
            </div>
            <div class="flex gap-2 md:col-span-2 mt-1">
                <button type="button" id="btn-save-xui-env" class="px-4 py-2 text-sm rounded-lg text-white bg-purple-600 hover:bg-purple-700">ذخیره env</button>
                <button type="button" id="btn-test-xui-env" class="px-4 py-2 text-sm rounded-lg text-white bg-blue-600 hover:bg-blue-700">تست با env</button>
                <span id="xui-env-result" class="text-xs self-center text-gray-600 dark:text-gray-300"></span>
            </div>
        </form>
    </div>

    <!-- افزودن سرور -->
    <div class="shadow-md min-w-0 p-4 bg-white rounded-lg dark:bg-gray-800 border dark:border-gray-700">
        <h3 class="text-sm font-bold text-gray-700 dark:text-gray-200 mb-3">افزودن سرور جدید</h3>
        <form method="post" id="form-add-server" class="grid gap-2 md:grid-cols-2">
            <div class="flex relative">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs"><?php echo $_LANG['Servername']; ?></span>
                <input required name="title_server" type="text" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
            </div>
            <div class="flex relative">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs"><?php echo $_LANG['Remark']; ?></span>
                <input required name="remark_server" type="text" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
            </div>
            <div class="flex relative">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs"><?php echo $_LANG['Count']; ?></span>
                <input required name="ucount_server" value="100" type="text" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
            </div>
            <div class="flex relative">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs"><?php echo $_LANG['Flag']; ?></span>
                <input required name="flag_server" value="🇮🇷" type="text" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
            </div>
            <div class="flex relative md:col-span-2">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs"><?php echo $_LANG['Panelurl']; ?></span>
                <input required name="panel_url_server" type="url" dir="ltr" placeholder="https://host:2053/path" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
            </div>
            <div class="flex relative md:col-span-2">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs">نوع پنل</span>
                <select name="panel_type_server" id="add-panel-type-select" class="panel-type-select rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200">
                    <option value="sanaei">3x-ui v3 (سنایی)</option>
                    <option value="marzban">Marzban</option>
                    <option value="pasarguard">Pasarguard</option>
                </select>
            </div>

            <!-- فیلدهای اختصاصی X-UI / Marzban -->
            <div class="xui-fields md:col-span-2 grid grid-cols-2 gap-2">
                <div class="flex relative">
                    <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs">API Token (اختیاری)</span>
                    <input name="api_token_server" type="text" dir="ltr" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
                </div>
                <div class="flex relative">
                    <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs">SNI</span>
                    <input name="sni_server" type="text" dir="ltr" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
                </div>
                <div class="flex relative">
                    <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs">IP</span>
                    <input name="ip_server" type="text" dir="ltr" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
                </div>
                <div class="flex relative">
                    <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs">آدرس ساب (اختیاری)</span>
                    <input name="subscription_base_url_server" type="text" dir="ltr" placeholder="https://sub.example.com:10882" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
                </div>
            </div>

            <!-- فیلدهای مشترک: username / password -->
            <div class="flex relative">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs"><?php echo $_LANG['Username']; ?></span>
                <input required name="username_server" type="text" dir="ltr" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
            </div>
            <div class="flex relative">
                <span class="rounded-l-md inline-flex items-center px-3 border bg-white border-gray-300 text-gray-500 text-xs"><?php echo $_LANG['Password']; ?></span>
                <input required name="password_server" type="password" dir="ltr" class="rounded-r-lg flex-1 border border-gray-300 py-2 px-3 text-sm dark:bg-gray-700 dark:text-gray-200"/>
            </div>

            <!-- نکته راهنمای پاسارگارد -->
            <div class="pasarguard-hint md:col-span-2 hidden">
                <p class="text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2">
                    🔷 <strong>Pasarguard:</strong> فقط آدرس پنل، یوزرنیم و پسورد ادمین نیاز است. سایر فیلدها (SNI، IP، API Token) برای این نوع پنل استفاده نمی‌شوند.
                </p>
            </div>

            <div class="md:col-span-2 flex flex-wrap items-center gap-2 mt-1">
                <button type="button" class="panel-test-btn px-4 py-2 text-sm rounded-lg text-white bg-blue-600 hover:bg-blue-700" data-target="#form-add-server">تست اتصال</button>
                <label class="text-xs text-gray-600 dark:text-gray-300 flex items-center gap-1">
                    <input type="checkbox" name="test_before_add" value="1" checked/>
                    قبل از ذخیره، اتصال تست شود
                </label>
                <button name="btn_add_server" type="submit" class="px-4 py-2 text-sm rounded-lg text-white bg-green-600 hover:bg-green-700">ذخیره سرور</button>
                <span class="panel-test-result text-xs text-gray-600 dark:text-gray-300"></span>
            </div>
        </form>
    </div>
</div>

<script>
(function () {
    function togglePanelFields(selectEl) {
        var val = $(selectEl).val();
        var $form = $(selectEl).closest('form');
        if (val === 'pasarguard') {
            $form.find('.xui-fields').hide();
            $form.find('.pasarguard-hint').show();
        } else {
            $form.find('.xui-fields').show();
            $form.find('.pasarguard-hint').hide();
        }
    }

    $(document).on('change', '.panel-type-select', function () {
        togglePanelFields(this);
    });

    // Init on load
    $('.panel-type-select').each(function () { togglePanelFields(this); });

    function panelTestFromForm($form, $result) {
        $result.text('در حال تست...');
        $.post('api/panel-test.php', {
            panel_type: $form.find('[name=panel_type_server]').val() || 'sanaei',
            panel_url: $form.find('[name=panel_url_server]').val(),
            username: $form.find('[name=username_server]').val(),
            password: $form.find('[name=password_server]').val(),
            api_token: $form.find('[name=api_token_server]').val(),
            subscription_base_url: $form.find('[name=subscription_base_url_server]').val()
        }).done(function (data) {
            if (typeof data === 'string') {
                try { data = JSON.parse(data); } catch (e) {}
            }
            if (data && data.success) {
                $result.css('color', '#1ebb0c').text('✓ ' + (data.msg || 'OK') + (data.detail ? ' — ' + data.detail : ''));
            } else {
                $result.css('color', '#c60313').text('✗ ' + ((data && data.msg) || 'خطا'));
            }
        }).fail(function () {
            $result.css('color', '#c60313').text('✗ خطای شبکه یا دسترسی');
        });
    }

    $(document).on('click', '.panel-test-btn', function () {
        var target = $(this).data('target');
        var $form = $(target);
        var $result = $form.find('.panel-test-result').first();
        if (!$result.length) {
            $result = $(this).siblings('.panel-test-result');
        }
        panelTestFromForm($form, $result);
    });

    $('#btn-save-xui-env').on('click', function () {
        var $r = $('#xui-env-result');
        $r.text('در حال ذخیره...');
        $.post('api/save-xui-env.php', $('#xui-env-form').serialize()).done(function (data) {
            if (typeof data === 'string') {
                try { data = JSON.parse(data); } catch (e) {}
            }
            if (data && data.success) {
                $r.css('color', '#1ebb0c').text('✓ ' + data.msg);
            } else {
                $r.css('color', '#c60313').text('✗ ' + ((data && data.msg) || 'خطا'));
            }
        });
    });

    $('#btn-test-xui-env').on('click', function () {
        var $r = $('#xui-env-result');
        var panelUrl = $('input[name=XUI_BASE_URL]').val() || $('input[name=XUI_SUBSCRIPTION_BASE_URL]').val() || '';
        if (!panelUrl) {
            $r.css('color', '#c60313').text('Panel URL یا Sub URL را در env وارد کنید');
            return;
        }
        $r.text('در حال تست env...');
        $.post('api/panel-test.php', {
            panel_type: 'sanaei',
            panel_url: panelUrl,
            username: '',
            password: '',
            api_token: $('input[name=XUI_API_TOKEN]').val(),
            subscription_base_url: $('input[name=XUI_SUBSCRIPTION_BASE_URL]').val()
        }).done(function (data) {
            if (typeof data === 'string') {
                try { data = JSON.parse(data); } catch (e) {}
            }
            if (data && data.success) {
                $r.css('color', '#1ebb0c').text('✓ ' + data.msg);
            } else {
                $r.css('color', '#c60313').text('✗ ' + ((data && data.msg) || 'خطا'));
            }
        });
    });
})();
</script>
