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

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

/**
 * @var yii\web\View $this
 * @var PortalPeople\palletways\models\ConsignmentForm $model
 */

$this->title = 'Create Palletways Consignment';
$this->params['breadcrumbs'][] = ['label' => 'Palletways', 'url' => ['/palletways/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',
];

// Toggle book-in fields based on checkbox
$this->registerJs(<<<JS
    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();
    });
JS
);
?>

<div class="palletways-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 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')->textInput([
                        'placeholder' => 'e.g. A or B',
                        'maxlength'   => 10,
                    ])->hint('Use AvailableServices API to confirm valid codes for your route.') ?>
                </div>
                <div class="col-md-3">
                    <?= $form->field($model, 'serviceSurcharge')->textInput([
                        'placeholder' => 'e.g. A or B',
                        'maxlength'   => 10,
                    ]) ?>
                </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>
            <?= $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">
        <?= Html::submitButton('Create Consignment', ['class' => 'btn btn-success']) ?>
        <?= Html::a('Cancel', ['/palletways/config'], ['class' => 'btn btn-secondary ml-2']) ?>
    </div>

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

</div>
