<?php

use yii\grid\ActionColumn;
use common\widgets\GridView;
use yii\helpers\Html;
use yii\helpers\Url;

/** @var yii\data\ArrayDataProvider $dataProvider */
/** @var int $totalCount */
/** @var int $paymentCount */
/** @var bool $isCached */
/** @var array<int, string> $importedOrderNumbers */

?>
<div class="card">
  <div class="card-header">Magento Orders</div>
  <div class="card-body">
        <p>Orders are downloaded from Magento and cached before being paginated locally.</p>
        <p>Total Magento orders available: <?= Html::encode((string) $totalCount) ?></p>
        <?php if ($isCached) : ?>
            <p>Showing cached data. Append <code>?refresh=1</code> to refresh from Magento.</p>
        <?php endif; ?>
    <div class="btn-group" role="group" aria-label="Magento order actions">
      <?= Html::a('Download Orders', ['download-orders'], [
          'class' => 'btn btn-outline-secondary',
          'data-method' => 'post',
      ]) ?>
      <?= Html::a('Import Orders', ['import-orders'], [
          'class' => 'btn btn-primary',
          'data-method' => 'post',
      ]) ?>
      <?= Html::a('Download Payments', ['download-payments'], [
          'class' => 'btn btn-outline-secondary',
          'data-method' => 'post',
      ]) ?>
      <?= Html::a('Import Payments', ['import-payments'], [
          'class' => 'btn btn-success',
          'data-method' => 'post',
      ]) ?>
    </div>
  </div>

  <?= GridView::widget([
      'dataProvider' => $dataProvider,
      'tableOptions' => ['class' => 'table table-striped table-bordered table-hover'],
      'emptyText' => 'No Magento orders were returned from the API.',
      'summary' => 'Showing {begin}-{end} of {totalCount} Magento orders.',
        'rowOptions' => static function (array $model) use ($importedOrderNumbers): array {
            Yii::warning($model, 'magento');
            $orderNo = (int) ($model['increment_id'] ?? '');
            if (!in_array($orderNo, $importedOrderNumbers)) {
                return [];
            }
            return [
              'class' => 'table-success',
              'title' => 'Already imported',
          ];
      },
      'columns' => [
          [
              'label' => 'ID',
              'value' => static function (array $model): string {
                  return (string) ($model['entity_id'] ?? '');
              },
              'headerOptions' => ['style' => 'width: 90px;'],
          ],
          [
              'label' => 'Order #',
              'value' => static function (array $model): string {
                  return (string) ($model['increment_id'] ?? '');
              },
          ],
          [
              'label' => 'NGauge Order ID #',
              'value' => static function (array $model): string {
                  return (string) ($model['extension_attributes']['ngauge_order_id'] ?? '');
              },
          ],
          [
              'label' => 'Order Total',
              'value' => static function (array $model): string {
                  $currency = (string) ($model['base_currency_code'] ?? $model['order_currency_code'] ?? '');
                  $amount = (float) ($model['base_grand_total'] ?? $model['grand_total'] ?? 0);

                  return trim($currency . ' ' . number_format($amount, 2));
              },
              'headerOptions' => ['style' => 'width: 140px;'],
          ],
          [
              'label' => 'Amount Paid',
              'value' => static function (array $model): string {
                  $currency = (string) ($model['base_currency_code'] ?? $model['order_currency_code'] ?? '');
                  $amount = (float) ($model['base_total_paid'] ?? $model['total_paid'] ?? 0);

                  return trim($currency . ' ' . number_format($amount, 2));
              },
              'headerOptions' => ['style' => 'width: 140px;'],
          ],
          [
              'label' => 'Status',
              'value' => static function (array $model): string {
                  return (string) ($model['status'] ?? '');
              },
              'headerOptions' => ['style' => 'width: 130px;'],
          ],
          [
              'label' => 'Customer',
              'value' => static function (array $model): string {
                  $billing = $model['billing_address'] ?? [];
                  $customer = $model['customer'] ?? [];
                  $name = trim((string) (($customer['firstname'] ?? '') . ' ' . ($customer['lastname'] ?? '')));

                if ($name === '') {
                    $name = trim((string) (($billing['firstname'] ?? '') . ' ' . ($billing['lastname'] ?? '')));
                }

                  return $name;
              },
          ],
          [
              'label' => 'Email',
              'value' => static function (array $model): string {
                  $customer = $model['customer'] ?? [];
                  $billing = $model['billing_address'] ?? [];

                  return (string) ($customer['email'] ?? $billing['email'] ?? '');
              },
          ],
          [
              'label' => 'Telephone',
              'value' => static function (array $model): string {
                  $billing = $model['billing_address'] ?? [];
                  $shipping = $model['shipping_address'] ?? [];

                  return (string) ($billing['telephone'] ?? $shipping['telephone'] ?? '');
              },
              'headerOptions' => ['style' => 'width: 160px;'],
          ],
          [
              'label' => 'Date',
              'value' => static function (array $model): string {
                  $date = (string) ($model['created_at'] ?? $model['updated_at'] ?? '');
                  return $date !== '' ? date('Y-m-d H:i', strtotime($date)) : '';
              },
              'headerOptions' => ['style' => 'width: 160px;'],
          ],
              [
                  'class' => ActionColumn::class,
                  'template' => '{download} {import}',
                  'header' => 'Actions',
                  'headerOptions' => ['style' => 'width: 140px;'],
                  'buttons' => [
                      'download' => static function (string $url, array $model, $key): string {
                          return Html::a('Download', $url, [
                              'class' => 'btn btn-sm btn-outline-secondary',
                              'data-pjax' => '0',
                          ]);
                      },
                      'import' => static function (string $url, array $model, $key): string {
                          return Html::a('Import', $url, [
                              'class' => 'btn btn-sm btn-primary',
                              'data-method' => 'post',
                              'data-pjax' => '0',
                              'style' => 'margin-left:4px;',
                          ]);
                      },
                  ],
                  'urlCreator' => static function (string $action, array $model, $key, int $index, ActionColumn $column) {
                      $id = (int) ($model['entity_id'] ?? 0);

                      return match ($action) {
                          'download' => Url::to(['download-order', 'id' => $id]),
                          'import' => Url::to(['import-order', 'id' => $id]),
                          default => Url::to(['orders']),
                      };
                  },
                  'visibleButtons' => [
                      'download' => static function (array $model, $key, int $index): bool {
                          return (int) ($model['entity_id'] ?? 0) > 0;
                      },
                      'import' => static function (array $model, $key, int $index): bool {
                          return (int) ($model['entity_id'] ?? 0) > 0;
                      },
                  ],
              ],
      ],
  ]) ?>
</div>
