<?php
/**
 * Palletforce – Configuration View
 */

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

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

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

$testUrl = \yii\helpers\Url::to(['/palletforce/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: $('#palletforce-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="palletforce-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="panel panel-default">
        <div class="panel-heading">API Settings</div>
        <div class="panel-body">

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

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

            <?= $form->field($model, 'apiUrl')->textInput([
                'placeholder' => 'https://api.palletforce.com (provided by Palletforce IT)',
            ]) ?>

            <?= $form->field($model, 'accessKey')->passwordInput([
                'placeholder' => 'Unique access key supplied by Palletforce IT',
                'autocomplete' => 'off',
            ]) ?>

            <?= $form->field($model, 'accountNumber')->textInput([
                'placeholder' => 'Customer account number (e.g. HIG021)',
            ]) ?>

            <?= $form->field($model, 'depotCode')->textInput([
                'placeholder' => '000',
                'maxlength'   => 3,
            ])->hint('Your 3-character requesting depot code assigned by Palletforce.') ?>

            <?= $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-default',
                    'type'  => 'button',
                ]) ?>
            </div>

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

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

        </div>
    </div>

    <div class="panel panel-info">
        <div class="panel-heading">Notes</div>
        <div class="panel-body">
            <ul>
                <li>The API Base URL and Access Key are issued by <strong>Palletforce IT</strong> after full testing sign-off. They are not contained in the API documentation.</li>
                <li>Rate limit: <strong>maximum one API call every 30 minutes</strong>. Error code <code>-6</code> indicates the limit has been reached.</li>
                <li>Once a consignment has <code>acceptedStatus: Y</code>, changes must be arranged through the depot via Alliance.</li>
                <li>Labels are returned as Base64-encoded thermal images (8&Prime; × 4&Prime;, landscape).</li>
            </ul>
        </div>
    </div>

</div>
