<?php

use yii\helpers\Html;
use yii\helpers\Url;

$this->title = Yii::t('app', 'QVC CSV Order Import');
$previewData = $previewData ?? [];
$summary = $previewData['summary'] ?? null;
$orders = $previewData['orders'] ?? [];
$skippedRows = $previewData['skippedRows'] ?? [];
?>

<div class="card">
    <div class="card-header">
        <h2><?= Html::encode($this->title) ?></h2>
        <p class="text-muted mb-0">Upload a CSV, review the converted orders, then approve import.</p>
    </div>
    <div class="card-body">

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger"><?= Html::encode($error) ?></div>
        <?php endif; ?>

        <?php if (!empty($importResult)): ?>
            <div class="alert <?= !empty($importResult['success']) ? 'alert-success' : 'alert-danger' ?>">
                <?= Html::encode($importResult['message'] ?? 'Import completed.') ?>
            </div>
        <?php endif; ?>

        <form method="post" enctype="multipart/form-data" action="<?= Url::to(['uploader']) ?>">
            <input type="hidden" name="<?= Html::encode(Yii::$app->request->csrfParam) ?>" value="<?= Html::encode(Yii::$app->request->csrfToken) ?>">

            <label for="order-csv-file" class="w-100" style="cursor:pointer;">
                <div id="csv-drop-zone" style="border:2px dashed #9da8b5;border-radius:10px;padding:30px;text-align:center;background:#f9fbfd;">
                    <strong>Drop CSV here</strong>
                    <div class="text-muted">or click to browse</div>
                    <div class="mt-2"><small>Accepted: .csv</small></div>
                </div>
            </label>

            <input type="file" id="order-csv-file" name="order-csv-file" accept=".csv,text/csv" class="d-none" required>

            <div class="mt-3">
                <?= Html::submitButton('Upload & Preview', ['class' => 'btn btn-primary']) ?>
            </div>
        </form>

        <?php if ($summary !== null): ?>
            <hr>
            <h4>Preview Summary</h4>
            <div class="row">
                <div class="col-md-3"><strong>File:</strong> <?= Html::encode($previewData['fileName'] ?? 'Unknown') ?></div>
                <div class="col-md-3"><strong>Orders:</strong> <?= Html::encode((string) ($summary['orderCount'] ?? 0)) ?></div>
                <div class="col-md-3"><strong>Order Lines:</strong> <?= Html::encode((string) ($summary['lineCount'] ?? 0)) ?></div>
                <div class="col-md-3"><strong>Skipped Rows:</strong> <?= Html::encode((string) ($summary['skippedCount'] ?? 0)) ?></div>
            </div>

            <?php if (!empty($orders)): ?>
                <div class="table-responsive mt-3">
                    <table class="table table-bordered table-sm">
                        <thead>
                            <tr>
                                <th>Order Ref</th>
                                <th>Customer Ref</th>
                                <th>PO Number</th>
                                <th>Lines</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($orders as $order): ?>
                                <tr>
                                    <td><?= Html::encode($order['orderRef']) ?></td>
                                    <td><?= Html::encode($order['customerRef'] ?: '-') ?></td>
                                    <td><?= Html::encode($order['poNumber'] ?: '-') ?></td>
                                    <td>
                                        <?php foreach ($order['lines'] as $line): ?>
                                            <div>
                                                <?= Html::encode($line['sku']) ?> x <?= Html::encode((string) $line['quantity']) ?>
                                                <?php if ($line['price'] !== ''): ?>
                                                    @ <?= Html::encode((string) $line['price']) ?>
                                                <?php endif; ?>
                                            </div>
                                        <?php endforeach; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>

            <?php if (!empty($skippedRows)): ?>
                <h5 class="mt-3">Skipped Rows</h5>
                <div class="table-responsive">
                    <table class="table table-bordered table-sm">
                        <thead>
                            <tr>
                                <th>Line</th>
                                <th>Reason</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($skippedRows as $skipped): ?>
                                <tr>
                                    <td><?= Html::encode((string) $skipped['line']) ?></td>
                                    <td><?= Html::encode($skipped['reason']) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>

            <form method="post" action="<?= Url::to(['approve-import']) ?>" class="mt-3">
                <input type="hidden" name="<?= Html::encode(Yii::$app->request->csrfParam) ?>" value="<?= Html::encode(Yii::$app->request->csrfToken) ?>">
                <?= Html::submitButton('Approve & Import Orders', [
                    'class' => 'btn btn-success',
                    'data-confirm' => 'Are you sure you want to import these converted orders?',
                ]) ?>
            </form>
        <?php endif; ?>
    </div>
</div>

<script>
(function () {
    var fileInput = document.getElementById('order-csv-file');
    var dropZone = document.getElementById('csv-drop-zone');

    if (!fileInput || !dropZone) {
        return;
    }

    function setFile(files) {
        if (!files || !files.length) {
            return;
        }
        fileInput.files = files;
        dropZone.innerHTML = '<strong>Selected:</strong> ' + files[0].name;
    }

    ['dragenter', 'dragover'].forEach(function (evtName) {
        dropZone.addEventListener(evtName, function (evt) {
            evt.preventDefault();
            dropZone.style.background = '#edf4ff';
            dropZone.style.borderColor = '#3d7cff';
        });
    });

    ['dragleave', 'drop'].forEach(function (evtName) {
        dropZone.addEventListener(evtName, function (evt) {
            evt.preventDefault();
            dropZone.style.background = '#f9fbfd';
            dropZone.style.borderColor = '#9da8b5';
        });
    });

    dropZone.addEventListener('drop', function (evt) {
        setFile(evt.dataTransfer.files);
    });

    fileInput.addEventListener('change', function () {
        setFile(fileInput.files);
    });
})();
</script>
