<?php
$esc = function( $value )
{
  return htmlspecialchars( (string)$value, ENT_QUOTES, 'UTF-8' );
};
?>
<style>
  .fakturownia-panel {
    border-radius: 6px;
    overflow: hidden;
  }
  .fakturownia-panel .panel-heading {
    padding: 12px 14px;
  }
  .fakturownia-panel .panel-title {
    margin: 0;
    line-height: 1.3;
  }
  .fakturownia-panel .panel-body {
    padding-bottom: 10px;
  }
  .fakturownia-panel .panel-body > :last-child {
    margin-bottom: 0;
  }
  .fakturownia-panel .select2-container {
    min-width: 320px !important;
  }
</style>
<div class="panel panel-default fakturownia-panel">
  <div class="panel-heading">
    <h4 class="panel-title">Import faktur z Fakturowni</h4>
  </div>
  <div class="panel-body">
    <? if ( is_array( $this -> fakturownia_last_summary ) && isset( $this -> fakturownia_last_summary['summary'] ) ): ?>
      <div class="alert alert-info mb15">
        Ostatni import: <?= $esc( $this -> fakturownia_last_summary['at'] ?? '-' ); ?><br>
        Zaimportowano: <strong><?= (int)( $this -> fakturownia_last_summary['summary']['imported'] ?? 0 ); ?></strong>,
        pominieto: <strong><?= (int)( $this -> fakturownia_last_summary['summary']['skipped'] ?? 0 ); ?></strong>,
        brak mapowan: <strong><?= (int)( $this -> fakturownia_last_summary['summary']['unmapped'] ?? 0 ); ?></strong>,
        bledy: <strong><?= (int)( $this -> fakturownia_last_summary['summary']['errors'] ?? 0 ); ?></strong>
      </div>
    <? endif; ?>

    <? if ( is_array( $this -> fakturownia_pending_clients ) && count( $this -> fakturownia_pending_clients ) ): ?>
      <h5>Brakujace mapowania klientow</h5>
      <table class="table table-sm table-bordered">
        <thead>
          <tr>
            <th>Klient z Fakturowni</th>
            <th>CRM klient</th>
            <th style="width: 130px;">Akcja</th>
          </tr>
        </thead>
        <tbody>
          <? foreach ( $this -> fakturownia_pending_clients as $row ): ?>
            <tr>
              <td>
                <?= $esc( $row['external_name'] ); ?><br>
                <? $payload = is_array( $row['payload'] ?? null ) ? $row['payload'] : []; ?>
                <? if ( !empty( $payload['tax_no'] ) ): ?>
                  <small class="text-muted">NIP: <?= $esc( $payload['tax_no'] ); ?></small><br>
                <? endif; ?>
                <? if ( !empty( $payload['document_number'] ) ): ?>
                  <small class="text-muted">Ostatnia faktura: <?= $esc( $payload['document_number'] ); ?></small><br>
                <? endif; ?>
                <? if ( !empty( $payload['positions'] ) && is_array( $payload['positions'] ) ): ?>
                  <? $positions = $payload['positions']; ?>
                  <? $shown = array_slice( $positions, 0, 10 ); ?>
                  <small class="text-muted">
                    Pozycje z faktury:
                    <ul style="margin:2px 0 4px 18px; padding:0;">
                      <? foreach ( $shown as $positionName ): ?>
                        <li><?= $esc( $positionName ); ?></li>
                      <? endforeach; ?>
                      <? if ( count( $positions ) > count( $shown ) ): ?>
                        <li>... i <?= count( $positions ) - count( $shown ); ?> wiecej</li>
                      <? endif; ?>
                    </ul>
                  </small>
                <? endif; ?>
                <small class="text-muted">Klucz: <?= $esc( $row['external_key'] ); ?> | wystapienia: <?= (int)$row['hits']; ?></small>
              </td>
              <td>
                <form method="post" action="/finances/fakturownia_client_mapping_save/" class="form-inline">
                  <input type="hidden" name="csrf_token" value="<?= \S::csrf_token(); ?>">
                  <input type="hidden" name="external_key" value="<?= $esc( $row['external_key'] ); ?>">
                  <input type="hidden" name="external_name" value="<?= $esc( $row['external_name'] ); ?>">
                  <select name="crm_client_id" class="form-control input-sm js-fakturownia-client-select" required>
                    <option value="">Wybierz klienta</option>
                    <? foreach ( $this -> fakturownia_crm_clients as $client ): ?>
                      <option value="<?= (int)$client['id']; ?>"><?= $esc( $client['firm'] ); ?></option>
                    <? endforeach; ?>
                  </select>
              </td>
              <td>
                  <button type="submit" class="btn btn-success btn-sm">Zapisz</button>
                </form>
              </td>
            </tr>
          <? endforeach; ?>
        </tbody>
      </table>
    <? endif; ?>

    <? if ( is_array( $this -> fakturownia_pending_items ) && count( $this -> fakturownia_pending_items ) ): ?>
      <h5 class="mt20">Brakujace mapowania produktow/uslug</h5>
      <table class="table table-sm table-bordered">
        <thead>
          <tr>
            <th>Pozycja z faktury</th>
            <th>Kategoria finansowa (mapuje globalnie)</th>
            <th style="width: 200px;">Akcja</th>
          </tr>
        </thead>
        <tbody>
          <? $renderedRows = 0; ?>
          <? foreach ( $this -> fakturownia_pending_items as $itemIdx => $row ): ?>
            <? $payload = is_array( $row['payload'] ?? null ) ? $row['payload'] : []; ?>
            <? $occurrences = ( isset( $payload['occurrences'] ) && is_array( $payload['occurrences'] ) ) ? $payload['occurrences'] : []; ?>
            <? if ( empty( $occurrences ) ) continue; ?>
            <? $saveFormId = 'fi-save-' . $itemIdx; ?>
            <? $occCount = count( $occurrences ); ?>
            <? foreach ( $occurrences as $occIdx => $occ ): ?>
              <? $isFirst = $occIdx === 0; ?>
              <tr>
                <td>
                  <?= $esc( $row['external_name'] ); ?><br>
                  <? if ( !empty( $occ['document_number'] ) ): ?>
                    <small class="text-muted">Faktura: <?= $esc( $occ['document_number'] ); ?> (ID <?= $esc( $occ['document_id'] ?? '' ); ?>)</small><br>
                  <? endif; ?>
                  <? if ( !empty( $occ['buyer_name'] ) || !empty( $occ['seller_name'] ) ): ?>
                    <small class="text-muted">
                      Nabywca: <?= $esc( $occ['buyer_name'] ?? '-' ); ?> |
                      Sprzedawca: <?= $esc( $occ['seller_name'] ?? '-' ); ?>
                    </small><br>
                  <? endif; ?>
                  <? if ( $isFirst ): ?>
                    <small class="text-muted">Klucz: <?= $esc( $row['external_key'] ); ?> | wystapien w kolejce: <?= $occCount; ?></small>
                  <? endif; ?>
                </td>
                <? if ( $isFirst ): ?>
                  <td rowspan="<?= $occCount; ?>" style="vertical-align: top;">
                    <select name="finance_category_id" form="<?= $saveFormId; ?>" class="form-control input-sm" required>
                      <option value="">Wybierz kategorie</option>
                      <? foreach ( $this -> fakturownia_categories as $category ): ?>
                        <option value="<?= (int)$category['id']; ?>">
                          <?= $esc( $category['name'] ); ?> (grupa: <?= (int)$category['group_id']; ?>)
                        </option>
                      <? endforeach; ?>
                    </select>
                    <form id="<?= $saveFormId; ?>" method="post" action="/finances/fakturownia_item_mapping_save/" style="display:inline;">
                      <input type="hidden" name="csrf_token" value="<?= \S::csrf_token(); ?>">
                      <input type="hidden" name="external_key" value="<?= $esc( $row['external_key'] ); ?>">
                      <input type="hidden" name="external_name" value="<?= $esc( $row['external_name'] ); ?>">
                      <button type="submit" class="btn btn-success btn-sm mt5">Zapisz mapowanie</button>
                    </form>
                    <? if ( $occCount > 1 ): ?>
                      <br><small class="text-muted">Zapis mapowania kategorii rozwiazuje wszystkie <?= $occCount; ?> wystapien tej pozycji.</small>
                    <? endif; ?>
                  </td>
                <? endif; ?>
                <td style="white-space:nowrap;">
                  <form method="post" action="/finances/fakturownia_document_position_skip/" style="display:inline-block; margin:0;">
                    <input type="hidden" name="csrf_token" value="<?= \S::csrf_token(); ?>">
                    <input type="hidden" name="external_id" value="<?= $esc( $occ['document_id'] ?? '' ); ?>">
                    <input type="hidden" name="document_type" value="<?= $esc( $occ['document_type'] ?? '' ); ?>">
                    <input type="hidden" name="external_item_key" value="<?= $esc( $row['external_key'] ); ?>">
                    <input type="hidden" name="item_name" value="<?= $esc( $row['external_name'] ); ?>">
                    <button type="submit" class="btn btn-warning btn-sm" title="Pomijaj te pozycje tylko na tej fakturze">Pomijaj na tej fakturze</button>
                  </form>
                </td>
              </tr>
              <? $renderedRows++; ?>
            <? endforeach; ?>
          <? endforeach; ?>
          <? if ( $renderedRows === 0 ): ?>
            <tr><td colspan="3"><em>(brak wystapien do rozwiazania)</em></td></tr>
          <? endif; ?>
        </tbody>
      </table>
    <? endif; ?>
  </div>
</div>
<script type="text/javascript">
  (function() {
    if ( typeof jQuery === 'undefined' || !jQuery.fn.select2 )
      return;

    var selects = jQuery( '.js-fakturownia-client-select' );
    if ( !selects.length )
      return;

    selects.select2({
      theme: 'bootstrap-5',
      width: '100%',
      placeholder: 'Wyszukaj klienta CRM'
    });

    selects.on( 'select2:open', function() {
      setTimeout( function() {
        var searchField = document.querySelector( '.select2-container--open .select2-search__field' );
        if ( searchField )
          searchField.focus();
      }, 0 );
    } );
  })();
</script>
