<?php

declare(strict_types=1);

/**
 * @var yii\web\View $this
 * @var \PortalPeople\datadash\models\ConfigForm $model
 * @var string[] $tables
 * @var string|null $tablesError
 */

use yii\helpers\Html;
use yii\helpers\Url;

$this->title = 'Generate Models — ' . $model->name;

$doGenerateUrl = Url::to(['/ngauge-datadash/config/do-generate']);
?>

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

    <div class="d-flex align-items-center justify-content-between mb-3">
        <h1 class="mb-0"><?= Html::encode($this->title) ?></h1>
        <?= Html::a('&larr; Back to Connections', ['/ngauge-datadash/config/index'], ['class' => 'btn btn-outline-secondary']) ?>
    </div>

    <?php foreach (['success', 'error', 'warning', 'info'] as $type) { ?>
        <?php if (Yii::$app->session->hasFlash($type)) { ?>
            <div class="alert alert-<?= $type === 'error' ? 'danger' : $type ?> alert-dismissible">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <pre class="mb-0" style="white-space:pre-wrap"><?= Html::encode((string) Yii::$app->session->getFlash($type)) ?></pre>
            </div>
        <?php } ?>
    <?php } ?>

    <!-- Connection info -->
    <div class="card mb-4">
        <div class="card-header">Connection Details</div>
        <div class="card-body">
            <dl class="row mb-0">
                <dt class="col-sm-3">Name</dt>
                <dd class="col-sm-9"><code><?= Html::encode($model->name) ?></code></dd>
                <dt class="col-sm-3">Label</dt>
                <dd class="col-sm-9"><?= Html::encode($model->label ?: '—') ?></dd>
                <dt class="col-sm-3">Driver</dt>
                <dd class="col-sm-9"><?= Html::encode($model->driver) ?></dd>
                <dt class="col-sm-3">Host</dt>
                <dd class="col-sm-9"><?= Html::encode($model->host) ?></dd>
                <dt class="col-sm-3">Database</dt>
                <dd class="col-sm-9"><?= Html::encode($model->dbname) ?></dd>
            </dl>
        </div>
    </div>

    <?php if ($tablesError !== null) { ?>
        <div class="alert alert-danger">
            <strong>Could not retrieve table list:</strong><br>
            <?= Html::encode($tablesError) ?>
        </div>
    <?php } elseif (empty($tables)) { ?>
        <div class="alert alert-warning">No tables found in this database.</div>
    <?php } else { ?>

        <?= Html::beginForm($doGenerateUrl, 'post', ['id' => 'datadash-generate-form']) ?>
            <?= Html::hiddenInput('name', $model->name) ?>

            <div class="card mb-4">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <span>Select Tables</span>
                    <span>
                        <a href="#" id="btn-select-all" class="mr-2">Select all</a>
                        <a href="#" id="btn-select-none">Clear</a>
                    </span>
                </div>
                <div class="card-body">
                    <div class="row">
                        <?php foreach ($tables as $row) { ?>
                            <?php $tableName = (string) ($row['table'] ?? $row['TABLE_NAME'] ?? $row[0] ?? ''); ?>
                            <?php if ($tableName === '') { continue; } ?>
                            <?php $safeId = preg_replace('/[^a-z0-9]/i', '_', $tableName); ?>
                            <div class="col-md-4 col-sm-6">
                                <div class="form-check">
                                    <?= Html::checkbox('tables[]', false, [
                                        'value' => $tableName,
                                        'id'    => 'tbl-' . $safeId,
                                        'class' => 'form-check-input datadash-table-cb',
                                    ]) ?>
                                    <label class="form-check-label" for="tbl-<?= Html::encode($safeId) ?>">
                                        <?= Html::encode($tableName) ?>
                                        <?php if (!empty($row['rows'])) { ?>
                                            <small class="text-muted">(<?= number_format((int) $row['rows']) ?> rows)</small>
                                        <?php } ?>
                                    </label>
                                </div>
                            </div>
                        <?php } ?>
                    </div>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-header">Model Namespace</div>
                <div class="card-body">
                    <div class="form-group mb-0">
                        <label for="datadash-namespace">Target namespace</label>
                        <input type="text"
                               id="datadash-namespace"
                               name="namespace"
                               class="form-control"
                               value="common\models\remote\<?= Html::encode(str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $model->name)))) ?>"
                               required>
                        <small class="form-text text-muted">
                            Models are saved relative to the namespace path under <code>@common/models/remote/</code>.
                        </small>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <?= Html::submitButton('Generate Models', ['class' => 'btn btn-success', 'id' => 'btn-generate']) ?>
                <?= Html::a('Cancel', ['/ngauge-datadash/config/index'], ['class' => 'btn btn-link']) ?>
            </div>

        <?= Html::endForm() ?>

    <?php } ?>

</div>

<script>
(function () {
    var selectAll  = document.getElementById('btn-select-all');
    var selectNone = document.getElementById('btn-select-none');
    var checkboxes = document.querySelectorAll('.datadash-table-cb');

    if (selectAll) {
        selectAll.addEventListener('click', function (e) {
            e.preventDefault();
            checkboxes.forEach(function (cb) { cb.checked = true; });
        });
    }
    if (selectNone) {
        selectNone.addEventListener('click', function (e) {
            e.preventDefault();
            checkboxes.forEach(function (cb) { cb.checked = false; });
        });
    }
}());
</script>
