<?php

/**
 * VirtualStock Module – Order Import Preview
 */

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

/**
 * @var yii\web\View $this
 * @var array|null   $previewData   Result of fetchForPreview(), or null on error.
 * @var string|null  $error         Error message, if fetch failed.
 * @var array|null   $importResult  Flash result from approve action.
 * @var int          $limit         Current limit applied.
 * @var int          $pollLimit     Module's configured pollLimit.
 */

$this->title = 'VirtualStock – Order Import Preview';
$this->params['breadcrumbs'][] = ['label' => 'Integrations', 'url' => ['/']];
$this->params['breadcrumbs'][] = ['label' => 'VirtualStock', 'url' => ['/virtualstock/config/index']];
$this->params['breadcrumbs'][] = 'Order Import Preview';

$orders     = $previewData['orders']     ?? [];
$nextCursor = $previewData['nextCursor'] ?? null;
$newCount   = count(array_filter($orders, fn($o) => $o['_isNew'] ?? true));
$updateCount = count($orders) - $newCount;
$errorCount = count(array_filter($orders, fn($o) => !empty($o['_errors'])));
?>

<div class="virtualstock-order-import">

    <div class="d-flex align-items-center justify-content-between mb-3">
        <h1 class="mb-0"><?= Html::encode($this->title) ?></h1>
        <div>
            <?= Html::a('← Back to Settings', ['/virtualstock/config/index'], ['class' => 'btn btn-outline-secondary btn-sm mr-2']) ?>
            <?= Html::a('Refresh', ['/virtualstock/config/order-import', 'limit' => $limit], ['class' => 'btn btn-outline-primary btn-sm']) ?>
        </div>
    </div>

    <?php if (!empty($importResult)): ?>
        <div class="alert <?= !empty($importResult['success']) ? 'alert-success' : 'alert-danger' ?>">
            <?= Html::encode($importResult['message'] ?? 'Import completed.') ?>
            <?php if (!empty($importResult['stats'])): ?>
                <ul class="mb-0 mt-1 small">
                    <li>Fetched: <?= (int) ($importResult['stats']['fetched']  ?? 0) ?></li>
                    <li>Created: <?= (int) ($importResult['stats']['created']  ?? 0) ?></li>
                    <li>Updated: <?= (int) ($importResult['stats']['updated']  ?? 0) ?></li>
                    <li>Failed:  <?= (int) ($importResult['stats']['failed']   ?? 0) ?></li>
                </ul>
            <?php endif; ?>
        </div>
    <?php endif; ?>

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

    <!-- Limit selector -->
    <form method="get" action="<?= Url::to(['/virtualstock/config/order-import']) ?>" class="form-inline mb-4">
        <label class="mr-2" for="vs-limit">Fetch limit</label>
        <?= Html::input('number', 'limit', (string) $limit, [
            'id'    => 'vs-limit',
            'class' => 'form-control form-control-sm mr-2',
            'min'   => 1,
            'max'   => 500,
            'style' => 'width:90px',
        ]) ?>
        <?= Html::submitButton('Fetch', ['class' => 'btn btn-outline-secondary btn-sm']) ?>
    </form>

    <?php if (!empty($orders)): ?>

        <!-- Summary bar -->
        <div class="row mb-3">
            <div class="col-auto">
                <div class="card border-0 bg-light px-3 py-2 text-center" style="min-width:90px">
                    <div class="h4 mb-0"><?= count($orders) ?></div>
                    <div class="small text-muted">Total</div>
                </div>
            </div>
            <div class="col-auto">
                <div class="card border-0 bg-success text-white px-3 py-2 text-center" style="min-width:90px">
                    <div class="h4 mb-0"><?= $newCount ?></div>
                    <div class="small">New</div>
                </div>
            </div>
            <div class="col-auto">
                <div class="card border-0 bg-warning px-3 py-2 text-center" style="min-width:90px">
                    <div class="h4 mb-0"><?= $updateCount ?></div>
                    <div class="small">Update</div>
                </div>
            </div>
            <?php if ($errorCount > 0): ?>
            <div class="col-auto">
                <div class="card border-0 bg-danger text-white px-3 py-2 text-center" style="min-width:90px">
                    <div class="h4 mb-0"><?= $errorCount ?></div>
                    <div class="small">Errors</div>
                </div>
            </div>
            <?php endif; ?>
            <?php if ($nextCursor): ?>
            <div class="col-auto align-self-center">
                <span class="badge badge-info">More orders available — increase limit to see them</span>
            </div>
            <?php endif; ?>
        </div>

        <!-- Orders table + approve form (single form so product_map fields are included) -->
        <form method="post" action="<?= Url::to(['/virtualstock/config/approve-order-import']) ?>">
            <input type="hidden" name="<?= Html::encode(Yii::$app->request->csrfParam) ?>" value="<?= Html::encode(Yii::$app->request->csrfToken) ?>">

        <div class="table-responsive">
            <table class="table table-bordered table-sm table-hover">
                <thead class="thead-light">
                    <tr>
                        <th style="width:1%"></th>
                        <th>Order Ref</th>
                        <th>Date</th>
                        <th>Status</th>
                        <th>Customer</th>
                        <th>Delivery Postcode</th>
                        <th>Currency</th>
                        <th>Lines</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $idx => $order): ?>
                        <?php
                        $isNew   = $order['_isNew']           ?? true;
                        $orderNo = $order['orderNo']          ?? '—';
                        $rowId   = 'vs-lines-' . $idx;
                        $lines   = $order['orderLines']       ?? [];
                        $errors  = $order['_errors']          ?? [];
                        // Count lines without a product match.
                        $unmatchedLines = 0;
                        foreach ($lines as $l) {
                            $lt = $l['product_lookup']['matchType'] ?? 'none';
                            if ($lt === 'none') { $unmatchedLines++; }
                        }
                        ?>
                        <tr class="<?= $isNew ? '' : 'table-warning' ?><?= !empty($errors) ? ' table-danger' : '' ?>">
                            <td class="text-center">
                                <?php if (!empty($lines)): ?>
                                    <button type="button"
                                            class="btn btn-link btn-sm p-0 vs-toggle-lines"
                                            data-target="#<?= $rowId ?>"
                                            title="Toggle lines">
                                        &#9660;
                                    </button>
                                <?php endif; ?>
                            </td>
                            <td>
                                <strong><?= Html::encode($orderNo) ?></strong>
                                <?php if (!empty($order['customerReference'])): ?>
                                    <br><small class="text-muted">Ref: <?= Html::encode($order['customerReference']) ?></small>
                                <?php endif; ?>
                            </td>
                            <td><?= Html::encode($order['orderDate'] ?? '—') ?></td>
                            <td>
                                <span class="badge badge-secondary"><?= Html::encode($order['status'] ?? '—') ?></span>
                            </td>
                            <td>
                                <?= Html::encode($order['customerName'] ?? '—') ?>
                                <?php if (!empty($order['customerEmail'])): ?>
                                    <br><small class="text-muted"><?= Html::encode($order['customerEmail']) ?></small>
                                <?php endif; ?>
                                <?php if (!empty($order['telephone'])): ?>
                                    <br><small class="text-muted"><?= Html::encode($order['telephone']) ?></small>
                                <?php endif; ?>
                            </td>
                            <td><?= Html::encode($order['deliveryPostcode'] ?? '—') ?></td>
                            <td><?= Html::encode($order['currency'] ?? '—') ?></td>
                            <td>
                                <?= count($lines) ?> line<?= count($lines) !== 1 ? 's' : '' ?>
                                <?php if ($unmatchedLines > 0): ?>
                                    <br><span class="badge badge-warning"><?= $unmatchedLines ?> unmatched</span>
                                <?php elseif (count($lines) > 0): ?>
                                    <br><span class="badge badge-success">All matched</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($isNew): ?>
                                    <span class="badge badge-success">New</span>
                                <?php else: ?>
                                    <span class="badge badge-warning">Update</span>
                                    <?php if (!empty($order['_existingOrderNo'])): ?>
                                        <br><small class="text-muted"><?= Html::encode($order['_existingOrderNo']) ?></small>
                                    <?php endif; ?>
                                <?php endif; ?>
                                <?php if (!empty($errors)): ?>
                                    <br><span class="badge badge-danger"><?= count($errors) ?> error<?= count($errors) !== 1 ? 's' : '' ?></span>
                                <?php endif; ?>
                                <br>
                                <?= Html::button('View Data', [
                                    'type' => 'button',
                                    'class' => 'btn btn-sm btn-outline-info mt-1 vs-view-data',
                                    'data-order' => Html::encode(base64_encode(Json::encode($order))),
                                    'title' => 'View full normalized and raw payload',
                                ]) ?>
                            </td>
                        </tr>
                        <?php if (!empty($errors)): ?>
                        <tr class="table-danger">
                            <td></td>
                            <td colspan="8">
                                <ul class="mb-0 small text-danger pl-3">
                                    <?php foreach ($errors as $err): ?>
                                        <li><?= Html::encode($err) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </td>
                        </tr>
                        <?php endif; ?>
                        <?php if (!empty($lines)): ?>
                        <tr id="<?= $rowId ?>" class="vs-lines-row d-none">
                            <td colspan="9" class="p-0">
                                <div class="p-3 bg-light border-top">
                                    <!-- Delivery address -->
                                    <?php if (!empty($order['deliveryAddress'])): ?>
                                        <div class="mb-2 small text-muted">
                                            <strong>Delivery:</strong>
                                            <?= Html::encode(implode(', ', array_filter($order['deliveryAddress']))) ?>
                                        </div>
                                    <?php endif; ?>
                                    <!-- Lines table -->
                                    <table class="table table-sm table-bordered mb-0">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>SKU / Part No.</th>
                                                <th>Description</th>
                                                <th>Qty</th>
                                                <th>Unit Price</th>
                                                <th>Match</th>
                                                <th style="min-width:250px">Product Mapping</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($lines as $line):
                                                $lookup    = $line['product_lookup'] ?? [];
                                                $matchType = $lookup['matchType'] ?? 'none';
                                                $matchBadge = match($matchType) {
                                                    'sku'  => '<span class="badge badge-success">SKU match</span>',
                                                    'name' => '<span class="badge badge-warning">Name match</span>',
                                                    default => '<span class="badge badge-danger">No match</span>',
                                                };
                                                $lineNo    = (int) ($line['lineNo'] ?? 0);
                                                $selectName = 'product_map[' . Html::encode($orderNo) . '][' . $lineNo . ']';
                                                $selectId   = 'pm_' . $idx . '_' . $lineNo;
                                                $options    = $lookup['options'] ?? [];
                                                $selected   = $lookup['selectedProductId'] ?? '';
                                            ?>
                                            <tr>
                                                <td>
                                                    <code><?= Html::encode($line['sku'] ?? $line['supplierProductNo'] ?? '—') ?></code>
                                                    <?php if (!empty($line['supplierProductNo']) && ($line['supplierProductNo'] !== ($line['sku'] ?? ''))): ?>
                                                        <br><small class="text-muted"><?= Html::encode($line['supplierProductNo']) ?></small>
                                                    <?php endif; ?>
                                                </td>
                                                <td><?= Html::encode($line['productDescription'] ?? $line['name'] ?? '—') ?></td>
                                                <td class="text-right"><?= Html::encode((string)($line['quantity'] ?? 1)) ?></td>
                                                <td class="text-right"><?= Html::encode((string)($line['unitPrice'] ?? '—')) ?></td>
                                                <td>
                                                    <?= $matchBadge ?>
                                                    <?php if (!empty($lookup['matchedProductLabel'])): ?>
                                                        <br><small class="text-muted"><?= Html::encode($lookup['matchedProductLabel']) ?></small>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?= \kartik\select2\Select2::widget([
                                                        'name'    => $selectName,
                                                        'id'      => $selectId,
                                                        'value'   => $selected !== '' ? $selected : null,
                                                        'data'    => $options,
                                                        'options' => [
                                                            'placeholder' => $matchType === 'none' ? '— Search or select product —' : '— Override product —',
                                                        ],
                                                        'pluginOptions' => [
                                                            'allowClear' => true,
                                                        ],
                                                    ]) ?>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </td>
                        </tr>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

            <!-- Approve & Import -->
            <?= Html::submitButton('Approve &amp; Import ' . count($orders) . ' Order' . (count($orders) !== 1 ? 's' : ''), [
                'class'        => 'btn btn-success mt-2',
                'data-confirm' => 'Are you sure you want to import ' . count($orders) . ' order(s) from VirtualStock?',
            ]) ?>
            <span class="text-muted small ml-3">
                <?= $newCount ?> new &bull; <?= $updateCount ?> update
            </span>

        </form>

    <?php elseif ($previewData !== null && empty($error)): ?>
        <div class="alert alert-info">
            No pending orders found from the VirtualStock API.
            <?php if ($nextCursor === null && ($previewData['cursor'] ?? null) !== null): ?>
                The cursor is set — try
                <a href="<?= Url::to(['/virtualstock/config/order-import', 'limit' => $limit]) ?>">refreshing</a>
                or clear the cursor from the configuration page.
            <?php endif; ?>
        </div>
    <?php endif; ?>

</div>

<!-- Data preview modal (uses Bootstrap if available) -->
<div id="vs-data-modal" class="modal fade d-none" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">VirtualStock Order Data</h5>
        <button type="button" class="close vs-modal-close" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        <div class="mb-2">
            <button type="button" class="btn btn-sm btn-outline-secondary mr-2" id="vs-show-normalized">Normalized</button>
            <button type="button" class="btn btn-sm btn-outline-secondary" id="vs-show-raw">Raw</button>
        </div>
        <pre id="vs-data-pre" style="max-height:60vh;overflow:auto;background:#f8f9fa;padding:1rem;border-radius:4px;"></pre>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary vs-modal-close">Close</button>
      </div>
    </div>
  </div>
</div>

<script>
(function () {
    function htmlDecode(input) {
        var e = document.createElement('textarea');
        e.innerHTML = input;
        return e.value;
    }

    // Toggle lines expand/collapse
    document.addEventListener('click', function (e) {
        var btn = e.target.closest('.vs-toggle-lines');
        if (btn) {
            var targetId = btn.getAttribute('data-target');
            var row = document.querySelector(targetId);
            if (row) {
                row.classList.toggle('d-none');
                btn.innerHTML = row.classList.contains('d-none') ? '\u25BC' : '\u25B2';
            }
            return;
        }

        // Open data preview modal
        var viewBtn = e.target.closest('.vs-view-data');
        if (viewBtn) {
            var rawAttr = viewBtn.getAttribute('data-order') || viewBtn.dataset.order || '';
            rawAttr = htmlDecode(rawAttr);
            var jsonStr = '';
            try {
                jsonStr = atob(rawAttr);
            } catch (err) {
                // If atob fails, assume the attribute already contains JSON
                jsonStr = rawAttr;
            }
            var parsed = null;
            try { parsed = JSON.parse(jsonStr); } catch (err) { parsed = jsonStr; }

            // store parsed object on modal element for toggling views
            var modal = document.getElementById('vs-data-modal');
            modal._vs_parsed = parsed;
            modal._vs_raw = parsed && parsed._raw ? parsed._raw : null;

            // show normalized view by default
            var pretty = '';
            try { pretty = JSON.stringify(parsed, null, 2); } catch (e) { pretty = String(parsed); }
            document.getElementById('vs-data-pre').textContent = pretty;

            // Show modal: prefer Bootstrap, otherwise use simple fallback with backdrop
            if (typeof jQuery !== 'undefined' && typeof jQuery('#vs-data-modal').modal === 'function') {
                jQuery('#vs-data-modal').modal('show');
            } else {
                // create backdrop
                var existing = document.getElementById('vs-data-backdrop');
                if (!existing) {
                    var backdrop = document.createElement('div');
                    backdrop.id = 'vs-data-backdrop';
                    backdrop.style.position = 'fixed';
                    backdrop.style.left = 0;
                    backdrop.style.top = 0;
                    backdrop.style.right = 0;
                    backdrop.style.bottom = 0;
                    backdrop.style.background = 'rgba(0,0,0,0.5)';
                    backdrop.style.zIndex = 1040;
                    document.body.appendChild(backdrop);
                }
                modal.classList.remove('d-none');
                modal.style.display = 'block';
                modal.style.position = 'fixed';
                modal.style.left = '50%';
                modal.style.top = '10%';
                modal.style.transform = 'translateX(-50%)';
                modal.style.zIndex = 1050;
            }
            return;
        }

        // Close modal handlers
        var closeBtn = e.target.closest('.vs-modal-close');
        if (closeBtn) {
            var modal = document.getElementById('vs-data-modal');
            if (typeof jQuery !== 'undefined' && typeof jQuery('#vs-data-modal').modal === 'function') {
                jQuery('#vs-data-modal').modal('hide');
            } else {
                modal.classList.add('d-none');
                modal.style.display = 'none';
                var backdrop = document.getElementById('vs-data-backdrop');
                if (backdrop) { backdrop.parentNode.removeChild(backdrop); }
            }
            return;
        }
    });

    // Toggle between Normalized and Raw views (guard for element existence)
    var btnNorm = document.getElementById('vs-show-normalized');
    var btnRaw  = document.getElementById('vs-show-raw');
    if (btnNorm) {
        btnNorm.addEventListener('click', function () {
            var modal = document.getElementById('vs-data-modal');
            var parsed = modal._vs_parsed;
            var pretty = '';
            try { pretty = JSON.stringify(parsed, null, 2); } catch (e) { pretty = String(parsed); }
            document.getElementById('vs-data-pre').textContent = pretty;
        });
    }
    if (btnRaw) {
        btnRaw.addEventListener('click', function () {
            var modal = document.getElementById('vs-data-modal');
            var raw = modal._vs_raw;
            var pretty = '';
            try { pretty = JSON.stringify(raw !== null ? raw : modal._vs_parsed, null, 2); } catch (e) { pretty = String(raw); }
            document.getElementById('vs-data-pre').textContent = pretty;
        });
    }

})();
</script>
