<?php

use kartik\select2\Select2;
use yii\helpers\Html;
use yii\widgets\Pjax;

/* @var $this yii\web\View */
/* @var $orders array */
/* @var $nextCursor string|null */
/* @var $cursor string|null */
/* @var $limit int */
/* @var $cacheKey string */
/* @var $cached bool */

$this->title = 'Import Orders from Caterpoint';
if (isset($this->params['breadcrumbs'])) {
    $this->params['breadcrumbs'][] = ['label' => 'Caterpoint', 'url' => ['index']];
    $this->params['breadcrumbs'][] = $this->title;
}
?>

<div class="order-bulk-list">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <h1><?= Html::encode($this->title) ?></h1>
            </div>
        </div>

        <div class="row mt-3">
            <div class="col-md-12">
                <div class="alert alert-info">
                    <strong>Cache Status:</strong> <?= $cached ? '✓ Using cached data (1 hour TTL)' : '✗ Fresh data from API' ?>
                    <?php if ($cached): ?>
                        <?= Html::a('Refresh Cache', ['bulk-list', 'cursor' => $cursor, 'limit' => $limit, 'refresh' => 1], ['class' => 'btn btn-sm btn-primary ms-2']) ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <?php Pjax::begin(['id' => 'order-grid-pjax']); ?>

        <div class="row mt-3">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-body">
                        <form id="bulk-import-form" method="post" action="<?= Yii::$app->urlManager->createUrl(['caterpoint/order/bulk-import']) ?>">
                            <?= Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken) ?>
                            <?= Html::hiddenInput('cache_key', $cacheKey) ?>

                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr class="table-active">
                                            <th style="width: 50px;">
                                                <input type="checkbox" id="select-all" class="form-check-input" title="Select all orders">
                                            </th>
                                            <th style="width: 50px;">#</th>
                                            <th>Order ID</th>
                                            <th>Buyer</th>
                                            <th>Items</th>
                                            <th>Delivery Date</th>
                                            <th>Source</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (empty($orders)): ?>
                                            <tr>
                                                <td colspan="7" class="text-center text-muted py-4">
                                                    <em>No orders found</em>
                                                </td>
                                            </tr>
                                        <?php endif; ?>
                                        
                                        <?php foreach ($orders as $index => $order): ?>
                                            <?php
                                            $orderId = isset($order['order']['id']) ? $order['order']['id'] : 'N/A';
                                            $firstName = isset($order['customer']['firstname']) ? $order['customer']['firstname'] : '';
                                            $lastName = isset($order['customer']['lastname']) ? $order['customer']['lastname'] : '';
                                            $email = isset($order['customer']['email']) ? $order['customer']['email'] : '';
                                            $itemCount = isset($order['items']) ? count($order['items']) : 0;
                                            $deliveryDate = isset($order['shipping_fields']['shipping_date']) ? $order['shipping_fields']['shipping_date'] : null;
                                            $orderSource = isset($order['order_source']) ? $order['order_source'] : 'caterpoint';
                                            $updatedAt = isset($order['order']['updated_at']) ? $order['order']['updated_at'] : null;
                                            $matchedItemCount = 0;
                                            foreach (isset($order['items']) ? $order['items'] : [] as $itemData) {
                                                $lookupData = isset($itemData['product_lookup']) && is_array($itemData['product_lookup'])
                                                    ? $itemData['product_lookup']
                                                    : [];
                                                if (!empty($lookupData['selectedProductId'])) {
                                                    $matchedItemCount++;
                                                }
                                            }
                                            $unmatchedItemCount = max($itemCount - $matchedItemCount, 0);
                                            ?>
                                            <tr>
                                                <td>
                                                    <?= Html::hiddenInput("order_keys[{$index}]", $orderId) ?>
                                                    <input type="checkbox" name="order_ids[]" value="<?= Html::encode($orderId) ?>" class="form-check-input order-checkbox">
                                                </td>
                                                <td><?= $index + 1 ?></td>
                                                <td>
                                                    <strong><?= Html::encode($orderId) ?></strong>
                                                    <?php if ($updatedAt): ?>
                                                        <br>
                                                        <small class="text-muted"><?= Html::encode(date('Y-m-d H:i', strtotime($updatedAt))) ?></small>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?= Html::encode(trim($firstName . ' ' . $lastName)) ?>
                                                    <?php if ($email): ?>
                                                        <br>
                                                        <small class="text-muted"><?= Html::encode($email) ?></small>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <span class="badge bg-info"><?= $itemCount ?> items</span>
                                                    <?php if ($itemCount > 0 && $unmatchedItemCount === 0): ?>
                                                        <span class="badge bg-success ms-1">All matched</span>
                                                    <?php elseif ($unmatchedItemCount > 0): ?>
                                                        <span class="badge bg-warning text-dark ms-1"><?= $unmatchedItemCount ?> need mapping</span>
                                                    <?php endif; ?>
                                                    <?php if ($itemCount > 0): ?>
                                                        <button type="button" class="btn btn-link btn-sm p-0" data-bs-toggle="modal" data-bs-target="#modal-order-<?= $index ?>">
                                                            View
                                                        </button>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?= $deliveryDate ? Html::encode($deliveryDate) : '<em class="text-muted">-</em>' ?>
                                                </td>
                                                <td>
                                                    <span class="badge bg-secondary"><?= Html::encode($orderSource) ?></span>
                                                </td>
                                            </tr>

                                            <!-- Modal for viewing order items -->
                                            <?php if ($itemCount > 0): ?>
                                                <div class="modal fade" id="modal-order-<?= $index ?>" tabindex="-1">
                                                    <div class="modal-dialog modal-xl">
                                                        <div class="modal-content">
                                                            <div class="modal-header">
                                                                <h5 class="modal-title">Order <?= Html::encode($orderId) ?> - Items</h5>
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                            </div>
                                                            <div class="modal-body">
                                                                <div class="table-responsive">
                                                                    <table class="table table-sm">
                                                                        <thead>
                                                                            <tr>
                                                                                <th>SKU</th>
                                                                                <th>Description</th>
                                                                                <th>Qty</th>
                                                                                <th>Price</th>
                                                                                <th>Match</th>
                                                                                <th>Product Mapping</th>
                                                                            </tr>
                                                                        </thead>
                                                                        <tbody>
                                                                            <?php foreach (isset($order['items']) ? $order['items'] : [] as $itemKey => $item): ?>
                                                                                <?php
                                                                                $sku = isset($item['sku']) ? $item['sku'] : 'N/A';
                                                                                $name = isset($item['name']) ? $item['name'] : 'N/A';
                                                                                $qty = isset($item['qty_ordered']) ? $item['qty_ordered'] : 0;
                                                                                $price = isset($item['row_total_incl_tax']) ? $item['row_total_incl_tax'] : '0.00';
                                                                                $lookup = isset($item['product_lookup']) && is_array($item['product_lookup'])
                                                                                    ? $item['product_lookup']
                                                                                    : [];
                                                                                $selectedProductId = isset($lookup['selectedProductId']) ? (string) $lookup['selectedProductId'] : '';
                                                                                $matchedProductLabel = isset($lookup['matchedProductLabel']) ? $lookup['matchedProductLabel'] : null;
                                                                                $matchType = isset($lookup['matchType']) ? $lookup['matchType'] : 'none';
                                                                                $matchLabel = isset($lookup['matchLabel']) ? $lookup['matchLabel'] : 'No match';
                                                                                $productOptions = isset($lookup['options']) && is_array($lookup['options']) ? $lookup['options'] : [];
                                                                                $isAllProducts = isset($lookup['allProducts']) && $lookup['allProducts'];
                                                                                $matchClass = 'bg-danger';
                                                                                if ($matchType === 'sku') {
                                                                                    $matchClass = 'bg-success';
                                                                                } elseif ($matchType === 'name') {
                                                                                    $matchClass = 'bg-warning text-dark';
                                                                                }
                                                                                $mapPlaceholder = $isAllProducts ? '— Search all products —' : 'Select product...';
                                                                                ?>
                                                                                <tr>
                                                                                    <td><code><?= Html::encode($sku) ?></code></td>
                                                                                    <td><?= Html::encode($name) ?></td>
                                                                                    <td class="text-end"><?= $qty ?></td>
                                                                                    <td class="text-end"><?= Html::encode($price) ?></td>
                                                                                    <td>
                                                                                        <span class="badge <?= $matchClass ?>"><?= Html::encode($matchLabel) ?></span>
                                                                                        <?php if ($matchedProductLabel): ?>
                                                                                            <br>
                                                                                            <small class="text-muted"><?= Html::encode($matchedProductLabel) ?></small>
                                                                                        <?php endif; ?>
                                                                                    </td>
                                                                                    <td>
                                                                                        <?= Select2::widget([
                                                                                            'name' => "product_map[{$index}][{$itemKey}]",
                                                                                            'value' => $selectedProductId !== '' ? $selectedProductId : null,
                                                                                            'data' => $productOptions,
                                                                                            'options' => [
                                                                                                'class' => 'product-map-select',
                                                                                                'placeholder' => $mapPlaceholder,
                                                                                            ],
                                                                                            'pluginOptions' => [
                                                                                                'allowClear' => true,
                                                                                                'width' => '100%',
                                                                                            ],
                                                                                        ]) ?>
                                                                                    </td>
                                                                                </tr>
                                                                            <?php endforeach; ?>
                                                                        </tbody>
                                                                    </table>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                            <div class="mt-3 d-flex gap-2 flex-wrap align-items-center">
                                <?= Html::submitButton('★ Import Selected Orders', ['class' => 'btn btn-primary', 'id' => 'submit-import', 'form' => 'bulk-import-form']) ?>
                                <?= Html::a('Clear Cache & Refresh', ['bulk-list', 'refresh' => 1], ['class' => 'btn btn-warning']) ?>
                                <?= Html::a('Back to Dashboard', ['index'], ['class' => 'btn btn-secondary']) ?>
                                <small class="text-muted ms-auto">
                                    <strong id="selected-count">0</strong> order(s) selected
                                </small>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Pagination -->
        <?php if ($nextCursor): ?>
            <div class="row mt-3">
                <div class="col-md-12">
                    <?= Html::a('Load More Orders →', ['bulk-list', 'cursor' => $nextCursor, 'limit' => $limit], ['class' => 'btn btn-outline-primary']) ?>
                </div>
            </div>
        <?php endif; ?>

        <?php Pjax::end(); ?>
    </div>
</div>

<?php
$js = <<<'JS'
$(function() {
    // Select all checkbox handler
    $('#select-all').on('change', function() {
        const checked = $(this).prop('checked');
        $('.order-checkbox').prop('checked', checked).trigger('change');
    });

    // Update selected count when any checkbox changes
    function updateSelectedCount() {
        const count = $('.order-checkbox:checked').length;
        $('#selected-count').text(count);
        $('#submit-import').prop('disabled', count === 0);
    }

    $('.order-checkbox').on('change', function() {
        updateSelectedCount();
    });

    // Initial state
    updateSelectedCount();

    // Validate and handle submission state
    $('#bulk-import-form').on('submit', function(e) {
        if ($('.order-checkbox:checked').length === 0) {
            alert('Please select at least one order to import.');
            e.preventDefault();
            return false;
        }

        $('#submit-import').prop('disabled', true).text('Processing...');
    });
});
JS;
$this->registerJs($js);
?>

<style>
.order-bulk-list {
    padding: 20px 15px;
}

.order-bulk-list .container-fluid {
    padding-left: 0;
    padding-right: 0;
}

.order-bulk-list .row {
    margin-left: 0;
    margin-right: 0;
}

.order-bulk-list .card {
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.order-bulk-list .card-body {
    padding: 1.5rem;
}

.order-bulk-list .table {
    margin-bottom: 0;
}

.order-bulk-list .table thead th {
    background-color: #f8f9fa;
    border-top: 2px solid #dee2e6;
    font-weight: 600;
    vertical-align: middle;
    padding: 0.75rem;
}

.order-bulk-list .table tbody tr {
    border-bottom: 1px solid #dee2e6;
}

.order-bulk-list .table tbody tr:hover {
    background-color: #f8f9fa;
}

.order-bulk-list .table tbody td {
    vertical-align: middle;
    padding: 0.75rem;
}

.order-bulk-list .table th:first-child,
.order-bulk-list .table td:first-child {
    text-align: center;
}

.order-bulk-list .alert {
    margin-bottom: 1.5rem;
}

.order-bulk-list .form-check-input {
    display: block;
    margin: 0 auto;
}

.order-bulk-list .product-map-select {
    min-width: 260px;
}

.order-bulk-list .modal-body small {
    display: inline-block;
    margin-top: 0.25rem;
}

#submit-import:disabled {
    opacity: 0.65;
    cursor: not-allowed;
}

.gap-2 {
    gap: 0.5rem !important;
}
</style>
