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

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

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

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

$testUrl = \yii\helpers\Url::to(['/gforce/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: $('#gforce-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="gforce-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'     => 'gforce-config-form',
                'action' => ['/gforce/config/index'],
            ]); ?>

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

            <?= $form->field($model, 'apiUrl')->textInput([
                'placeholder' => 'https://api-uat.vigocloud.com/api/v1',
            ])->hint('Vigo REST API endpoint. Use UAT URL for testing, then switch to your live URL.') ?>

            <?= $form->field($model, 'apiKey')->passwordInput([
                'placeholder' => 'Encrypted customer API key issued by GForce IT',
                'autocomplete' => 'off',
            ])->hint('API key supplied by GForce IT (itintegration@gforce.com / 01543 440206).') ?>

            <?= $form->field($model, 'autoConfirm')->checkbox()->hint(
                'When enabled, consignments are confirmed directly into the depot system (Confirm=yes). '
                . 'Once confirmed, consignments cannot be modified via the API – contact the depot for changes.'
            ) ?>

            <div class="row">
                <div class="col-md-6">
                    <?= $form->field($model, 'defaultCollectionCountry')->textInput([
                        'maxlength' => 2,
                        'placeholder' => 'GB',
                    ])->hint('Collection country used when checking available services from this account/depot.') ?>
                </div>
                <div class="col-md-6">
                    <?= $form->field($model, 'defaultCollectionPostcode')->textInput([
                        'maxlength' => 10,
                        'placeholder' => 'e.g. WS13 8NE',
                    ])->hint('Collection postcode used for route/service availability lookups.') ?>
                </div>
            </div>

            <?= $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>The API Key is issued by <strong>GForce IT</strong>. Contact <a href="mailto:itintegration@gforce.com">itintegration@gforce.com</a> or call <strong>01543 440206</strong>.</li>
                <li><strong>Auto-Confirm disabled</strong> (recommended initially): consignments are posted to the customer account for manual review at <a href="https://portal.gforce.com" target="_blank" rel="noopener">portal.gforce.com</a>.</li>
                <li><strong>Auto-Confirm enabled</strong>: consignments are sent directly to the depot system. They <strong>cannot</strong> be modified or deleted via the API once confirmed.</li>
                <li>Labels are thermal 10.5 × 25cm PDF format. Thermal label printing must be enabled on your GForce account.</li>
                <li>Maximum weight by pallet type: FP=1200kg, LP=750kg, HP=500kg, QP=250kg, MQP=150kg, EPL=500kg, XLP=1200kg.</li>
                <li>Maximum tail lift consignment weight: <strong>750kg</strong>.</li>
            </ul>
        </div>
    </div>

</div>
