<?php

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

/**
 * @var yii\web\View $this
 * @var PortalPeople\shippingcosts\models\ConfigForm $model
 */

$this->title = 'Shipping Costs Configuration';
$this->params['breadcrumbs'][] = $this->title;

$statusUrl = Url::to(['config/status']);

$js = <<<'JS'
(function () {
    function escapeHtml(text) {
        return $('<div>').text(text == null ? '' : text).html();
    }

    function rowTemplate(item) {
        var type = item.type || 'text';
        var options = ['text', 'number', 'boolean', 'select'];
        var typeOptions = options.map(function (option) {
            var selected = option === type ? ' selected' : '';
            return '<option value="' + option + '"' + selected + '>' + option + '</option>';
        }).join('');

        var requiredChecked = item.required ? ' checked' : '';
        var enabledChecked = item.enabled !== false ? ' checked' : '';

        return '<tr>' +
            '<td><input class="form-control parameter-key" value="' + escapeHtml(item.key || '') + '" placeholder="key"></td>' +
            '<td><input class="form-control parameter-label" value="' + escapeHtml(item.label || '') + '" placeholder="label"></td>' +
            '<td><select class="form-control parameter-type">' + typeOptions + '</select></td>' +
            '<td><input class="form-control parameter-default" value="' + escapeHtml(item.default || '') + '" placeholder="default"></td>' +
            '<td><input class="form-control parameter-options" value="' + escapeHtml(item.options || '') + '" placeholder="opt1,opt2"></td>' +
            '<td class="text-center"><input type="checkbox" class="parameter-required"' + requiredChecked + '></td>' +
            '<td class="text-center"><input type="checkbox" class="parameter-enabled"' + enabledChecked + '></td>' +
            '<td class="text-center"><button type="button" class="btn btn-sm btn-outline-danger remove-parameter">Remove</button></td>' +
            '</tr>';
    }

    function collectRows() {
        var rows = [];

        $('#parameters-table tbody tr').each(function () {
            var key = $(this).find('.parameter-key').val();
            if (!key || !key.trim()) {
                return;
            }

            rows.push({
                key: key.trim(),
                label: ($(this).find('.parameter-label').val() || '').trim(),
                type: $(this).find('.parameter-type').val() || 'text',
                default: ($(this).find('.parameter-default').val() || '').trim(),
                options: ($(this).find('.parameter-options').val() || '').trim(),
                required: $(this).find('.parameter-required').is(':checked'),
                enabled: $(this).find('.parameter-enabled').is(':checked')
            });
        });

        $('#configform-parametersjson').val(JSON.stringify(rows));
    }

    function renderStatus() {
        $.ajax({
            url: '__STATUS_URL__',
            type: 'GET',
            dataType: 'json',
            success: function (response) {
                if (!response.success) {
                    $('#status-info').html('<div class="text-danger">' + escapeHtml(response.message || 'Unable to load status') + '</div>');
                    return;
                }

                var html = '';
                html += '<strong>Configured:</strong> ' + (response.configured ? 'Yes' : 'No') + '<br>';
                html += '<strong>Enabled:</strong> ' + (response.enabled ? 'Yes' : 'No') + '<br>';
                html += '<strong>Parameter Controls:</strong> ' + escapeHtml(String(response.parameterCount || 0)) + '<br>';
                html += '<strong>Max Shipping Cost:</strong> ' + escapeHtml(String(response.maxShippingCost || 0));

                $('#status-info').html(html);
            },
            error: function () {
                $('#status-info').html('<div class="text-danger">Unable to load status</div>');
            }
        });
    }

    $('#add-parameter').on('click', function () {
        $('#parameters-table tbody').append(rowTemplate({
            key: '',
            label: '',
            type: 'text',
            default: '',
            options: '',
            required: false,
            enabled: true
        }));
    });

    $('#parameters-table').on('click', '.remove-parameter', function () {
        $(this).closest('tr').remove();
    });

    $('#config-form').on('submit', function () {
        collectRows();
    });

    renderStatus();
    setInterval(renderStatus, 30000);
})();
JS;

$this->registerJs(str_replace('__STATUS_URL__', $statusUrl, $js));
?>

<div class="shippingcosts-config-index">
    <div class="row">
        <div class="col-md-9">
            <?php $form = ActiveForm::begin([
                'id' => 'config-form',
                'action' => Url::to(['config/index']),
                'method' => 'post',
                'enableAjaxValidation' => true,
                'validationUrl' => Url::to(['config/validate']),
            ]); ?>

            <div class="card border-info mb-3">
                <div class="card-header bg-info text-white">Core Settings</div>
                <div class="card-body">
                    <?= $form->field($model, 'enabled')->checkbox() ?>
                    <?= $form->field($model, 'maxShippingCost')->input('number', ['step' => '0.01', 'min' => 0]) ?>
                    <?= $form->field($model, 'defaultHaulierId')->input('number', ['min' => 0]) ?>
                    <?= $form->field($model, 'debug')->checkbox() ?>
                </div>
            </div>

            <div class="card border-warning mb-3">
                <div class="card-header bg-warning text-dark d-flex justify-content-between align-items-center">
                    <span>Parameter Controls</span>
                    <button type="button" class="btn btn-sm btn-dark" id="add-parameter">Add Control</button>
                </div>
                <div class="card-body">
                    <p class="text-muted mb-3">Define editable parameters used by shipping configuration and runtime rules.</p>

                    <div class="table-responsive">
                        <table class="table table-bordered" id="parameters-table">
                            <thead>
                            <tr>
                                <th>Key</th>
                                <th>Label</th>
                                <th>Type</th>
                                <th>Default</th>
                                <th>Options</th>
                                <th class="text-center">Required</th>
                                <th class="text-center">Enabled</th>
                                <th></th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($model->getParameterRows() as $row): ?>
                                <tr>
                                    <td><input class="form-control parameter-key" value="<?= Html::encode($row['key']) ?>" placeholder="key"></td>
                                    <td><input class="form-control parameter-label" value="<?= Html::encode($row['label']) ?>" placeholder="label"></td>
                                    <td>
                                        <select class="form-control parameter-type">
                                            <?php foreach (['text', 'number', 'boolean', 'select'] as $type): ?>
                                                <option value="<?= Html::encode($type) ?>" <?= $row['type'] === $type ? 'selected' : '' ?>>
                                                    <?= Html::encode($type) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input class="form-control parameter-default" value="<?= Html::encode($row['default']) ?>" placeholder="default"></td>
                                    <td><input class="form-control parameter-options" value="<?= Html::encode($row['options']) ?>" placeholder="opt1,opt2"></td>
                                    <td class="text-center"><input type="checkbox" class="parameter-required" <?= $row['required'] ? 'checked' : '' ?>></td>
                                    <td class="text-center"><input type="checkbox" class="parameter-enabled" <?= $row['enabled'] ? 'checked' : '' ?>></td>
                                    <td class="text-center"><button type="button" class="btn btn-sm btn-outline-danger remove-parameter">Remove</button></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <?= $form->field($model, 'parametersJson')->hiddenInput()->label(false) ?>
                </div>
            </div>

            <div class="form-group">
                <?= Html::submitButton('Save Configuration', ['class' => 'btn btn-primary']) ?>
            </div>

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

            <?php if (Yii::$app->session->hasFlash('success')): ?>
                <div class="alert alert-success"><?= Html::encode(Yii::$app->session->getFlash('success')) ?></div>
            <?php endif; ?>
            <?php if (Yii::$app->session->hasFlash('error')): ?>
                <div class="alert alert-danger"><?= Html::encode(Yii::$app->session->getFlash('error')) ?></div>
            <?php endif; ?>
        </div>

        <div class="col-md-3">
            <div class="card border-success mb-3">
                <div class="card-header bg-success text-white">Module Status</div>
                <div class="card-body" id="status-info">
                    Loading status...
                </div>
            </div>

            <div class="card">
                <div class="card-header">Notes</div>
                <div class="card-body">
                    <ul class="small mb-0">
                        <li>Use parameter keys that are stable and machine-friendly.</li>
                        <li>For select types, provide comma-separated options.</li>
                        <li>Disabled controls stay in config but should be ignored by UI/runtime.</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
