<?php
/**
 * DataDash — Database Configuration View
 *
 * @var yii\web\View $this
 * @var PortalPeople\datadash\models\ConfigForm $model
 */

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

$this->title = 'DataDash — Database Configuration';
$this->params['breadcrumbs'][] = ['label' => 'Plugins', 'url' => ['#']];
$this->params['breadcrumbs'][] = $this->title;

// Driver → default port map used by JS to auto-fill the port field
$driverPorts = ['mysql' => 3306, 'pgsql' => 5432, 'sqlsrv' => 1433, 'sqlite' => 0];

$this->registerJs(/** @lang JavaScript */ "
(function () {
    'use strict';

    var driverPorts = " . json_encode($driverPorts) . ";

    // Auto-fill port when driver changes
    $('#configform-driver').on('change', function () {
        var port = driverPorts[$(this).val()] || 0;
        if (port > 0) { $('#configform-port').val(port); }
    });

    // Toggle sqlite-specific UI
    function toggleSqliteFields() {
        var isSqlite = $('#configform-driver').val() === 'sqlite';
        $('.datadash-non-sqlite').toggle(!isSqlite);
        $('.datadash-sqlite-only').toggle(isSqlite);
    }
    $('#configform-driver').on('change', toggleSqliteFields);
    toggleSqliteFields();

    // ── Test Connection ──────────────────────────────────────────────────────
    $('#datadash-test-btn').on('click', function () {
        var btn = $(this);
        btn.prop('disabled', true).text('Testing…');
        $('#datadash-test-result').html('');

        $.ajax({
            url: '" . Url::to(['/ngauge-datadash/config/test-connection']) . "',
            type: 'POST',
            data: $('#datadash-config-form').serialize(),
            dataType: 'json',
            success: function (res) {
                var cls = res.success ? 'alert-success' : 'alert-danger';
                var html = '<div class=\"alert ' + cls + ' mb-0\"><strong>' +
                    (res.success ? 'Connected' : 'Failed') + '</strong>: ' +
                    $('<span>').text(res.message).html() + '</div>';

                if (res.success && res.details) {
                    html += '<dl class=\"row mt-2 mb-0 small\">';
                    $.each(res.details, function (k, v) {
                        html += '<dt class=\"col-sm-4\">' + k + '</dt><dd class=\"col-sm-8\"><code>' +
                            $('<span>').text(String(v)).html() + '</code></dd>';
                    });
                    html += '</dl>';
                }
                $('#datadash-test-result').html(html);
            },
            error: function () {
                $('#datadash-test-result').html('<div class=\"alert alert-danger mb-0\">Request failed.</div>');
            },
            complete: function () {
                btn.prop('disabled', false).text('Test Connection');
            }
        });
    });

    // ── List Tables ──────────────────────────────────────────────────────────
    $('#datadash-tables-btn').on('click', function () {
        var btn = $(this);
        btn.prop('disabled', true).text('Loading…');
        $('#datadash-tables-result').html('');

        $.ajax({
            url: '" . Url::to(['/ngauge-datadash/config/list-tables']) . "',
            type: 'POST',
            data: $('#datadash-config-form').serialize(),
            dataType: 'json',
            success: function (res) {
                if (!res.success) {
                    $('#datadash-tables-result').html(
                        '<div class=\"alert alert-danger mb-0\">' + $('<span>').text(res.message).html() + '</div>'
                    );
                    return;
                }

                var tables = res.tables || [];
                if (tables.length === 0) {
                    $('#datadash-tables-result').html('<div class=\"alert alert-info mb-0\">No tables found.</div>');
                    return;
                }

                // Build a responsive table
                var cols = Object.keys(tables[0]);
                var html = '<div class=\"table-responsive\"><table class=\"table table-sm table-striped table-hover mb-0\">';
                html += '<thead class=\"thead-dark\"><tr>';
                cols.forEach(function (c) {
                    html += '<th>' + $('<span>').text(c).html() + '</th>';
                });
                html += '</tr></thead><tbody>';

                tables.forEach(function (row) {
                    html += '<tr>';
                    cols.forEach(function (c) {
                        var val = row[c] !== null && row[c] !== undefined ? String(row[c]) : '—';
                        html += '<td>' + $('<span>').text(val).html() + '</td>';
                    });
                    html += '</tr>';
                });

                html += '</tbody></table></div>';
                html = '<p class=\"text-muted small mb-1\">' + $('<span>').text(res.message).html() + '</p>' + html;
                $('#datadash-tables-result').html(html);
            },
            error: function () {
                $('#datadash-tables-result').html('<div class=\"alert alert-danger mb-0\">Request failed.</div>');
            },
            complete: function () {
                btn.prop('disabled', false).text('List Tables');
            }
        });
    });

}());
");
?>

<div class="datadash-config-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <?php foreach (['success', 'error', 'warning', 'info'] as $type) { ?>
        <?php if (Yii::$app->session->hasFlash($type)) { ?>
            <div class="alert alert-<?= $type === 'error' ? 'danger' : $type ?>">
                <?= Html::encode((string) Yii::$app->session->getFlash($type)) ?>
            </div>
        <?php } ?>
    <?php } ?>

    <div class="row">

        <!-- ── Configuration Form ─────────────────────────────────────────── -->
        <div class="col-md-7">

            <?php $form = ActiveForm::begin([
                'id'                    => 'datadash-config-form',
                'action'                => Url::to(['/ngauge-datadash/config/index']),
                'method'                => 'post',
                'options'               => ['class' => 'form-horizontal'],
                'enableAjaxValidation'  => true,
                'enableClientValidation'=> true,
                'validationUrl'         => Url::to(['/ngauge-datadash/config/validate']),
                'fieldConfig'           => [
                    'template'      => "{label}\n<div class=\"col-sm-8\">{input}\n{hint}\n{error}</div>",
                    'labelOptions'  => ['class' => 'col-sm-4 control-label'],
                ],
            ]); ?>

            <!-- Module enable toggle -->
            <div class="card border-primary mb-3">
                <div class="card-header bg-primary text-white">
                    <h5 class="card-title mb-0">Module Status</h5>
                </div>
                <div class="card-body">
                    <?= $form->field($model, 'enabled')->checkbox() ?>
                </div>
            </div>

            <!-- DSN settings -->
            <div class="card border-info mb-3">
                <div class="card-header bg-info text-white">
                    <h5 class="card-title mb-0">Database DSN</h5>
                </div>
                <div class="card-body">

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

                    <div class="datadash-non-sqlite">
                        <?= $form->field($model, 'host')->textInput(['placeholder' => '127.0.0.1']) ?>

                        <?= $form->field($model, 'port')->input('number', [
                            'min' => 0, 'max' => 65535,
                        ]) ?>
                    </div>

                    <div class="datadash-sqlite-only" style="display:none;">
                        <?= $form->field($model, 'dbname')
                            ->textInput(['placeholder' => '/absolute/path/to/database.sqlite'])
                            ->label('SQLite File Path') ?>
                    </div>

                    <div class="datadash-non-sqlite">
                        <?= $form->field($model, 'dbname')
                            ->textInput(['placeholder' => 'my_database'])
                            ->label('Database Name') ?>

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

                    <div class="datadash-non-sqlite">
                        <?= $form->field($model, 'persistent')->checkbox() ?>
                    </div>

                    <!-- Live DSN preview -->
                    <div class="form-group row">
                        <label class="col-sm-4 control-label text-muted">DSN Preview</label>
                        <div class="col-sm-8">
                            <code id="datadash-dsn-preview" class="small text-muted">
                                <?= Html::encode($model->buildDsn()) ?>
                            </code>
                        </div>
                    </div>

                </div>
            </div>

            <!-- Credentials -->
            <div class="card border-warning mb-3">
                <div class="card-header bg-warning text-dark">
                    <h5 class="card-title mb-0">Credentials</h5>
                </div>
                <div class="card-body">

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

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

                    <?= $form->field($model, 'encryptAtRest')->checkbox()
                        ->hint('When checked the password is encrypted with the backend Security component before being written to params-local.php.') ?>

                </div>
            </div>

            <!-- Actions -->
            <div class="form-group row">
                <div class="col-sm-offset-4 col-sm-8">
                    <?= Html::submitButton('Save Configuration', ['class' => 'btn btn-primary mr-1']) ?>
                    <?= Html::button('Test Connection', [
                        'class' => 'btn btn-info mr-1',
                        'id'    => 'datadash-test-btn',
                        'type'  => 'button',
                    ]) ?>
                    <?= Html::button('List Tables', [
                        'class' => 'btn btn-secondary',
                        'id'    => 'datadash-tables-btn',
                        'type'  => 'button',
                    ]) ?>
                </div>
            </div>

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

        </div><!-- /col-md-7 -->

        <!-- ── Results Panel ──────────────────────────────────────────────── -->
        <div class="col-md-5">

            <div class="card border-secondary mb-3">
                <div class="card-header bg-secondary text-white">
                    <h5 class="card-title mb-0">Connection Test Result</h5>
                </div>
                <div class="card-body" id="datadash-test-result">
                    <p class="text-muted mb-0">Click <strong>Test Connection</strong> to verify your credentials.</p>
                </div>
            </div>

            <div class="card border-secondary">
                <div class="card-header bg-secondary text-white">
                    <h5 class="card-title mb-0">Tables &amp; Sizes</h5>
                </div>
                <div class="card-body" id="datadash-tables-result">
                    <p class="text-muted mb-0">Click <strong>List Tables</strong> to inspect the target database.</p>
                </div>
            </div>

            <!-- DSN config hint -->
            <div class="card border-light mt-3">
                <div class="card-header bg-light">
                    <h6 class="card-title mb-0 text-muted">Bootstrap Info</h6>
                </div>
                <div class="card-body small text-muted">
                    <p>Once saved, the module bootstraps a <code>datadash</code> Yii db component
                    from the stored DSN into every application that loads this module.
                    You can access it via:</p>
                    <pre class="bg-light p-2 rounded"><code>Yii::$app->get('datadash')</code></pre>
                </div>
            </div>

        </div><!-- /col-md-5 -->

    </div><!-- /row -->

</div><!-- /datadash-config-index -->
