<?php
/**
 * Step 3 — Preview the mapped Cartsbe/Cartlines orders before approval.
 *
 * @var yii\web\View  $this
 * @var array         $previewData    Contains: fileName, summary, orders, skippedRows, mapping, createdAt
 * @var array|null    $importResult   Flash result from a previous approve attempt
 * @var string|null   $detectedMapMessage
 */
$this->title = 'Import CSV — Preview Mapped Orders';

$summary     = $previewData['summary']    ?? [];
$orders      = $previewData['orders']     ?? [];
$skippedRows = $previewData['skippedRows'] ?? [];
$fileName    = $previewData['fileName']   ?? '';
$mapping     = $previewData['mapping']    ?? [];
$detectedMapMessage = $detectedMapMessage ?? null;

// Build a human-readable label for each mapped target.
$targetLabels = [];
foreach ($mapping as $key => $value) {
    if (!is_string($key) || !is_string($value) || $value === '' || $value === '__skip__') {
        continue;
    }

    // Support both mapping shapes:
    // 1) csvHeader => cartsbe.field / cartlines.field
    // 2) cartsbe.field / cartlines.field => csvHeader
    if (strpos($key, 'cartsbe.') === 0 || strpos($key, 'cartlines.') === 0) {
        $target = $key;
        $csvCol = $value;
    } else {
        $target = $value;
        $csvCol = $key;
    }

    if (strpos($target, '.') === false) {
        continue;
    }

    [$model, $field] = explode('.', $target, 2);
    if ($field === '') {
        continue;
    }

    $targetLabels[$csvCol] = ($model === 'cartsbe' ? 'Header' : 'Line') . ': ' . $field;
}
?>
<div class="qvc-mapped-preview">

    <h1><?= $this->title ?></h1>

    <?php if ($importResult !== null) { ?>
        <div class="alert alert-<?= $importResult['success'] ? 'success' : 'danger' ?>">
            <?= htmlspecialchars($importResult['message']) ?>
            <?php if (!empty($importResult['errors'])) { ?>
                <ul style="margin:8px 0 0;">
                    <?php foreach ($importResult['errors'] as $err) { ?>
                        <li>
                            <strong><?= htmlspecialchars($err['groupKey']) ?></strong>:
                            <?= htmlspecialchars($err['error']) ?>
                        </li>
                    <?php } ?>
                </ul>
            <?php } ?>
        </div>
    <?php } ?>

    <?php if ($detectedMapMessage !== null) { ?>
        <div class="alert alert-info">
            <?= htmlspecialchars($detectedMapMessage) ?>
        </div>
    <?php } ?>

    <?php if (empty($orders)) { ?>
        <div class="alert alert-warning">
            No valid orders were produced from the mapping. Please
            <a href="<?= \yii\helpers\Url::to(['upload-csv']) ?>">upload a new file</a>.
        </div>
    <?php } else { ?>
        <!-- Summary strip -->
        <div class="d-flex gap-3 mb-4">
            <div class="card flex-fill text-center p-3" style="background:#f5f5f5;">
                <div style="font-size:2rem; font-weight:700; color:#337ab7;">
                    <?= (int) ($summary['orderCount'] ?? 0) ?>
                </div>
                <div class="text-muted">Orders</div>
            </div>
            <div class="card flex-fill text-center p-3" style="background:#f5f5f5;">
                <div style="font-size:2rem; font-weight:700; color:#5cb85c;">
                    <?= (int) ($summary['lineCount'] ?? 0) ?>
                </div>
                <div class="text-muted">Lines</div>
            </div>
            <?php if (($summary['skippedCount'] ?? 0) > 0) { ?>
                <div class="card flex-fill text-center p-3" style="background:#fff8e1;">
                    <div style="font-size:2rem; font-weight:700; color:#f0ad4e;">
                        <?= (int) $summary['skippedCount'] ?>
                    </div>
                    <div class="text-muted">Skipped Rows</div>
                </div>
            <?php } ?>
        </div>

        <!-- Per-order accordion -->
        <?php foreach ($orders as $i => $order) {
            $groupKey  = htmlspecialchars($order['groupKey']);
            $cartsbe   = $order['cartsbe']  ?? [];
            $lines     = $order['lines']    ?? [];
            $panelId   = 'order-panel-' . $i;
        ?>
            <div class="card mb-2">
                <div class="card-header"
                     style="cursor:pointer; user-select:none;"
                     onclick="togglePanel('<?= $panelId ?>')">
                    <strong>Order <?= ($i + 1) ?></strong>
                    &mdash; <span class="text-muted"><?= $groupKey ?></span>
                    <span class="float-right text-muted" style="font-size:0.85rem;">
                        <?= count($lines) ?> line<?= count($lines) !== 1 ? 's' : '' ?>
                    </span>
                </div>
                <div class="card-body" id="<?= $panelId ?>" style="display:none;">

                    <!-- Cartsbe header fields -->
                    <?php if (!empty($cartsbe)) { ?>
                        <h5 style="margin:0 0 8px; color:#337ab7;">Order Header (Cartsbe)</h5>
                        <table class="table table-sm table-bordered" style="font-size:0.85rem; margin-bottom:12px;">
                            <thead><tr><th>Field</th><th>Value</th></tr></thead>
                            <tbody>
                                <?php foreach ($cartsbe as $f => $v) { ?>
                                    <tr>
                                        <td style="color:#555;"><?= htmlspecialchars($f) ?></td>
                                        <td><?= htmlspecialchars((string) $v) ?></td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    <?php } ?>

                    <!-- Cartlines -->
                    <?php if (!empty($lines)) { ?>
                        <h5 style="margin:0 0 8px; color:#5cb85c;">Order Lines (Cartlines)</h5>
                        <?php
                        $lineKeys = array_unique(array_merge(...array_map('array_keys', $lines)));
                        ?>
                        <table class="table table-sm table-bordered" style="font-size:0.85rem;">
                            <thead>
                                <tr>
                                    <?php foreach ($lineKeys as $lk) {
                                        echo '<th>' . htmlspecialchars($lk) . '</th>';
                                    } ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($lines as $line) { ?>
                                    <tr>
                                        <?php foreach ($lineKeys as $lk) {
                                            $cellVal = isset($line[$lk]) ? (string) $line[$lk] : '';
                                            echo '<td>' . htmlspecialchars($cellVal) . '</td>';
                                        } ?>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    <?php } ?>
                </div>
            </div>
        <?php } ?>

        <!-- Skipped rows -->
        <?php if (!empty($skippedRows)) { ?>
            <h4 style="color:#c0392b; margin-top:24px;">
                Skipped Rows (<?= count($skippedRows) ?>)
            </h4>
            <table class="table table-sm table-bordered" style="font-size:0.85rem;">
                <thead>
                    <tr>
                        <th>CSV Row #</th>
                        <th>Reason</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($skippedRows as $skipped) { ?>
                        <tr>
                            <td><?= (int) $skipped['line'] ?></td>
                            <td><?= htmlspecialchars($skipped['reason']) ?></td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        <?php } ?>

        <!-- Approve / back buttons -->
        <div style="margin-top: 24px; display:flex; gap:12px; align-items:center;">
            <form method="post" action="<?= \yii\helpers\Url::to(['approve-mapped-import']) ?>"
                  onsubmit="return confirm('Import <?= (int) ($summary['orderCount'] ?? 0) ?> order(s) into the database? This cannot be undone.');">
                <input type="hidden"
                       name="<?= Yii::$app->request->csrfParam ?>"
                       value="<?= Yii::$app->request->csrfToken ?>">
                <button type="submit" class="btn btn-success btn-lg">
                    &#x2713; Approve &amp; Import to Database
                </button>
            </form>

            <a href="<?= \yii\helpers\Url::to(['map-csv']) ?>" class="btn btn-secondary">
                &larr; Back to Column Mapping
            </a>
            <a href="<?= \yii\helpers\Url::to(['upload-csv']) ?>" class="btn btn-secondary">
                Upload a different file
            </a>
        </div>
    <?php } ?>

    <div style="margin-top:16px; font-size:0.8rem; color:#aaa;">
        File: <?= htmlspecialchars($fileName) ?>
        &bull; Prepared: <?= htmlspecialchars($previewData['createdAt'] ?? '') ?>
    </div>
</div>

<script>
function togglePanel(id) {
    var el = document.getElementById(id);
    el.style.display = (el.style.display === 'none') ? 'block' : 'none';
}
// Open the first panel by default.
document.addEventListener('DOMContentLoaded', function () {
    var first = document.getElementById('order-panel-0');
    if (first) { first.style.display = 'block'; }
});
</script>
