<?php
/**
 * DX Despatch Manager – Create Consignment View
 */

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

/* @var $this     yii\web\View */
/* @var $model    PortalPeople\dx\models\ConsignmentForm */
/* @var $services array  Service objects from GetServices */

$this->title = 'Create DX Consignment';
$this->params['breadcrumbs'][] = ['label' => 'DX Despatch Manager', 'url' => ['/dx/config']];
$this->params['breadcrumbs'][] = $this->title;

// Build service code dropdown from API response if available
$serviceOptions = [];
if (!empty($services)) {
    foreach ($services as $svc) {
        $code = $svc['serviceCode'] ?? ($svc['code'] ?? '');
        $name = $svc['serviceName'] ?? ($svc['name'] ?? $code);
        if ($code) {
            $serviceOptions[$code] = "{$code} – {$name}";
        }
    }
}
if (empty($serviceOptions)) {
    $serviceOptions = ['NS' => 'NS (enter postcode to populate services)'];
}

// AJAX: reload service codes when postcode changes
$servicesUrl = \yii\helpers\Url::to(['/dx/consignment/services']);
$this->registerJs(<<<JS
    $('#consignmentform-postcode').on('blur', function () {
        var postcode = $(this).val().trim();
        if (!postcode) { return; }
        $.getJSON('{$servicesUrl}', { postcode: postcode }, function (resp) {
            if (!resp.success || !resp.data || !resp.data.length) { return; }
            var sel = $('#consignmentform-servicecode').empty();
            $.each(resp.data, function (i, svc) {
                var code = svc.serviceCode || svc.code || '';
                var name = svc.serviceName || svc.name || code;
                sel.append(new Option(code + ' – ' + name, code));
            });
        });
    });
JS
);
?>

<div class="dx-consignment-create">

    <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; ?>

    <?php $form = ActiveForm::begin(['id' => 'consignment-form']); ?>

    <!-- Delivery / destination address -->
    <div class="card mb-4">
        <div class="card-header">Delivery Address</div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <?= $form->field($model, 'recipient')->textInput(['maxlength' => 30]) ?>
                </div>
                <div class="col-md-6">
                    <?= $form->field($model, 'company')->textInput(['maxlength' => 40]) ?>
                </div>
            </div>
            <?= $form->field($model, 'address1')->textInput(['maxlength' => 50]) ?>
            <?= $form->field($model, 'address2')->textInput(['maxlength' => 50]) ?>
            <?= $form->field($model, 'address3')->textInput(['maxlength' => 50]) ?>
            <div class="row">
                <div class="col-md-4">
                    <?= $form->field($model, 'town')->textInput(['maxlength' => 30]) ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'county')->textInput(['maxlength' => 30])->hint('Required for Ireland (IE) only') ?>
                </div>
                <div class="col-md-2">
                    <?= $form->field($model, 'postcode')->textInput(['maxlength' => 8]) ?>
                </div>
                <div class="col-md-2">
                    <?= $form->field($model, 'countryCode')->textInput(['maxlength' => 2]) ?>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <?= $form->field($model, 'phone')->textInput(['maxlength' => 15]) ?>
                </div>
                <div class="col-md-6">
                    <?= $form->field($model, 'email')->input('email', ['maxlength' => 50]) ?>
                </div>
            </div>
            <?= $form->field($model, 'specialInstructions')->textInput(['maxlength' => 75]) ?>
        </div>
    </div>

    <!-- Consignment details -->
    <div class="card mb-4">
        <div class="card-header">Consignment Details</div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <?= $form->field($model, 'reference')->textInput() ?>
                </div>
                <div class="col-md-6">
                    <?= $form->field($model, 'despatchDate')->input('date') ?>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <?= $form->field($model, 'serviceCode')->dropDownList($serviceOptions)
                        ->hint('Service codes are populated automatically when you enter a postcode above and tab away.') ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'packageTypeCode')->textInput([
                        'maxlength'   => 3,
                        'placeholder' => 'BX',
                    ])->hint('e.g. BX=Box, PLT=Pallet, ENV=Envelope') ?>
                </div>
                <div class="col-md-2">
                    <?= $form->field($model, 'itemQuantity')->textInput(['type' => 'number', 'min' => 1]) ?>
                </div>
                <div class="col-md-2">
                    <?= $form->field($model, 'weight')->textInput(['type' => 'number', 'min' => 0.01, 'step' => '0.01'])->hint('kg per item') ?>
                </div>
            </div>
        </div>
    </div>

    <div class="form-group">
        <?= Html::submitButton('Create Consignment', ['class' => 'btn btn-success']) ?>
        <?= Html::a('Cancel', ['/dx/config'], ['class' => 'btn btn-secondary']) ?>
    </div>

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

</div>
