<?php

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

/**
 * @var yii\web\View $this
 * @var array|null $allOrders
 * @var string|null $error
 * @var int $limit
 * @var int $pollLimit
 * @var string|null $cursor
 * @var string|null $nextCursor
 */

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

$orders = $allOrders ?? [];
?>

<div class="virtualstock-order-import-all">
    <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-all', 'limit' => $limit], ['class' => 'btn btn-outline-primary btn-sm']) ?>
        </div>
    </div>

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

    <form method="get" action="<?= Url::to(['/virtualstock/config/order-import-all']) ?>" 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' => 1000, 'style' => 'width:90px'
        ]) ?>
        <?= Html::submitButton('Fetch', ['class' => 'btn btn-outline-secondary btn-sm']) ?>
    </form>

    <?php if (!empty($orders)): ?>
        <div class="table-responsive">
            <table class="table table-bordered table-sm table-hover">
                <thead class="thead-light">
                    <tr>
                        <th>Order Identifier</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Customer</th>
                        <th>Lines</th>
                        <th>Raw</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $order):
                        $id = $order['order_reference'] ?? $order['id'] ?? $order['order_id'] ?? $order['reference'] ?? $order['url'] ?? '—';
                        $status = $order['status'] ?? '—';
                        $date = $order['order_date'] ?? ($order['created_at'] ?? '—');
                        $cust = $order['shipping_address']['full_name'] ?? $order['retailer_data']['name'] ?? ($order['customerName'] ?? '—');
                        $lines = is_array($order['items'] ?? null) ? count($order['items']) : 0;
                    ?>
                    <tr>
                        <td><strong><?= Html::encode($id) ?></strong></td>
                        <td><?= Html::encode($status) ?></td>
                        <td><?= Html::encode($date) ?></td>
                        <td><?= Html::encode($cust) ?></td>
                        <td><?= Html::encode((string)$lines) ?></td>
                        <td>
                            <?= Html::button('View', [
                                'type' => 'button',
                                'class' => 'btn btn-sm btn-outline-info vs-view-raw',
                                'data-order' => Html::encode(base64_encode(Json::encode($order)))
                            ]) ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php else: ?>
        <div class="alert alert-info">No orders returned from the API.</div>
    <?php endif; ?>

</div>

<div id="vs-raw-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">Order Raw 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"><pre id="vs-raw-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 (){
    document.addEventListener('click', function (e) {
        var btn = e.target.closest('.vs-view-raw');
        if (btn) {
            var raw = btn.getAttribute('data-order') || btn.dataset.order || '';
            try { raw = atob(raw); } catch (err) { /* ignore */ }
            var parsed = raw;
            try { parsed = JSON.parse(raw); } catch (err) { parsed = raw; }
            document.getElementById('vs-raw-pre').textContent = JSON.stringify(parsed, null, 2);
            if (typeof jQuery !== 'undefined' && typeof jQuery('#vs-raw-modal').modal === 'function') {
                jQuery('#vs-raw-modal').modal('show');
            }
        }
        var close = e.target.closest('.vs-modal-close');
        if (close && typeof jQuery !== 'undefined' && typeof jQuery('#vs-raw-modal').modal === 'function') {
            jQuery('#vs-raw-modal').modal('hide');
        }
    });
})();
</script>
