<?php
/**
 * GForce – Create Consignment View
 */

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

/**
 * @var yii\web\View $this
 * @var PortalPeople\gforce\models\ConsignmentForm $model
 * @var bool $queueAvailable
 */

$this->title = 'Create GForce Consignment';
$this->params['breadcrumbs'][] = ['label' => 'GForce', 'url' => ['/gforce/config']];
$this->params['breadcrumbs'][] = $this->title;

$consignmentTypeOptions = [
    'D' => 'D – Delivery (collected from your site, delivered to address)',
    'C' => 'C – Collection (collected from address, returned to your site)',
    '3' => '3 – Third Party (remote collection and delivery)',
];

$billUnitOptions = [
    'FP'  => 'FP – Full Pallet (1.2×1.2×2.2m, max 1200kg)',
    'LP'  => 'LP – Light Pallet (1.2×1.2×2.2m, max 750kg)',
    'HP'  => 'HP – Half Pallet (1.2×1.2×1.1m, max 500kg)',
    'QP'  => 'QP – Quarter Pallet (1.2×1.2×0.8m, max 250kg)',
    'MQP' => 'MQP – Mini Quarter Pallet (1.2×1.2×0.6m, max 150kg)',
    'EPL' => 'EPL – Euro Pallet (0.8×1.2×2.2m, max 500kg)',
    'XLP' => 'XLP – XL Pallet (1.6×1.2×2.2m, max 1200kg)',
];

$notificationOptions = [
    '1' => '1 – Scanned out of sortation facility (departed processing hub)',
    '2' => '2 – Scanned in to sortation facility (arrived at processing hub)',
    '3' => '3 – Consignment out for delivery (loaded onto delivery vehicle)',
    '4' => '4 – Delivery completed (POD available)',
    '5' => '5 – ETA details (estimated time of arrival)',
    '6' => '6 – Image available (POD image with signature)',
    '7' => '7 – Scheduled AM delivery',
    '8' => '8 – Scheduled PM delivery',
];

$servicesUrl = Url::to(['/gforce/consignment/services']);
$defaultServiceOptions = [
    'B' => 'B - Economy',
    'A' => 'A - Premium Next Day',
];

// Toggle book-in fields based on checkbox
$this->registerJs(<<<JS
    var serviceLookupUrl = '{$servicesUrl}';

    function toggleBookIn() {
        var checked = $('#consignmentform-bookinrequest').is(':checked');
        $('#bookin-fields').toggle(checked);
    }
    $('#consignmentform-bookinrequest').on('change', toggleBookIn);
    toggleBookIn();

    // Dynamic product rows
    var productCount = parseInt($('#product-rows').attr('data-count') || 1);
    $('#add-product-btn').on('click', function () {
        productCount++;
        var html = '<div class="row product-row" id="product-row-' + productCount + '">'
            + '<div class="col-md-5">'
            + '<input type="text" class="form-control mb-2" name="ConsignmentForm[products][' + productCount + '][description]" placeholder="Description">'
            + '</div>'
            + '<div class="col-md-2">'
            + '<input type="number" class="form-control mb-2" name="ConsignmentForm[products][' + productCount + '][quantity]" placeholder="Qty" min="1" value="1">'
            + '</div>'
            + '<div class="col-md-3">'
            + '<input type="text" class="form-control mb-2" name="ConsignmentForm[products][' + productCount + '][code]" placeholder="Product Code">'
            + '</div>'
            + '<div class="col-md-2">'
            + '<button type="button" class="btn btn-sm btn-danger remove-product mb-2" data-row="' + productCount + '">Remove</button>'
            + '</div>'
            + '</div>';
        $('#product-rows').append(html);
        $('#product-rows').attr('data-count', productCount);
    });
    $(document).on('click', '.remove-product', function () {
        var row = $(this).data('row');
        $('#product-row-' + row).remove();
    });

    function normalizeServices(payload) {
        if (!payload) {
            return [];
        }

        if (Array.isArray(payload)) {
            return payload;
        }

        if (Array.isArray(payload.data)) {
            return payload.data;
        }

        if (typeof payload.data === 'string') {
            try {
                var parsed = JSON.parse(payload.data);
                if (Array.isArray(parsed)) {
                    return parsed;
                }
            } catch (e) {
                // Ignore parse errors and continue fallback checks.
            }
        }

        if (Array.isArray(payload.data)) {
            return payload.data;
        }

        if (typeof payload.data === 'string') {
            try {
                var parsedCamel = JSON.parse(payload.data);
                if (Array.isArray(parsedCamel)) {
                    return parsedCamel;
                }
            } catch (e) {
                // Ignore parse errors and continue fallback checks.
            }
        }

        if (Array.isArray(payload.data)) {
            return payload.data;
        }

        if (Array.isArray(payload.Service)) {
            return payload.Service;
        }

        if (payload.Services && Array.isArray(payload.Services.Service)) {
            return payload.Services.Service;
        }

        if (payload.AvailableServices && Array.isArray(payload.AvailableServices.Service)) {
            return payload.AvailableServices.Service;
        }

        return [];
    }

    function setServiceMessage(message, ok) {
        var el = $('#gforce-services-hint');
        if (!message) {
            el.hide().removeClass('text-success text-danger text-muted').text('');
            return;
        }

        el.show().removeClass('text-success text-danger text-muted');
        if (ok === true) {
            el.addClass('text-success');
        } else if (ok === false) {
            el.addClass('text-danger');
        } else {
            el.addClass('text-muted');
        }
        el.text(message);
    }

    function populateServiceOptions(services) {
        var codeSelect = $('#consignmentform-servicecode');
        var surchargeSelect = $('#consignmentform-servicesurcharge');
        var currentCode = codeSelect.val();
        var currentSurcharge = surchargeSelect.val();

        codeSelect.empty();
        surchargeSelect.empty();

        if (!services.length) {
            codeSelect.append(new Option('No route services available', ''));
            surchargeSelect.append(new Option('No surcharge options available', ''));
            return;
        }

        codeSelect.append(new Option('Select service', ''));
        surchargeSelect.append(new Option('Select surcharge', ''));

        var seenCodes = {};
        var seenSurcharges = {};

        $.each(services, function (_, svc) {
            var code = (svc.ServiceCode || svc.Code || svc.code || '').toString().trim();
            var surcharge = (svc.ServiceGroupCode || svc.Surcharge || svc.surcharge || code).toString().trim();
            var name = (svc.ServiceName || svc.Name || svc.Description || svc.description || code).toString().trim();
            var daysMin = (svc.ServiceDaysMin || svc.daysMin || '').toString().trim();
            var daysMax = (svc.ServiceDaysMax || svc.daysMax || '').toString().trim();
            var etaText = '';

            if (daysMin && daysMax) {
                etaText = daysMin === daysMax ? ' (' + daysMin + ' day)' : ' (' + daysMin + '-' + daysMax + ' days)';
            }

            if (code && !seenCodes[code]) {
                seenCodes[code] = true;
                codeSelect.append(new Option(code + ' - ' + name + etaText, code));
            }

            if (surcharge && !seenSurcharges[surcharge]) {
                seenSurcharges[surcharge] = true;
                surchargeSelect.append(new Option(surcharge, surcharge));
            }
        });

        if (currentCode && seenCodes[currentCode]) {
            codeSelect.val(currentCode);
        } else if (!codeSelect.val()) {
            codeSelect.prop('selectedIndex', 1);
        }

        if (currentSurcharge && seenSurcharges[currentSurcharge]) {
            surchargeSelect.val(currentSurcharge);
        } else {
            var selectedCode = codeSelect.val();
            if (selectedCode && seenSurcharges[selectedCode]) {
                surchargeSelect.val(selectedCode);
            } else if (!surchargeSelect.val()) {
                surchargeSelect.prop('selectedIndex', 1);
            }
        }
    }

    function fetchAvailableServices() {
        var type = ($('#consignmentform-consignmenttype').val() || 'D').trim();
        var delCountry = ($('#consignmentform-deliverycountry').val() || 'GB').trim();
        var delPost = ($('#consignmentform-deliverypostcode').val() || '').trim();

        if (!delPost) {
            setServiceMessage('Enter delivery postcode to load route services.', null);
            return;
        }

        setServiceMessage('Checking available services for this route...', null);

        $.getJSON(serviceLookupUrl, {
            type: type,
            delCountry: delCountry,
            delPostcode: delPost
        }).done(function (resp) {
            if (!resp || !resp.success) {
                populateServiceOptions([]);
                setServiceMessage((resp && resp.message) ? resp.message : 'No services returned for this route.', false);
                return;
            }

            var services = normalizeServices(resp.data);
            populateServiceOptions(services);
            setServiceMessage('Loaded ' + services.length + ' service option(s) for ' + (resp.route ? resp.route.colPost + ' -> ' + resp.route.delPost : 'route') + '.', true);
        }).fail(function () {
            populateServiceOptions([]);
            setServiceMessage('Service lookup request failed.', false);
        });
    }

    $('#consignmentform-deliverypostcode, #consignmentform-deliverycountry, #consignmentform-consignmenttype').on('change blur', fetchAvailableServices);
    $('#consignmentform-servicecode').on('change', function () {
        var selectedCode = $(this).val();
        var surcharge = $('#consignmentform-servicesurcharge');
        if (selectedCode && surcharge.find('option[value="' + selectedCode + '"]').length) {
            surcharge.val(selectedCode);
        }
    });

    fetchAvailableServices();
JS
);
?>

<div class="gforce-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']); ?>

    <!-- Collection Address -->
    <div class="card mb-4">
        <div class="card-header">Collection Address</div>
        <div class="card-body">
            <p class="text-muted mb-3">
                Optional for <strong>D</strong> (Delivery) jobs. Required for <strong>C</strong> and <strong>3</strong> job types.
            </p>
            <div class="row">
                <div class="col-md-6">
                    <?= $form->field($model, 'collectionContactName')->textInput(['maxlength' => 50]) ?>
                    <?= $form->field($model, 'collectionTelephone')->textInput(['maxlength' => 20]) ?>
                    <?= $form->field($model, 'collectionCompanyName')->textInput(['maxlength' => 50]) ?>
                </div>
                <div class="col-md-6">
                    <?= $form->field($model, 'collectionLine')->textInput(['maxlength' => 35]) ?>
                    <?= $form->field($model, 'collectionLine2')->textInput(['maxlength' => 35]) ?>
                    <?= $form->field($model, 'collectionTown')->textInput(['maxlength' => 35]) ?>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <?= $form->field($model, 'collectionCounty')->textInput(['maxlength' => 35]) ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'collectionPostCode')->textInput(['maxlength' => 10]) ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'collectionCountry')->textInput(['maxlength' => 2])->hint('ISO 2-letter code, e.g. GB') ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Delivery 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, 'deliveryContactName')->textInput(['maxlength' => 50]) ?>
                    <?= $form->field($model, 'deliveryTelephone')->textInput(['maxlength' => 20]) ?>
                    <?= $form->field($model, 'deliveryCompanyName')->textInput(['maxlength' => 50]) ?>
                </div>
                <div class="col-md-6">
                    <?= $form->field($model, 'deliveryLine')->textInput(['maxlength' => 35]) ?>
                    <?= $form->field($model, 'deliveryLine2')->textInput(['maxlength' => 35]) ?>
                    <?= $form->field($model, 'deliveryTown')->textInput(['maxlength' => 35]) ?>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <?= $form->field($model, 'deliveryCounty')->textInput(['maxlength' => 35]) ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'deliveryPostCode')->textInput(['maxlength' => 10]) ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'deliveryCountry')->textInput(['maxlength' => 2])->hint('ISO 2-letter code, e.g. GB') ?>
                </div>
            </div>
        </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-4">
                    <?= $form->field($model, 'consignmentType')->dropDownList($consignmentTypeOptions) ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'consignmentNumber')->textInput([
                        'placeholder' => 'e.g. MYREF-001',
                    ])->hint('Unique identifier for this consignment.') ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'reference')->textInput(['placeholder' => 'Optional secondary reference']) ?>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3">
                    <?= $form->field($model, 'lifts')->textInput(['type' => 'number', 'min' => 1])->hint('Total number of pallet lifts.') ?>
                </div>
                <div class="col-md-3">
                    <?= $form->field($model, 'weight')->textInput(['type' => 'number', 'min' => 1])->hint('Total weight in kg (integer).') ?>
                </div>
                <div class="col-md-3">
                    <?= $form->field($model, 'billUnitType')->dropDownList($billUnitOptions) ?>
                </div>
                <div class="col-md-3">
                    <?= $form->field($model, 'billUnitAmount')->textInput(['type' => 'number', 'min' => 1])->hint('Number of billing units / pallets.') ?>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3">
                    <?= $form->field($model, 'serviceCode')->dropDownList($defaultServiceOptions, [
                        'prompt' => 'Select service',
                    ])->hint('Service list auto-updates from AvailableServices using the entered route.') ?>
                </div>
                <div class="col-md-3">
                    <?= $form->field($model, 'serviceSurcharge')->dropDownList($defaultServiceOptions, [
                        'prompt' => 'Select surcharge',
                    ]) ?>
                </div>
                <div class="col-md-3">
                    <?= $form->field($model, 'importId')->textInput(['placeholder' => 'Optional batch ID']) ?>
                </div>
                <div class="col-md-3">
                    <?= $form->field($model, 'insurance')->textInput([
                        'type'        => 'number',
                        'min'         => 0,
                        'placeholder' => 'Leave blank for account default',
                    ])->hint('RSA insurance (£ per 1000kg). Leave blank to use account defaults.') ?>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <?= $form->field($model, 'collectionDate')->textInput([
                        'placeholder' => 'YYYY-MM-DD',
                        'type'        => 'date',
                    ])->hint('Only required for collection services.') ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'deliveryDate')->textInput([
                        'placeholder' => 'YYYY-MM-DD',
                        'type'        => 'date',
                    ])->hint('Optional. Available on economy service for day selection.') ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'deliveryTime')->textInput([
                        'placeholder' => 'HH:MM:SS',
                    ])->hint('Only required for timed delivery service.') ?>
                </div>
            </div>
            <small id="gforce-services-hint" class="form-text text-muted" style="display:none;"></small>
            <?= $form->field($model, 'manifestNote')->textarea(['rows' => 2, 'maxlength' => 255])->hint('Special delivery instructions (max 255 chars).') ?>
        </div>
    </div>

    <!-- Options -->
    <div class="card mb-4">
        <div class="card-header">Options</div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-4">
                    <?= $form->field($model, 'handball')->checkbox()->hint('Contents handed to customer item-by-item (e.g. high street shops).') ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'tailLift')->checkbox()->hint('Tail lift required (no forklift at delivery point). Max 750kg.') ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'bookInRequest')->checkbox()->hint('Depot contacts consignee to arrange delivery time.') ?>
                </div>
            </div>

            <div id="bookin-fields" style="display: none;">
                <hr>
                <h5>Book-In Details <small class="text-muted">(required when Book-In is selected)</small></h5>
                <div class="row">
                    <div class="col-md-6">
                        <?= $form->field($model, 'bookInInstructions')->textInput(['placeholder' => 'Booking-in instructions']) ?>
                    </div>
                    <div class="col-md-6">
                        <?= $form->field($model, 'bookInReference')->textInput(['placeholder' => 'Booking-in reference']) ?>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4">
                        <?= $form->field($model, 'bookInContactName')->textInput(['placeholder' => 'Contact name']) ?>
                    </div>
                    <div class="col-md-4">
                        <?= $form->field($model, 'bookInContactPhone')->textInput(['placeholder' => '07123 456789']) ?>
                    </div>
                    <div class="col-md-4">
                        <?= $form->field($model, 'bookInEmailAddress')->input('email', ['placeholder' => 'contact@example.com']) ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Notifications -->
    <div class="card mb-4">
        <div class="card-header">Notifications <small class="text-muted">(optional)</small></div>
        <div class="card-body">
            <?= $form->field($model, 'notificationSysGroups')->checkboxList($notificationOptions)->hint('Select which events trigger a notification. SMS only receives event 5 (ETA).') ?>
            <div class="row">
                <div class="col-md-4">
                    <?= $form->field($model, 'notificationSms')->textInput(['placeholder' => '07123 456789'])->hint('Mobile number for ETA SMS.') ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'notificationEmail')->input('email', ['placeholder' => 'notify@example.com']) ?>
                </div>
                <div class="col-md-4">
                    <?= $form->field($model, 'notificationEmail2')->input('email', ['placeholder' => 'notify2@example.com']) ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Products -->
    <div class="card mb-4">
        <div class="card-header">Products <small class="text-muted">(optional)</small></div>
        <div class="card-body">
            <div class="row mb-1">
                <div class="col-md-5"><strong>Description</strong></div>
                <div class="col-md-2"><strong>Quantity</strong></div>
                <div class="col-md-3"><strong>Product Code</strong></div>
                <div class="col-md-2"></div>
            </div>
            <div id="product-rows" data-count="1">
                <div class="row product-row" id="product-row-1">
                    <div class="col-md-5">
                        <input type="text" class="form-control mb-2"
                               name="ConsignmentForm[products][1][description]"
                               placeholder="Description">
                    </div>
                    <div class="col-md-2">
                        <input type="number" class="form-control mb-2"
                               name="ConsignmentForm[products][1][quantity]"
                               placeholder="Qty" min="1" value="1">
                    </div>
                    <div class="col-md-3">
                        <input type="text" class="form-control mb-2"
                               name="ConsignmentForm[products][1][code]"
                               placeholder="Product Code">
                    </div>
                    <div class="col-md-2"></div>
                </div>
            </div>
            <?= Html::button('+ Add Product', [
                'id'    => 'add-product-btn',
                'class' => 'btn btn-sm btn-outline-secondary mt-2',
                'type'  => 'button',
            ]) ?>
        </div>
    </div>

    <div class="form-group">
        <?php if ($queueAvailable): ?>
            <?= Html::submitButton('Queue Consignment', [
                'class' => 'btn btn-primary mr-2',
                'name'  => 'submitAction',
                'value' => 'queue',
            ]) ?>
            <?= Html::submitButton('Send Consignment', [
                'class' => 'btn btn-success',
                'name'  => 'submitAction',
                'value' => 'send',
            ]) ?>
        <?php else: ?>
            <?= Html::submitButton('Send Consignment', [
                'class' => 'btn btn-success',
                'name'  => 'submitAction',
                'value' => 'send',
            ]) ?>
        <?php endif; ?>
        <?= Html::a('Cancel', ['/gforce/config'], ['class' => 'btn btn-secondary ml-2']) ?>
    </div>

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

</div>
