<?php
/**
 * UPN Delivery Module – Configuration View
 */

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

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

$this->title = 'UPN (United Pallet Network) Configuration';
$this->params['breadcrumbs'][] = ['label' => 'Integrations', 'url' => ['/']];
$this->params['breadcrumbs'][] = $this->title;

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

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

            <?= $form->field($model, 'apiUrl')->textInput([
                'placeholder' => 'https://services.upn.co.uk:20675/ExternalLinks',
            ])->hint('The UPN External Links SOAP service URL. The WSDL is appended automatically (?wsdl).') ?>

            <?= $form->field($model, 'depot')->textInput([
                'type'        => 'number',
                'min'         => 1,
                'placeholder' => 'Your UPN depot number',
            ])->hint('Integer depot number assigned by UPN. Contact your contracted haulier if unsure.') ?>

            <?= $form->field($model, 'customerId')->textInput([
                'type'        => 'number',
                'min'         => 0,
                'placeholder' => 'e.g. 10016',
            ])->hint('The depot\'s unique ID for your customer account. Leave 0 if unknown.') ?>

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

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

            <div class="row">
                <div class="col-md-6">
                    <?= $form->field($model, 'fuelSurcharge')->textInput([
                        'type' => 'number',
                        'min' => 0,
                        'max' => 1,
                        'step' => '0.0001',
                        'placeholder' => '0.1000',
                    ])->hint('Decimal rate, e.g. 0.1000 for 10%.') ?>
                </div>
                <div class="col-md-6">
                    <?= $form->field($model, 'discount')->textInput([
                        'type' => 'number',
                        'min' => 0,
                        'max' => 1,
                        'step' => '0.0001',
                        'placeholder' => '0.0500',
                    ])->hint('Decimal rate, e.g. 0.0500 for 5%.') ?>
                </div>
            </div>

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

            <?= $form->field($model, 'debug')->checkbox()->hint('Logs all SOAP 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 UPN API uses <strong>SOAP</strong>. Credentials (depot, username, password) are passed with each call — there is no session token to manage.</li>
                <li>The <strong>Depot Number</strong> and <strong>Customer ID</strong> are provided by your contracted UPN haulier or by emailing <a href="mailto:it@u-p-n.co.uk">it@u-p-n.co.uk</a>.</li>
                <li>PDF pallet labels are returned as <strong>Base64-encoded</strong> strings. Decode and stream as <code>application/pdf</code> to print.</li>
                <li>Tracking data is <strong>incremental</strong> — the <code>GetPODAndTrackingByDepot_V2</code> function returns only data logged since it was last called.</li>
                <li>Consignments can only be deleted (<code>DeleteImportedCon</code>) before they are <strong>processed by UPN</strong>.</li>
                <li>For questions, contact your contracted haulier or email <a href="mailto:it@u-p-n.co.uk">it@u-p-n.co.uk</a>.</li>
            </ul>
        </div>
    </div>

</div>
