<?php

declare(strict_types=1);

/**
 * @var yii\web\View $this
 * @var \PortalPeople\datadash\models\ConfigForm $model
 * @var bool $isNew
 */

use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;

$formAction = $isNew
    ? ['/ngauge-datadash/config/create']
    : ['/ngauge-datadash/config/update', 'name' => $model->name];

$testUrl      = Url::to(['/ngauge-datadash/config/test-connection']);
$listTablesUrl = Url::to(['/ngauge-datadash/config/list-tables']);
$validateUrl  = Url::to(['/ngauge-datadash/config/validate']);
?>

<?php $form = ActiveForm::begin([
    'id'                   => 'datadash-config-form',
    'action'               => $formAction,
    'enableAjaxValidation' => true,
    'validationUrl'        => $validateUrl,
]); ?>

<div class="row">

    <!-- ── Identity ─────────────────────────────────────────── -->
    <div class="col-md-6">
        <div class="card mb-4">
            <div class="card-header">Connection Identity</div>
            <div class="card-body">

                <?php if ($isNew) { ?>
                    <?= $form->field($model, 'name')->textInput([
                        'placeholder' => 'e.g. my_connection',
                        'pattern'     => '[a-z][a-z0-9_]*',
                    ])->hint('Lowercase letters, digits and underscores only. Cannot be changed after creation.') ?>
                <?php } else { ?>
                    <div class="form-group">
                        <label class="control-label">Name</label>
                        <?= Html::textInput('', $model->name, ['class' => 'form-control', 'readonly' => true]) ?>
                        <?= Html::hiddenInput('ConfigForm[name]', $model->name) ?>
                        <p class="form-text text-muted">Name cannot be changed after creation.</p>
                    </div>
                <?php } ?>

                <?= $form->field($model, 'label')->textInput(['placeholder' => 'Human-readable label (optional)']) ?>

                <?= $form->field($model, 'enabled')->checkbox() ?>

            </div>
        </div>
    </div>

    <!-- ── Driver ─────────────────────────────────────────────── -->
    <div class="col-md-6">
        <div class="card mb-4">
            <div class="card-header">Connection Settings</div>
            <div class="card-body">

                <?= $form->field($model, 'driver')->dropDownList([
                    'mysql'  => 'MySQL / MariaDB',
                    'pgsql'  => 'PostgreSQL',
                    'sqlsrv' => 'SQL Server',
                    'sqlite' => 'SQLite',
                ], ['id' => 'datadash-driver']) ?>

                <div id="datadash-host-fields">
                    <?= $form->field($model, 'host')->textInput(['placeholder' => 'localhost']) ?>
                    <?= $form->field($model, 'port')->textInput(['type' => 'number', 'min' => 1, 'max' => 65535]) ?>
                </div>

                <?= $form->field($model, 'dbname')->textInput(['placeholder' => 'database name or SQLite file path']) ?>

                <?= $form->field($model, 'charset')->textInput(['placeholder' => 'utf8mb4']) ?>

            </div>
        </div>
    </div>

</div>

<div class="row">

    <!-- ── Credentials ───────────────────────────────────────── -->
    <div class="col-md-6">
        <div class="card mb-4">
            <div class="card-header">Credentials</div>
            <div class="card-body">

                <?= $form->field($model, 'username')->textInput(['autocomplete' => 'off']) ?>

                <?= $form->field($model, 'password')->passwordInput(['autocomplete' => 'new-password']) ?>

                <?= $form->field($model, 'encryptAtRest')->checkbox()->hint('Password is encrypted before being saved to the params file.') ?>

                <?= $form->field($model, 'persistent')->checkbox()->hint('Keep the PDO connection alive between requests (use with caution).') ?>

            </div>
        </div>
    </div>

    <!-- ── Test panel ─────────────────────────────────────────── -->
    <div class="col-md-6">
        <div class="card mb-4">
            <div class="card-header">Test Connection</div>
            <div class="card-body">
                <p class="text-muted">Save the form first, or use the buttons below to test the current values without saving.</p>

                <button type="button" id="btn-test-conn" class="btn btn-outline-secondary mr-2">
                    Test Connection
                </button>
                <button type="button" id="btn-list-tables" class="btn btn-outline-secondary">
                    List Tables
                </button>

                <div id="datadash-test-result" class="mt-3" style="display:none">
                    <pre id="datadash-test-output" class="bg-light p-2" style="white-space:pre-wrap;max-height:200px;overflow:auto"></pre>
                </div>
            </div>
        </div>
    </div>

</div>

<div class="form-group">
    <?= Html::submitButton($isNew ? 'Add Connection' : 'Save Changes', ['class' => 'btn btn-success']) ?>
    <?= Html::a('Cancel', ['/ngauge-datadash/config/index'], ['class' => 'btn btn-link']) ?>
</div>

<?php ActiveForm::end(); ?>

<script>
(function () {
    // Port auto-fill when driver changes
    var portDefaults = { mysql: 3306, pgsql: 5432, sqlsrv: 1433, sqlite: '' };
    var driverSel    = document.getElementById('datadash-driver');
    var hostFields   = document.getElementById('datadash-host-fields');
    var portField    = document.querySelector('#datadash-config-form [name="ConfigForm[port]"]');

    function applyDriver(driver) {
        var isSqlite = driver === 'sqlite';
        hostFields.style.display = isSqlite ? 'none' : '';
        if (portField && portDefaults[driver] !== undefined) {
            portField.value = portDefaults[driver];
        }
    }

    if (driverSel) {
        applyDriver(driverSel.value);
        driverSel.addEventListener('change', function () { applyDriver(this.value); });
    }

    // AJAX test helpers
    function postForm(url, callback) {
        var form = document.getElementById('datadash-config-form');
        var data = new URLSearchParams(new FormData(form));
        fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
            body: data.toString(),
        })
        .then(function (r) { return r.text(); })
        .then(callback)
        .catch(function (err) { callback('Error: ' + err); });
    }

    function showResult(text) {
        var panel  = document.getElementById('datadash-test-result');
        var output = document.getElementById('datadash-test-output');
        panel.style.display = '';
        output.textContent  = text;
    }

    var btnTest   = document.getElementById('btn-test-conn');
    var btnTables = document.getElementById('btn-list-tables');

    if (btnTest) {
        btnTest.addEventListener('click', function () {
            showResult('Testing…');
            postForm(<?= json_encode($testUrl) ?>, function (resp) {
                try { resp = JSON.stringify(JSON.parse(resp), null, 2); } catch (e) {}
                showResult(resp);
            });
        });
    }

    if (btnTables) {
        btnTables.addEventListener('click', function () {
            showResult('Fetching tables…');
            postForm(<?= json_encode($listTablesUrl) ?>, function (resp) {
                try { resp = JSON.stringify(JSON.parse(resp), null, 2); } catch (e) {}
                showResult(resp);
            });
        });
    }
}());
</script>
