<?php
ob_start();
session_start();
require_once __DIR__ . '/../_init.php';

// Redirecciones estándar
if (!is_loggedin()) {
  redirect(root_url() . '/index.php?redirect_to=' . url());
}
if (user_group_id() != 1 && !has_permission('access', 'transfer')) {
  redirect(root_url() . '/' . ADMINDIRNAME . '/dashboard.php');
}

// Cargar cuentas
$accounts = [];
$st = db()->query("SELECT id, account_name FROM bank_accounts ORDER BY account_name ASC");
$accounts = $st->fetchAll(PDO::FETCH_ASSOC);

// URL a la API
$API_URL = rtrim(root_url(), '/') . '/' . ADMINDIRNAME . '/cheque_transfer_api.php';

include __DIR__ . '/header.php';
include __DIR__ . '/left_sidebar.php';
?>
<div class="content-wrapper">
  <section class="content-header">
    <h1>Transferir Cheques entre Cuentas <small><?php echo store('name'); ?></small></h1>
    <ol class="breadcrumb">
      <li><a href="dashboard.php"><i class="fa fa-dashboard"></i> <?php echo trans('text_dashboard'); ?></a></li>
      <li class="active">Transferir Cheques</li>
    </ol>
  </section>

  <section class="content">
    <div class="box box-primary">
      <div class="box-header with-border">
        <h3 class="box-title">Seleccionar cuentas</h3>
      </div>
      <div class="box-body">

        <div class="row">
          <div class="col-sm-6">
            <div class="form-group">
              <label>Desde (cuenta origen)</label>
              <select id="from_account" class="form-control">
                <option value="">-- Elegir --</option>
                <?php foreach ($accounts as $acc):
                  $id = (int)$acc['id'];
                  // nunca mostrar estas cuentas
                  if (in_array($id, [1, 10, 11, 5, 15, 7, 12], true)) continue; ?>
                  <option value="<?php echo (int)$acc['id'];?>">
                    <?php echo htmlspecialchars($acc['account_name']);?>
                  </option>
                <?php endforeach;?>
              </select>
            </div>
          </div>
          <div class="col-sm-6">
            <div class="form-group">
              <label>Hacia (cuenta destino)</label>
              <select id="to_account" class="form-control">
                <option value="">-- Elegir --</option>
                <?php foreach ($accounts as $acc):
                  $id = (int)$acc['id'];
                  // nunca mostrar estas cuentas
                  if (in_array($id, [1, 10, 11, 5, 15, 7, 12], true)) continue; ?>
                  <option value="<?php echo (int)$acc['id'];?>">
                    <?php echo htmlspecialchars($acc['account_name']);?>
                  </option>
                <?php endforeach;?>
              </select>
            </div>
          </div>
        </div>

        <hr>

        <div id="panel-cheques" style="display:none;">
          <div class="well well-sm">
            <strong>Cuenta origen:</strong> <span id="lbl-origen"></span><br>
            <strong>Total seleccionado:</strong> <span id="lbl-total">$ 0,00</span>
            <button class="btn btn-xs btn-default pull-right" id="btn-usar-total">Usar total</button>
            <div class="clearfix"></div>
          </div>

          <div class="table-responsive" style="max-height:360px; overflow:auto;">
            <table class="table table-bordered table-striped table-condensed" id="tbl-cheques">
              <thead>
                <tr>
                  <th style="width:32px;"><input type="checkbox" id="chk-all"></th>
                  <th>N°</th>
                  <th>Fecha</th>
                  <th>Fecha pago</th>
                  <th>Banco</th>
                  <th>CUIT</th>
                  <th class="text-right">Importe</th>
                  <th>Obs.</th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>

          <div class="text-right">
            <button id="btn-transferir" class="btn btn-primary" disabled>
              <i class="fa fa-exchange"></i> Transferir seleccionados
            </button>
          </div>
        </div>

        <div id="alerta" style="display:none;" class="alert"></div>

      </div>
    </div>
  </section>
</div>

<script>
(function() {
  var API = <?php echo json_encode($API_URL);?>;
  var $from = $('#from_account');
  var $to   = $('#to_account');
  var $panel = $('#panel-cheques');
  var $tbody = $('#tbl-cheques tbody');
  var $chkAll = $('#chk-all');
  var $lblOrigen = $('#lbl-origen');
  var $lblTotal = $('#lbl-total');
  var $btnUsarTotal = $('#btn-usar-total');
  var $btnTransfer = $('#btn-transferir');
  var $alerta = $('#alerta');

  function formatCurrency(n) {
    n = isNaN(n) ? 0 : n;
    try {
      return '$ ' + n.toLocaleString('es-AR', {minimumFractionDigits:2, maximumFractionDigits:2});
    } catch(e) {
      return '$ ' + (Math.round(n * 100)/100).toFixed(2);
    }
  }

  function recompute() {
    var sum = 0;
    $tbody.find('input.chk:checked').each(function() {
      var v = parseFloat($(this).data('importe')) || 0;
      sum += v;
    });
    $lblTotal.text(formatCurrency(sum));
    $btnTransfer.prop('disabled', $tbody.find('input.chk:checked').length === 0 || !$to.val());
  }

  function mensaje(tipo, html) {
    $alerta.removeClass('alert-success alert-danger').addClass('alert-' + tipo).html(html).show();
    setTimeout(function(){ $alerta.fadeOut(); }, 4000);
  }

  function cargarCheques() {
    var id = $from.val();
    if (!id) {
      $panel.hide();
      $tbody.empty();
      $chkAll.prop('checked', false);
      $lblTotal.text(formatCurrency(0));
      return;
    }
    var text = $from.find('option:selected').text();
    $lblOrigen.text(text);
    $tbody.html('<tr><td colspan="8" class="text-center text-muted">Cargando…</td></tr>');
    $.getJSON(API, { action: 'list', from_account_id: id })
      .done(function(resp){
        if (!resp || resp.ok === false) {
          $tbody.html('<tr><td colspan="8" class="text-center text-danger">' + (resp && resp.error ? resp.error : 'Error al cargar.') + '</td></tr>');
          $panel.show();
          return;
        }
        var rows = (resp.items || []).map(function(ch){
          var imp = ch.importe || '0';
          // parse lado cliente para totalizar
          var tmp = (''+imp).replace(/[^\d,.\-]/g,'');
          if (tmp.indexOf(',')>-1 && tmp.indexOf('.')>-1) { tmp = tmp.replace(/\./g,'').replace(',', '.'); }
          else if (tmp.indexOf(',')>-1) { tmp = tmp.replace(',', '.'); }
          var num = parseFloat(tmp) || 0;
          return [
            '<tr>',
              '<td><input type="checkbox" class="chk" value="', ch.cheque_id, '" data-importe="', num, '"></td>',
              '<td>', ch.numero||'', '</td>',
              '<td>', ch.fecha||'', '</td>',
              '<td>', ch.fecha_pago||'', '</td>',
              '<td>', ch.banco||'', '</td>',
              '<td>', ch.cuit||'', '</td>',
              '<td class="text-right">', formatCurrency(num), '</td>',
              '<td>', ch.observaciones||'', '</td>',
            '</tr>'
          ].join('');
        }).join('');
        if (!rows) rows = '<tr><td colspan="8" class="text-center text-muted">No hay cheques en esta cuenta.</td></tr>';
        $tbody.html(rows);
        $chkAll.prop('checked', false);
        recompute();
        $panel.show();
      })
      .fail(function(xhr){
        $tbody.html('<tr><td colspan="8" class="text-center text-danger">Error al cargar (' + xhr.status + ').</td></tr>');
        $panel.show();
      });
  }

  $from.on('change', cargarCheques);
  $to.on('change', recompute);
  $chkAll.on('change', function(){
    $tbody.find('input.chk').prop('checked', $(this).is(':checked'));
    recompute();
  });
  $tbody.on('change', 'input.chk', function(){
    if (!$(this).is(':checked')) $chkAll.prop('checked', false);
    recompute();
  });
  $btnUsarTotal.on('click', function(e){ e.preventDefault(); recompute(); });

  $btnTransfer.on('click', function(){
    var fromId = $from.val();
    var toId   = $to.val();
    if (!fromId || !toId) {
      mensaje('danger','Elegí cuenta origen y destino.');
      return;
    }
    var ids = [];
    $tbody.find('input.chk:checked').each(function(){ ids.push($(this).val()); });
    if (ids.length === 0) {
      mensaje('danger','Seleccioná al menos un cheque.');
      return;
    }

    $btnTransfer.prop('disabled', true).text('Procesando…');
    $.ajax({
      url: API,
      method: 'POST',
      dataType: 'json',
      data: {
        action: 'transfer',
        from_account_id: fromId,
        to_account_id: toId,
        'cheque_ids[]': ids
      }
    })
    .done(function(resp){
      if (!resp || resp.ok === false) {
        mensaje('danger', (resp && resp.error) ? resp.error : 'Error al transferir.');
        return;
      }

      var totalNum = parseFloat(resp.total || 0);
      mensaje('success',
        'Transferidos ' + resp.moved + ' cheque(s). Total: ' + formatCurrency(totalNum)
      );

      // Al terminar, ir a la lista de transferencias
      if (resp.transfer_id) {
        window.location.href = 'ver_transferencias.php';
      }
    })
    .fail(function(xhr){
      var msg = (xhr.responseJSON && xhr.responseJSON.error)
        ? xhr.responseJSON.error
        : ('Error ' + xhr.status);
      mensaje('danger', msg);
    })
    .always(function(){
      $btnTransfer.prop('disabled', false).text('Transferir seleccionados');
    });
  });

})();
</script>

<?php include __DIR__ . '/footer.php'; ?>
