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

$csvOptions = [
    '__skip__' => '- Skip -',
    'CSV Columns' => [],
];

foreach ($headers as $header) {
    $csvOptions['CSV Columns'][$header] = $header;
}

$mappingByTarget = [];
foreach ($savedMapping as $key => $value) {
    if (!is_string($key) || !is_string($value)) {
        continue;
    }

    if (strpos($key, 'cartsbe.') === 0 || strpos($key, 'cartlines.') === 0) {
        $mappingByTarget[$key] = $value;
        continue;
    }

    if (strpos($value, 'cartsbe.') === 0 || strpos($value, 'cartlines.') === 0) {
        if (!isset($mappingByTarget[$value])) {
            $mappingByTarget[$value] = $key;
        }
    }
}

$targetRows = [];
foreach ($cartsbeFields as $fieldName => $fieldLabel) {
    $targetRows[] = [
        'target' => 'cartsbe.' . $fieldName,
        'group' => 'Cartsbe - Order Header',
        'label' => $fieldLabel,
    ];
}
foreach ($cartlinesFields as $fieldName => $fieldLabel) {
    $targetRows[] = [
        'target' => 'cartlines.' . $fieldName,
        'group' => 'Cartlines - Order Line',
        'label' => $fieldLabel,
    ];
}

$gridRows = [];
foreach ($targetRows as $row) {
    $target = $row['target'];
    $savedHeader = $mappingByTarget[$target] ?? '';

    if ($savedHeader === '') {
        foreach ($headers as $header) {
            if (QvcImportService::guessMapping($header) === $target) {
                $savedHeader = $header;
                break;
            }
        }
    }

    $gridRows[] = [
        'group' => $row['group'],
        'target' => $target,
        'label' => $row['label'],
        'selectedHeader' => $savedHeader,
        'samples' => array_map(
            static function ($sampleRow) use ($savedHeader) {
                if ($savedHeader === '__skip__' || $savedHeader === '' || !isset($sampleRow[$savedHeader])) {
                    return '';
                }

                return (string) $sampleRow[$savedHeader];
            },
            $sampleRows
        ),
    ];
}

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

$columns = [
    [
        'label' => 'Target Field',
        'format' => 'raw',
        'value' => static function ($row) {
            return '<div><span style="display:block; color:#888; font-size:0.78rem;">'
                . Html::encode($row['group'])
                . '</span><span style="font-weight:600; word-break:break-word;">'
                . Html::encode($row['label'])
                . '</span><span style="display:block; color:#999; font-size:0.75rem;">'
                . Html::encode($row['target'])
                . '</span></div>';
        },
        'contentOptions' => ['style' => 'width:30%;'],
    ],
    [
        'label' => 'CSV Column',
        'format' => 'raw',
        'value' => static function ($row) use ($csvOptions) {
            return Html::dropDownList(
                'mapping[' . $row['target'] . ']',
                $row['selectedHeader'],
                $csvOptions,
                ['class' => 'form-control form-control-sm mapping-select']
            );
        },
        'contentOptions' => ['style' => 'width:26%;'],
    ],
];

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> -
        Select a CSV column for each target field.
        CSV columns can be reused across multiple target fields.
    </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>
