<?php

use common\widgets\GridView;
use PortalPeople\qvc\components\QvcImportService;
use yii\data\ArrayDataProvider;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;

/**
 * Step 2 - Map CSV columns to Cartsbe / Cartlines fields.
 *
 * @var yii\web\View $this
 * @var string[] $headers
 * @var array[] $sampleRows
 * @var string $fileName
 * @var array $cartsbeFields
 * @var array $cartlinesFields
 * @var array $savedMapping
 * @var string|null $error
 */
$this->title = 'Import CSV - Map Columns';
$sampleCount = count($sampleRows);

$groupedDropdownItems = [
    '__skip__' => '- Skip -',
    'Cartsbe - Order Header' => [],
    'Cartlines - Order Line' => [],
];

foreach ($cartsbeFields as $fieldName => $fieldLabel) {
    $groupedDropdownItems['Cartsbe - Order Header']['cartsbe.' . $fieldName] = $fieldLabel;
}

foreach ($cartlinesFields as $fieldName => $fieldLabel) {
    $groupedDropdownItems['Cartlines - Order Line']['cartlines.' . $fieldName] = $fieldLabel;
}

$gridRows = [];
foreach ($headers as $header) {
    $savedTarget = $savedMapping[$header] ?? '';
    $guessedTarget = QvcImportService::guessMapping($header);
    $selectedTarget = $savedTarget !== '' ? $savedTarget : $guessedTarget;

    $gridRows[] = [
        'header' => $header,
        'selectedTarget' => $selectedTarget,
        'samples' => array_map(
            static function ($sampleRow) use ($header) {
                return isset($sampleRow[$header]) ? (string) $sampleRow[$header] : '';
            },
            $sampleRows
        ),
    ];
}

$dataProvider = new ArrayDataProvider([
    'allModels' => $gridRows,
    'pagination' => false,
]);

$columns = [
    [
        'attribute' => 'header',
        'label' => 'CSV Column',
        'format' => 'raw',
        'value' => static function ($row) {
            return '<span style="font-weight:600; word-break:break-word;">' . Html::encode($row['header']) . '</span>';
        },
        'contentOptions' => ['style' => 'width:22%;'],
    ],
    [
        'label' => 'Map To',
        'format' => 'raw',
        'value' => static function ($row) use ($groupedDropdownItems) {
            return Html::dropDownList(
                'mapping[' . $row['header'] . ']',
                $row['selectedTarget'],
                $groupedDropdownItems,
                ['class' => 'form-control form-control-sm mapping-select']
            );
        },
        'contentOptions' => ['style' => 'width:28%;'],
    ],
];

for ($i = 0; $i < $sampleCount; $i++) {
    $columns[] = [
        'label' => 'Sample row ' . ($i + 1),
        'format' => 'raw',
        'value' => static function ($row) use ($i) {
            $value = $row['samples'][$i] ?? '';
            return '<span style="font-size:0.85rem; color:#555; word-break:break-all;">'
                . Html::encode(mb_strimwidth($value, 0, 60, '...'))
                . '</span>';
        },
        'headerOptions' => ['class' => 'text-muted', 'style' => 'font-weight:normal; font-size:0.85rem;'],
    ];
}
?>

<div class="qvc-map-csv">
    <h1><?= Html::encode($this->title) ?></h1>

    <p class="text-muted">
        File: <strong><?= Html::encode($fileName) ?></strong> -
        Assign each CSV column to an order-header (Cartsbe) or order-line (Cartlines) field,
        or choose <em>Skip</em> to ignore the column.
    </p>

    <?php if ($error !== null) { ?>
        <div class="alert alert-danger">
            <strong>Error:</strong> <?= Html::encode($error) ?>
        </div>
    <?php } ?>

    <?php $form = ActiveForm::begin([
        'id' => 'map-csv-form',
        'method' => 'post',
    ]); ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'layout' => '{items}',
        'tableOptions' => [
            'class' => 'table table-bordered table-hover',
            'style' => 'width:100%; table-layout:fixed;',
        ],
        'columns' => $columns,
    ]) ?>

    <div class="form-group" style="margin-top: 16px; display:flex; gap:12px; align-items:center;">
        <?= Html::submitButton('Continue to Preview &rarr;', ['class' => 'btn btn-success']) ?>
        <a href="<?= Url::to(['upload-csv']) ?>" class="btn btn-secondary">
            &larr; Upload a different file
        </a>
    </div>

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

    <?php if ($sampleCount > 0) { ?>
        <div style="margin-top: 24px; font-size: 0.8rem; color: #888;">
            Showing first <?= (int) $sampleCount ?> data rows as samples.
        </div>
    <?php } ?>
</div>
