<?php
declare(strict_types=1);

$filters = is_array($filters ?? null) ? $filters : [];
$channelOptions = is_array($channelOptions ?? null) ? $channelOptions : [];
$statusGroupOptions = is_array($statusGroupOptions ?? null) ? $statusGroupOptions : [];
$table = is_array($table ?? null) ? $table : [];

$selectedChannels = is_array($filters['selected_channels'] ?? null) ? $filters['selected_channels'] : [];
$selectedStatusGroups = is_array($filters['selected_status_groups'] ?? null) ? $filters['selected_status_groups'] : [];

$rows = is_array($table['rows'] ?? null) ? $table['rows'] : [];
$totals = is_array($table['totals'] ?? null) ? $table['totals'] : ['channels' => []];
$hasData = (bool) ($table['hasData'] ?? false);
$debugEnabled = (bool) ($debugEnabled ?? false);
$diagnostics = is_array($diagnostics ?? null) ? $diagnostics : [];
$debugMeta = is_array($debugMeta ?? null) ? $debugMeta : [];

$channelMap = [];
foreach ($channelOptions as $channelOption) {
    $key = (string) ($channelOption['key'] ?? '');
    if ($key === '') {
        continue;
    }
    $channelMap[$key] = (string) ($channelOption['label'] ?? $key);
}
?>

<section class="card statistics-orders-page">
  <div class="statistics-orders-head">
    <div>
      <h2 class="section-title"><?= $e($t('statistics.orders.title')) ?></h2>
      <p class="muted mt-12"><?= $e($t('statistics.orders.description')) ?></p>
    </div>
  </div>

  <form method="get" action="/statistics/orders" class="statistics-orders-filters mt-16">
    <label class="form-field">
      <span class="field-label"><?= $e($t('statistics.orders.filters.date_from')) ?></span>
      <input class="form-control" type="date" name="date_from" value="<?= $e((string) ($filters['date_from'] ?? '')) ?>">
    </label>

    <label class="form-field">
      <span class="field-label"><?= $e($t('statistics.orders.filters.date_to')) ?></span>
      <input class="form-control" type="date" name="date_to" value="<?= $e((string) ($filters['date_to'] ?? '')) ?>">
    </label>

    <label class="form-field">
      <span class="field-label"><?= $e($t('statistics.orders.filters.channels')) ?></span>
      <select class="form-control statistics-orders-multiselect js-checkbox-multiselect"
        name="channels[]"
        multiple
        size="6"
        data-checkbox-multiselect
        data-all-label="Wszystkie"
        data-empty-label="Nic nie wybrano"
        data-selected-label-singular="zaznaczono"
        data-selected-label-plural="zaznaczono">
        <?php foreach ($channelOptions as $channelOption): ?>
          <?php
          $key = (string) ($channelOption['key'] ?? '');
          $label = (string) ($channelOption['label'] ?? $key);
          if ($key === '') {
              continue;
          }
          ?>
          <option value="<?= $e($key) ?>"<?= in_array($key, $selectedChannels, true) ? ' selected' : '' ?>>
            <?= $e($label) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </label>

    <label class="form-field">
      <span class="field-label"><?= $e($t('statistics.orders.filters.status_groups')) ?></span>
      <select class="form-control statistics-orders-multiselect js-checkbox-multiselect"
        name="status_groups[]"
        multiple
        size="6"
        data-checkbox-multiselect
        data-all-label="Wszystkie"
        data-empty-label="Nic nie wybrano"
        data-selected-label-singular="zaznaczono"
        data-selected-label-plural="zaznaczono">
        <?php foreach ($statusGroupOptions as $groupOption): ?>
          <?php
          $groupId = (int) ($groupOption['id'] ?? 0);
          $groupName = (string) ($groupOption['name'] ?? '');
          if ($groupId <= 0) {
              continue;
          }
          ?>
          <option value="<?= $e((string) $groupId) ?>"<?= in_array($groupId, $selectedStatusGroups, true) ? ' selected' : '' ?>>
            <?= $e($groupName) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </label>

    <div class="form-field statistics-orders-filters__actions">
      <span class="field-label">&nbsp;</span>
      <div class="filters-actions">
        <button type="submit" class="btn btn--primary"><?= $e($t('statistics.orders.actions.apply_filters')) ?></button>
        <a href="/statistics/orders" class="btn btn--secondary"><?= $e($t('statistics.orders.actions.reset_filters')) ?></a>
      </div>
    </div>
  </form>
</section>

<section class="card mt-16 statistics-orders-table-wrap">
  <?php if ($debugEnabled): ?>
    <?php
      ob_start();
    ?>
      <strong>DEBUG</strong>
      <pre style="margin:8px 0 0;white-space:pre-wrap;"><?= $e(json_encode([
        'filters' => $debugMeta,
        'diagnostics' => $diagnostics,
      ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) ?></pre>
    <?php
      $statisticsDebugHtml = ob_get_clean();
    ?>
    <?php $type='warning'; $messageHtml=$statisticsDebugHtml; $dismissible=true; include dirname(__DIR__) . '/components/alert.php'; unset($messageHtml); ?>
  <?php endif; ?>

  <?php if (!$hasData): ?>
    <p class="muted"><?= $e($t('statistics.orders.empty')) ?></p>
  <?php else: ?>
    <div class="table-wrap">
      <table class="table statistics-orders-table">
        <thead>
        <tr>
          <th rowspan="2"><?= $e($t('statistics.orders.columns.day')) ?></th>
          <?php foreach ($selectedChannels as $channelKey): ?>
            <th colspan="3"><?= $e($channelMap[$channelKey] ?? $channelKey) ?></th>
          <?php endforeach; ?>
          <th colspan="3"><?= $e($t('statistics.orders.columns.total')) ?></th>
        </tr>
        <tr>
          <?php foreach ($selectedChannels as $channelKey): ?>
            <th><?= $e($t('statistics.orders.columns.orders_count')) ?></th>
            <th><?= $e($t('statistics.orders.columns.total_net')) ?></th>
            <th><?= $e($t('statistics.orders.columns.total_gross')) ?></th>
          <?php endforeach; ?>
          <th><?= $e($t('statistics.orders.columns.orders_count')) ?></th>
          <th><?= $e($t('statistics.orders.columns.total_net')) ?></th>
          <th><?= $e($t('statistics.orders.columns.total_gross')) ?></th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($rows as $row): ?>
          <tr>
            <td><?= $e((string) ($row['day'] ?? '')) ?></td>
            <?php foreach ($selectedChannels as $channelKey): ?>
              <?php $channelStats = is_array($row['channels'][$channelKey] ?? null) ? $row['channels'][$channelKey] : []; ?>
              <td><?= $e((string) ((int) ($channelStats['orders_count'] ?? 0))) ?></td>
              <td><?= $e(number_format((float) ($channelStats['total_net'] ?? 0), 2, '.', ' ')) ?></td>
              <td><?= $e(number_format((float) ($channelStats['total_gross'] ?? 0), 2, '.', ' ')) ?></td>
            <?php endforeach; ?>
            <td><?= $e((string) ((int) ($row['day_total_orders'] ?? 0))) ?></td>
            <td><?= $e(number_format((float) ($row['day_total_net'] ?? 0), 2, '.', ' ')) ?></td>
            <td><?= $e(number_format((float) ($row['day_total_gross'] ?? 0), 2, '.', ' ')) ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
        <tfoot>
        <tr>
          <th><?= $e($t('statistics.orders.columns.summary')) ?></th>
          <?php foreach ($selectedChannels as $channelKey): ?>
            <?php $channelTotals = is_array($totals['channels'][$channelKey] ?? null) ? $totals['channels'][$channelKey] : []; ?>
            <th><?= $e((string) ((int) ($channelTotals['orders_count'] ?? 0))) ?></th>
            <th><?= $e(number_format((float) ($channelTotals['total_net'] ?? 0), 2, '.', ' ')) ?></th>
            <th><?= $e(number_format((float) ($channelTotals['total_gross'] ?? 0), 2, '.', ' ')) ?></th>
          <?php endforeach; ?>
          <th><?= $e((string) ((int) ($totals['orders_count'] ?? 0))) ?></th>
          <th><?= $e(number_format((float) ($totals['total_net'] ?? 0), 2, '.', ' ')) ?></th>
          <th><?= $e(number_format((float) ($totals['total_gross'] ?? 0), 2, '.', ' ')) ?></th>
        </tr>
        </tfoot>
      </table>
    </div>
  <?php endif; ?>
</section>
