<?php
/**
 * DX Despatch Manager – Configuration View
 */

use yii\helpers\Html;
use yii\bootstrap4\ActiveForm;

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

$this->title = 'DX Despatch Manager Configuration';
$this->params['breadcrumbs'][] = ['label' => 'Integrations', 'url' => ['/']];
$this->params['breadcrumbs'][] = $this->title;

$testUrl = \yii\helpers\Url::to(['/dx/config/test-connection']);

$this->registerJs(<<<JS
    $('#test-connection-btn').on('click', function () {
        var btn = $(this);
        btn.prop('disabled', true).text('Testing...');

        $.ajax({
            url: '{$testUrl}',
            type: 'POST',
            data: $('#dx-config-form').serialize(),
            dataType: 'json',
            success: function (resp) {
                var cls  = resp.success ? 'alert-success' : 'alert-danger';
                var icon = resp.success ? '✔' : '✖';
                $('#connection-result').html('<div class="alert ' + cls + '">' + icon + ' ' + resp.message + '</div>');
            },
            error: function () {
                $('#connection-result').html('<div class="alert alert-danger">✖ Request failed. Check browser console.</div>');
            },
            complete: function () {
                btn.prop('disabled', false).text('Test Connection');
            }
        });
    });
JS
);
?>

<div class="dx-config">

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

    <?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 class="card mb-4">
        <div class="card-header">API Settings</div>
        <div class="card-body">

            <?php $form = ActiveForm::begin([
                'id'     => 'dx-config-form',
                'action' => ['/dx/config/index'],
            ]); ?>

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

            <?= $form->field($model, 'apiUrl')->textInput([
                'placeholder' => 'https://despatch-api.dxdelivery.com',
            ])->hint('Use the test environment URL during development. The production URL requires IP whitelisting.') ?>

            <?= $form->field($model, 'accountCode')->textInput([
                'placeholder' => 'Your DX account code',
            ]) ?>

            <?= $form->field($model, 'username')->textInput([
                'placeholder' => 'API username',
                'type'        => 'text',
            ]) ?>

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

            <?= $form->field($model, 'timeout')->textInput(['type' => 'number', 'min' => 5, 'max' => 120]) ?>

            <?= $form->field($model, 'debug')->checkbox()->hint('Logs all API requests/responses to the application log.') ?>

            <div class="form-group">
                <?= Html::submitButton('Save Configuration', ['class' => 'btn btn-primary']) ?>
                <?= Html::button('Test Connection', [
                    'id'    => 'test-connection-btn',
                    'class' => 'btn btn-secondary',
                    'type'  => 'button',
                ]) ?>
            </div>

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

            <div id="connection-result" class="mt-3"></div>

        </div>
    </div>

    <div class="card border-info">
        <div class="card-header bg-info text-white">Notes</div>
        <div class="card-body">
            <ul>
                <li>DX provides separate <strong>test</strong> and <strong>production</strong> API URLs. The production environment requires <strong>IP whitelisting</strong> — contact DX to register your server IP.</li>
                <li>Authentication tokens are cached automatically and reused until expiry. You do not need to manage token refresh manually.</li>
                <li>Each item in a consignment must be cancelled <strong>individually</strong> before the despatch date.</li>
                <li>PDF labels are returned as Base64-encoded data. ZPL labels are returned as raw ZPL text.</li>
            </ul>
        </div>
    </div>

</div>

