<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use PortalPeople\shippingcosts\models\ColumnMapForm;

/* @var $this     yii\web\View */
/* @var $mapForm  PortalPeople\shippingcosts\models\ColumnMapForm */
/* @var $preview  list<array<string,mixed>>  First 3 rows from session */
/* @var $stats    array  ['input','output','merged','skipped'] */

$this->title = 'Map Columns';
$this->params['breadcrumbs'][] = ['label' => 'Shippingcosts', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => 'Upload',        'url' => ['upload']];
$this->params['breadcrumbs'][] = $this->title;

$roleOptions = ColumnMapForm::roleOptions();
?>
<div class="shippingcosts-map">

    <?php if (Yii::$app->session->hasFlash('error')): ?>
        <div class="alert alert-danger mb-3">
            <?= \yii\helpers\Html::encode(Yii::$app->session->getFlash('error')) ?>
        </div>
    <?php endif; ?>

    <?php if (!empty($stats)): ?>
        <div class="alert alert-info mb-3">
            Consolidated sheet:
            <strong><?= (int) $stats['input'] ?></strong> input rows &rarr;
            <strong><?= (int) $stats['output'] ?></strong> output rows
            (merged <strong><?= (int) $stats['merged'] ?></strong>,
             skipped <strong><?= (int) $stats['skipped'] ?></strong>)
        </div>
    <?php endif; ?>

    <div class="card mb-3">
        <div class="card-header"><h4 class="mb-0">Map Spreadsheet Columns</h4></div>
        <div class="card-body">
            <p class="text-muted">
                Assign each column a role. Columns marked <strong>Price Column</strong> will be
                parsed for size (<code>Qtr=0.25 / Half=0.50 / Full=1.00</code>) and
                qty (<code>{n}&nbsp;X</code>) from the header text; the cell value becomes the price.
            </p>

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

                <?php
                // Render hidden inputs for the headers array so the model can be reloaded
                foreach ($mapForm->headers as $i => $header):
                ?>
                    <?= Html::hiddenInput("ColumnMapForm[headers][{$i}]", $header) ?>
                <?php endforeach; ?>

                <div class="table-responsive">
                    <table class="table table-sm table-bordered align-middle">
                        <thead class="thead-light">
                            <tr>
                                <th style="width:10%">Column Header</th>
                                <th style="width:20%">Role</th>
                                <th>Price-header parse preview</th>
                                <?php foreach ($preview as $pi => $previewRow): ?>
                                    <th class="text-muted" style="width:20%">Preview row <?= $pi + 1 ?></th>
                                <?php endforeach; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($mapForm->headers as $header):
                                $currentRole = $mapForm->assignments[$header] ?? ColumnMapForm::ROLE_IGNORE;
                                $parsed      = ColumnMapForm::parsePriceHeader((string) $header);
                            ?>
                                <tr>
                                    <td><code><?= Html::encode((string) $header) ?></code></td>
                                    <td>
                                        <?= Html::dropDownList(
                                            'ColumnMapForm[assignments][' . $header . ']',
                                            $currentRole,
                                            $roleOptions,
                                            [
                                                'class'                => 'form-control form-control-sm role-select',
                                                'data-header'          => $header,
                                                'data-parsed-size'     => $parsed['size'] ?? '',
                                                'data-parsed-qty'      => $parsed['qty']  ?? '',
                                            ]
                                        ) ?>
                                    </td>
                                    <td class="parse-preview text-muted small">
                                        <?php if ($currentRole === ColumnMapForm::ROLE_PRICE): ?>
                                            <?= Html::encode(
                                                'label: "' . $parsed['label'] . '"'
                                                . ($parsed['size'] !== null ? ', size: ' . $parsed['size'] : '')
                                                . ($parsed['qty']  !== null ? ', qty: '  . $parsed['qty']  : '')
                                            ) ?>
                                        <?php endif; ?>
                                    </td>
                                    <?php foreach ($preview as $previewRow): ?>
                                        <td class="text-muted small" style="width:20%; max-width:20%; white-space:normal; overflow-wrap:break-word; word-break:break-all;"><?= str_replace('||', '|| ', Html::encode((string) ($previewRow[$header] ?? ''))) ?></td>
                                    <?php endforeach; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($mapForm->hasErrors('assignments')): ?>
                    <div class="alert alert-danger">
                        <?= Html::encode(implode(' ', $mapForm->getErrors('assignments'))) ?>
                    </div>
                <?php endif; ?>

                <div class="mt-3">
                    <?= Html::a('&larr; Upload another file', ['upload'], ['class' => 'btn btn-secondary me-2']) ?>
                    <?= Html::submitButton('Proceed to Import &rarr;', ['class' => 'btn btn-primary']) ?>
                </div>

            <?php ActiveForm::end() ?>
        </div>
    </div>

</div>

<?php
// Inline JS: update the parse-preview cell whenever a role dropdown changes
$js = <<<JS
document.querySelectorAll('.role-select').forEach(function(sel) {
    sel.addEventListener('change', function() {
        var cell    = this.closest('tr').querySelector('.parse-preview');
        var role    = this.value;
        var size    = this.dataset.parsedSize;
        var qty     = this.dataset.parsedQty;
        var label   = this.dataset.header;
        if (role === 'price') {
            var parts = ['label: "' + label + '"'];
            if (size) parts.push('size: ' + size);
            if (qty)  parts.push('qty: '  + qty);
            cell.textContent = parts.join(', ');
        } else {
            cell.textContent = '';
        }
    });
});
JS;
$this->registerJs($js);
?>
