<?php 
include ("../../_init.php");
$customer_id = isset($request->get['customer_id']) ? $request->get['customer_id'] : 0;
?>
<style>
  .compact *{font-size:12px}
  .compact .form-control{height:28px;padding:4px 8px}
  .compact .input-group-addon{padding:3px 8px}
  .compact .section-title{margin:6px 0 8px;font-weight:600}
  .modal-lg{width:97%;margin-top:15px;margin-bottom:15px}
  #filas-container .formulario-fila{
    display:flex;flex-wrap:wrap;gap:6px;margin:6px 0;padding:6px;border:1px dashed #e5e7eb;border-radius:6px;background:#fcfcfd
  }
  #filas-container .formulario-fila .form-control{min-width:140px}
  .btn-icon{width:28px;height:28px;line-height:1;padding:4px 0;text-align:center}
</style>

<form class="form-horizontal compact" id="checkout-form" action="payment.php">
  <!-- hidden requeridos -->
  <input type="hidden" name="invoice-id" value="{{ order.invoice_id }}">
  <input type="hidden" name="customer-id" value="{{ order.customer_id }}">
  <input type="hidden" name="pmethod-id" value="{{ pmethodId }}">
  <input type="hidden" name="tiporecibo" value="2"><!-- SIEMPRE RECIBO A CUENTA -->

  <div class="bootbox-body">
    <div class="table-selection">
      <!-- M�todos -->
      <div class="col-lg-2 col-md-2 col-sm-3 bootboox-tab-menu bootboox-container p-0">
        <div class="list-group" style="margin-bottom:0">
          <?php $inc = 0;foreach(get_pmethods() as $pmethod) : ?>
            <a class="text-left list-group-item pmethod_item"
               id="pmethod_<?php echo $pmethod['pmethod_id']; ?>"
               href="javascript:void(0)"
               <?php echo $inc == 0 ? 'ng-init="selectPaymentMethod('.$pmethod['pmethod_id'].',\''.$pmethod['code_name'].'\')"' : null;?>
               ng-click="selectPaymentMethod('<?php echo $pmethod['pmethod_id']; ?>','<?php echo $pmethod['code_name']; ?>')"
               onClick="return false;">
              <span class="fa fa-fw fa-angle-double-right"></span>
              <b><?php echo $pmethod['name']; ?></b>
              <?php if (strtolower($pmethod['code_name']) == 'credit'):
                $customer_balance = get_customer_balance($customer_id); ?>
                <small class="pull-right" ng-init="customerBalance='<?php echo $customer_balance;?>'">
                  (<?php echo get_currency_symbol();?><?php echo currency_format($customer_balance);?>)
                </small>
              <?php endif;?>
            </a>
          <?php $inc++;endforeach; ?>
        </div>
      </div>

      <!-- Centro -->
      <div class="col-lg-6 col-md-6 col-sm-5 bootboox-container pmethod-option checkout-payment-option">
        <h5 ng-show="pmethodId" class="text-center" style="margin:5px 0">
          <?php echo trans('text_pmethod'); ?> <b>{{ pmethodName }}</b>
        </h5>

        <?php
          $statement = db()->prepare("SELECT `taxrate` FROM `taxrates` WHERE `taxrate_id` = 6");
          $statement->execute();
          $source  = $statement->fetch(PDO::FETCH_ASSOC);
          $taxrate = $source ? $source['taxrate'] : 0;
        ?>

        <!-- Monto y cotizaci�n -->
        <div class="section-title"><?php echo trans('MONTO Y COTIZACI�N'); ?></div>
        <div class="input-group input-group-sm" style="width:100%">
          <span class="input-group-addon hidden-sm" style="width:35%"><?php echo trans('MONTO PAGO EN PESOS'); ?></span>
          <input class="form-control" name="pago-pesos" ng-model="pagoPesos" placeholder="<?php echo trans('monto en pesos'); ?>" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
          <span class="input-group-addon hidden-sm" style="width:20%"><?php echo trans('Cotizacion'); ?></span>
          <input  name="cotizaciondolar" type="text" class="form-control" id="cotizaciondolar" ng-model="cotiDolar" placeholder="">
        </div>
        <div class="text-right" style="margin:4px 0">
          <small><?php echo trans('COTIZACION DOLAR OFICIAL'); ?>: <b><?php echo $taxrate; ?></b></small>
        </div>

        <!-- Totales -->
        <div style="margin:6px 0">
          <div><small><?php echo trans('IMPORTE EN DOLARES:'); ?></small> <b>{{ pagoPesos > 0 && cotiDolar > 0 ? pagoPesos / cotiDolar  : 0 | formatDecimal:4 }}</b></div>
          <div><small><?php echo trans('BALANCE CONTRAPARTIDA PESOS:'); ?></small>
            <b>{{ ( (pagoPesos>0 && cotiDolar>0 ? (pagoPesos) : (paidAmount*cotiDolar) ) ) - (importeCheque + importeEfectivo + importeDeposito + importeRetencion + (importeDolar * cotizacionBillete)) | formatDecimal:4 }}</b>
          </div>
        </div>

        <!-- paid-amount (readonly) -->
        <input type="text" id="paid-amount" name="paid-amount" class="form-control"
               value="{{ pagoPesos > 0 && cotiDolar > 0 ? pagoPesos / cotiDolar : 0 | formatDecimal:4 }}" readonly>

        <hr style="margin:8px 0">

        <!-- CONTRAPARTIDAS -->
        <div class="section-title"><?php echo trans('CONTRAPARTIDAS'); ?></div>

        <!-- Caja pesos (permite negativo para vuelto) -->
        <div class="input-group input-group-sm" style="width:100%;margin-bottom:6px">
          <span class="input-group-addon hidden-sm" style="width:35%"><?php echo trans('Caja Diaria Pesos'); ?></span>
          <input type="number" step="0.01" id="importeefectivo" name="importeefectivo" ng-model="importeEfectivo" class="form-control" placeholder="0.00 (negativo = vuelto)">
        </div>

        <!-- Total cheques -->
        <div class="input-group input-group-sm" style="width:100%;margin-bottom:6px">
          <span class="input-group-addon hidden-sm" style="width:35%"><?php echo trans('IMPORTE TOTAL EN CHEQUES'); ?></span>
          <input type="number" step="0.01" id="importecheque" name="importecheque" ng-model="importeCheque" class="form-control" placeholder="0.00">
        </div>

        <!-- Cheques m�ltiples -->
        <div id="filas-container">
          <div class="formulario-fila">
            <input type="text"  class="form-control" name="num_cheque[]"        placeholder="N�mero de Cheque">
            <input type="date"  class="form-control" name="fecha_cheque[]"      placeholder="Fecha emisi�n">
            <input type="date"  class="form-control" name="fecha_pago_cheque[]" placeholder="Fecha cobro">
            <input type="number" step="0.01" class="form-control" name="importe_cheque[]"    placeholder="Importe">
            <input type="text"  class="form-control" name="cuit_titular[]"      placeholder="CUIT Titular">
            <select class="form-control" name="caja_id[]">
              <option value="2">CAJA FISICO</option>
              <option value="17">CAJA ELECTRONICO</option>
            </select>
            <select class="form-control" name="tipo_cheque[]">
              <option value="fisico">Cheque F�sico</option>
              <option value="echeq">eCheq</option>
            </select>
            <input type="text" class="form-control" name="banco_cheque[]"         placeholder="Banco">
            <input type="text" class="form-control" name="observaciones_cheque[]" placeholder="Observaciones (opcional)">
            <div class="btn-group">
              <button type="button" class="btn btn-success btn-icon" onclick="agregarFila()"><span class="fa fa-plus"></span></button>
              <button type="button" class="btn btn-danger  btn-icon" onclick="eliminarFila(this)"><span class="fa fa-minus"></span></button>
            </div>
          </div>
        </div>

        <!-- D�lar billete -->
        <div class="input-group input-group-sm" style="width:100%;margin-top:6px">
          <span class="input-group-addon hidden-sm" style="width:35%"><?php echo trans('Caja Dolar BILLETE Diaria'); ?></span>
          <input type="number" step="0.01" id="importe-dolar" name="importedolar" ng-model="importeDolar" class="form-control" placeholder="USD">
          <span class="input-group-addon hidden-sm" style="width:30%"><?php echo trans('Cotizacion Dolar Billete'); ?></span>
          <input type="number" step="0.01" id="cotizacion-billete" name="cotizacionbillete" ng-model="cotizacionBillete" class="form-control" placeholder="TC billete">
        </div>

        <!-- Dep�sitos / Transferencias -->
        <div class="input-group input-group-sm" style="width:100%;margin-top:6px">
          <span class="input-group-addon hidden-sm" style="width:35%"><?php echo trans('Caja deposito'); ?></span>
          <input type="number" step="0.01" id="importedeposito" name="importedeposito" ng-model="importeDeposito" class="form-control" placeholder="0.00">
          <span class="input-group-addon hidden-sm" style="width:30%"><?php echo trans('Numero de Transaccion'); ?></span>
          <input type="text" id="numerodeposito" name="numerodeposito" class="form-control" placeholder="Referencia">
        </div>

        <!-- Retenciones -->
        <div class="input-group input-group-sm" style="width:100%;margin-top:6px">
          <span class="input-group-addon hidden-sm" style="width:35%"><?php echo trans('Caja RETENCIONES'); ?></span>
          <input type="number" step="0.01" id="importeretencion" name="importeretencion" ng-model="importeRetencion" class="form-control" placeholder="0.00">
          <span class="input-group-addon hidden-sm" style="width:30%"><?php echo trans('Numero de Retencion'); ?></span>
          <input type="text" id="numeroretencion" name="numeroretencion" class="form-control" placeholder="Referencia">
        </div>
         <!-- DESCUENTO -->
        <div class="input-group input-group-sm" style="width:100%;margin-top:6px">
          <span class="input-group-addon hidden-sm" style="width:35%"><?php echo trans('Contra Partida ND'); ?></span>
          <input type="number" step="0.01" id="importedescuento" name="importedescuento" ng-model="importeDescuento" class="form-control" placeholder="0.00">
          <span class="input-group-addon hidden-sm" style="width:30%"><?php echo trans('Detalle'); ?></span>
          <input type="text" id="detalleDescuento" name="detalleDescuento" class="form-control" placeholder="escriba nota">
        </div>

        <!-- Nota -->
        <div class="input-group input-group-sm" style="width:100%;margin-top:6px">
          <span class="input-group-addon hidden-sm" style="width:35%"><?php echo trans('label_note'); ?></span>
          <input type="text" name="note" class="form-control" placeholder="<?php echo trans('placeholder_note_here');?>">
        </div>

        <!-- Campos pmethod espec�ficos (tu app los inyecta) -->
        <div bind-html-compile="rawPaymentMethodHtml"></div>
      </div>

      <!-- Resumen derecha (igual que ten�as) -->
      <div class="col-lg-4 col-md-4 col-sm-4 cart-details bootboox-container">
        <div class="table-responsive" style="margin-top:10px">
          <table class="table table-bordered table-striped table-condensed">
            <tbody>
              <tr>
                <td class="w-40 text-right"><?php echo trans('label_invoice_id'); ?></td>
                <td class="w-60 bg-gray">{{ order.invoice_id }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="text-center">
          <h5 style="margin:6px 0"><?php echo trans('text_billing_details'); ?></h5>
        </div>

        <div class="table-responsive">
          <table class="table table-bordered table-striped table-condensed">
            <tbody>
              <tr ng-repeat="items in order.items">
                <td class="text-center w-10">
                  <input type="hidden" name="item['{{ items.item_id }}'][item_id]" value="{{ items.item_id }}">
                  <input type="hidden" name="item['{{ items.item_id }}'][category_id]" value="{{ items.categoryId }}">
                  <input type="hidden" name="item['{{ items.item_id }}'][sup_id]" value="{{ items.supId }}">
                  <input type="hidden" name="item['{{ items.item_id }}'][item_name]" value="{{ items.item_name }}">
                  <input type="hidden" name="item['{{ items.item_id }}'][item_price]" value="{{ items.item_price  | formatDecimal:2 }}">
                  <input type="hidden" name="item['{{ items.item_id }}'][item_quantity]" value="{{ items.item_quantity }}">
                  <input type="hidden" name="item['{{ items.item_id }}'][item_total]" value="{{ items.item_total  | formatDecimal:2 }}">
                  {{ $index+1 }}
                </td>
                <td class="w-70">{{ items.item_name }} (x{{ items.item_quantity | formatDecimal:2 }} {{ items.unitName }})</td>
                <td class="text-right w-20">{{ items.item_total  | formatDecimal:2 }}</td>
              </tr>
            </tbody>
            <tfoot>
              <tr>
                <th class="text-right w-60" colspan="2"><?php echo trans('label_subtotal'); ?></th>
                <input type="hidden" name="sub-total" value="{{ order.subtotal }}">
                <td class="text-right w-40">{{ order.subtotal  | formatDecimal:2 }}</td>
              </tr>
              <tr>
                <th class="text-right w-60" colspan="2"><?php echo trans('label_order_tax'); ?></th>
                <input type="hidden" name="tax-amount" value="{{ order.order_tax }}">
                <td class="text-right w-40">{{ order.order_tax  | formatDecimal:2 }}</td>
              </tr>
              <tr>
                <th class="text-right w-60" colspan="2"><?php echo trans('label_shipping_charge'); ?></th>
                <input type="hidden" name="shipping-type" value="{{ shippingType }}">
                <input type="hidden" name="shipping-amount" value="{{ shippingType  == 'percentage' ? _percentage(totalAmount, shippingAmount) : shippingAmount }}">
                <td class="text-right w-40">{{ shippingType  == 'percentage' ? (_percentage(totalAmount, shippingAmount) | formatDecimal:2) : (shippingAmount | formatDecimal:2) }}</td>
              </tr>
              <tr>
                <th class="text-right w-60" colspan="2"><?php echo trans('label_others_charge'); ?></th>
                <input type="hidden" name="others-charge" value="{{ othersCharge }}">
                <td class="text-right w-40">{{ othersCharge | formatDecimal:2 }}</td>
              </tr>
              <tr>
                <th class="text-right w-60" colspan="2"><?php echo trans('label_previous_due'); ?></th>
                <input type="hidden" name="previous-due" value="{{ order.previous_due }}">
                <td class="text-right w-40">{{ order.previous_due | formatDecimal:2 }}</td>
              </tr>
              <tr>
                <th class="text-right w-60 bg-gray" colspan="2"><?php echo trans('label_payable_amount'); ?> <small>({{ order.total_items }} items)</small></th>
                <input type="hidden" name="payable-amount" value="{{ order.payable_amount }}">
                <td class="text-right w-40 bg-gray">{{ order.payable_amount | formatDecimal:2 }}</td>
              </tr>
              <tr class="success">
                <th class="text-right w-60" colspan="2"><?php echo trans('label_previous_due_paid'); ?></th>
                <input type="hidden" name="previous-due" value="{{ order.prev_due_paid }}">
                <td class="text-right w-40">{{ order.prev_due_paid | formatDecimal:2 }}</td>
              </tr>

              <tr class="danger">
                <th class="text-right w-60" colspan="2"><?php echo trans('label_due'); ?></th>
                <input type="hidden" name="due-amount" value="{{ order.due }}">
                <td class="text-right w-40">{{ order.due | formatDecimal:2 }}</td>
              </tr>

              <tr ng-show="order.invoice_not" class="active">
                <td colspan="3"><b><?php echo trans('label_note'); ?>:</b> {{ order.invoice_note }}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>
  </div>
</form>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Suma autom�tica del total de cheques -> #importecheque
$(document).on('input change', "input[name='importe_cheque[]']", function () { calcularSuma(); });

function agregarFila() {
  var $c = $('#filas-container');
  var $clone = $c.children().first().clone();
  $clone.find('input').val('');
  $clone.find('select').each(function(){ this.selectedIndex = 0; });
  $c.append($clone);
  calcularSuma();
}
function eliminarFila(btn) {
  var $c = $('#filas-container');
  if ($c.children().length > 1) {
    $(btn).closest('.formulario-fila').remove();
    calcularSuma();
  }
}
function calcularSuma() {
  var suma = 0;
  $("input[name='importe_cheque[]']").each(function() {
    var v = parseFloat($(this).val());
    if (!isNaN(v)) suma += v;
  });
  $("#importecheque").val(suma.toFixed(2));
}
</script>
