<?
global $db;

ob_start();

  if ( $this -> operation['id'] )
    $date = $this -> operation['date'];
  elseif ( $this -> operation_date )
    $date = $this -> operation_date;
  else
    $date = date( 'Y-m-d' );

  echo \Html::input( [
                'label'   => 'Data',
                'name'    => 'date',
                'value'   => $date ? $date : date( 'Y-m-d' ),
                'class' => 'datetime require',
                'inline'  => true
              ] );
  echo \Html::input( [
                'label' => 'Kwota',
                'name' => 'amount',
                'value' => $this -> operation['amount'],
                'class' => 'price require',
                'inline' => true
              ] );
  echo \Html::input( [
                'label' => 'Opis',
                'name' => 'description',
                'value' => $this -> operation['description'],
                'inline' => true
              ] );

  $clients_values = [ '' => '--- brak ---' ];
  if ( is_array( $this -> clients ) ) foreach ( $this -> clients as $client )
    $clients_values[ $client['id'] ] = $client['firm'];

  echo \Html::select( [
                'label' => 'Klient',
                'name' => 'client_id',
                'id' => 'client_id',
                'values' => $clients_values,
                'value' => $this -> operation['client_id'],
              ] );

  foreach ( $this -> operation['tags'] as $tag )
  {
    $tags_value .= $tag['tag'];

    if ( $tag != end( $this -> operation['tags'] ) )
      $tags_value .= ',';
  }

  echo \Html::input( [
                'label' => 'Tagi',
                'name' => 'tags',
                'id' => 'tags',
                'value' => $tags_value,
                'inline' => true
              ] );

  $fakturowniaOperationContext = $this -> fakturownia_operation_context;
  if ( ( !is_array( $fakturowniaOperationContext ) || empty( $fakturowniaOperationContext ) ) && !empty( $this -> operation['id'] ) )
  {
    $financeRepository = new \Domain\Finances\FinanceRepository();
    $fakturowniaOperationContext = $financeRepository -> fakturowniaOperationContext( (int)$this -> operation['id'] );
  }

  if ( is_array( $fakturowniaOperationContext ) && !empty( $fakturowniaOperationContext ) )
  {
    $currentCategoryId = (int)( $fakturowniaOperationContext['finance_category_id'] ?? 0 );
    ?>
    <div class="alert alert-info" style="margin-top: 20px;">
      <strong>Edycja dopasowania Fakturownia</strong><br>
      Pozycja: <?= htmlspecialchars( (string)$fakturowniaOperationContext['external_name'] ); ?>
    </div>
    <div class="form-inline" style="margin-bottom: 20px;">
      <div class="form-group" style="margin-right: 10px;">
        <label style="margin-right: 8px;">Nowa kategoria:</label>
        <select id="fakturownia-finance-category-id" class="form-control" required>
          <option value="">-- wybierz --</option>
          <? foreach ( $this -> fakturownia_categories as $category ): ?>
            <option value="<?= (int)$category['id']; ?>" <?= (int)$category['id'] === $currentCategoryId ? 'selected' : ''; ?>>
              <?= htmlspecialchars( (string)$category['name'] ); ?>
            </option>
          <? endforeach; ?>
        </select>
      </div>

      <label class="checkbox-inline" style="margin-right: 10px;">
        <input type="checkbox" id="fakturownia-apply-to-all" value="1"> Przepnij wszystkie pasujace operacje z Fakturowni
      </label>

      <button
        type="button"
        class="btn btn-warning"
        id="fakturownia-mapping-save"
        data-operation-id="<?= (int)$this -> operation['id']; ?>"
        data-return-category-id="<?= (int)$this -> category_id; ?>"
        data-csrf-token="<?= \S::csrf_token(); ?>"
      >Zmien dopasowanie</button>
    </div>
    <?
  }

$out = ob_get_clean();

$grid = new \gridEdit;
$grid -> id               = 'operation-edit';
$grid -> gdb_opt          = $gdb;
$grid -> include_plugins  = true;
$grid -> title            = 'edycja <strong>operacji</strong>';
$grid -> title_small      = 'Zarządzaj parametrami operacji';
$grid -> fields           = [
                              [
                                'db' => 'id',
                                'type' => 'hidden',
                                'value' => $this -> operation['id']
                              ], [
                                'db' => 'category_id',
                                'type' => 'hidden',
                                'value' => $this -> operation['id'] ? $this -> operation['category_id'] : \S::get( 'category-id' )
                              ]
                            ];
$grid -> external_code    = $out;

if ( \S::get( 'return' ) == 'category' or $this -> operation['id'] )
  $return_url = '/finances/operations_list/category-id=' . $this -> category_id;
else
  $return_url = '/finances/main_view/';

$grid -> actions          = [
                              'save' => [ 'url' => '/finances/operation_save/', 'back_url' => $return_url ],
                              'cancel' => [ 'url' => $return_url ]
                            ];
$grid -> persist_edit     = true;
$grid -> id_param         = 'id';
echo $grid -> draw();
?>
<link rel="stylesheet" type="text/css" href="/libraries/tagsinput/bootstrap-tagsinput.css">
<link rel="stylesheet" type="text/css" href="/libraries/tagsinput/app.css">
<script type="text/javascript" src="/libraries/typeahead.bundle.js"></script>
<script type="text/javascript" src="/libraries/tagsinput/bootstrap-tagsinput.min.js"></script>
<script type="text/javascript">
  $( function() {
    var tags_list = [ <? foreach ( $this -> tags_json as $tag ): echo '"' . $tag . '"'; if ( $tag != end( $this -> tags_json ) ) echo','; endforeach;?> ];

    var tags_data = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      local: $.map( tags_list, function(item) {
        return {
          name: item
        };
      })
    });

    tags_data.initialize();

    $( '#tags' ).tagsinput({
      typeaheadjs: {
        name: 'tags',
        displayKey: 'name',
        valueKey: 'name',
        source: tags_data.ttAdapter()
      }
    });

    $( '#fakturownia-mapping-save' ).on( 'click', function() {
      var categoryId = $( '#fakturownia-finance-category-id' ).val();
      if ( !categoryId ) {
        alert( 'Wybierz nowa kategorie.' );
        return false;
      }

      var form = $( '<form>', {
        method: 'post',
        action: '/finances/fakturownia_operation_mapping_save/'
      } );

      form.append( $( '<input>', { type: 'hidden', name: 'csrf_token', value: $( this ).data( 'csrf-token' ) } ) );
      form.append( $( '<input>', { type: 'hidden', name: 'operation_id', value: $( this ).data( 'operation-id' ) } ) );
      form.append( $( '<input>', { type: 'hidden', name: 'return_category_id', value: $( this ).data( 'return-category-id' ) } ) );
      form.append( $( '<input>', { type: 'hidden', name: 'finance_category_id', value: categoryId } ) );
      form.append( $( '<input>', { type: 'hidden', name: 'apply_to_all', value: $( '#fakturownia-apply-to-all' ).is( ':checked' ) ? 1 : 0 } ) );

      $( 'body' ).append( form );
      form.submit();
      return false;
    } );
  });
</script>
