<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
    .border-danger {
        border: 2px solid #d9534f !important;
        box-shadow: 0 0 5px rgba(217, 83, 79, 0.5) !important;
    }
</style>
<div class="content-wrapper">
  <section class="content-header">
    <h1>
      Gérer les
      <small>Commandes</small>
    </h1>
    <ol class="breadcrumb">
      <li><a href="#"><i class="fa fa-dashboard"></i> Accueil</a></li>
      <li class="active">Commandes</li>
    </ol>
  </section>

  <section class="content">
    <div class="row">
      <div class="col-md-12 col-xs-12">

        <div id="messages"></div>

        <?php if (session()->getFlashdata('success')): ?>
            <div class="alert alert-success alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <?php echo session()->getFlashdata('success'); ?>
            </div>
        <?php elseif (session()->getFlashdata('error')): ?>
            <div class="alert alert-danger alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <?php echo session()->getFlashdata('error'); ?>
            </div>
        <?php endif; ?>

        <?php if ($errors = session()->getFlashdata('errors')): ?>
            <div class="alert alert-danger alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <?php if (is_array($errors)): ?>
                    <ul>
                        <?php foreach ($errors as $error): ?>
                            <li><?= esc($error) ?></li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <?= esc($errors) ?>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <div class="box">
          <div class="box-header">
            <h3 class="box-title">Mise à jour de commande</h3>
          </div>
          
          <form role="form" action="<?php base_url('orders/create') ?>" method="post" class="form-horizontal">
            <div class="box-body">

              <div class="form-group">
                <label for="date" class="col-sm-12 control-label">Date: <?php echo date('Y-m-d') ?></label>
              </div>
              <div class="form-group">
                <label for="time" class="col-sm-12 control-label">Heure: <?php echo date('h:i a') ?></label>
              </div>

             <div class="col-md-4 col-xs-12 pull pull-left">
                <!-- ✅ Type de document -->
                <div class="form-group">
                  <label for="document_type" class="col-sm-5 control-label" style="text-align:left;">
                    Type de document <span class="text-danger">*</span>
                  </label>
                  <div class="col-sm-7">
                    <select name="document_type" id="document_type" class="form-control" required>
                      <option value="facture" <?php echo (isset($order_data['order']['document_type']) && $order_data['order']['document_type'] == 'facture') ? 'selected' : ''; ?>>
                        Facture
                      </option>
                      <option value="bl" <?php echo (isset($order_data['order']['document_type']) && $order_data['order']['document_type'] == 'bl') ? 'selected' : ''; ?>>
                        Bon de Livraison
                      </option>
                      <option value="both" <?php echo (isset($order_data['order']['document_type']) && $order_data['order']['document_type'] == 'both') ? 'selected' : ''; ?>>
                        Facture & Bon de Livraison
                      </option>
                    </select>
                  </div>
              </div>

                <!-- Types d'impression -->
                <div class="form-group">
                  <label for="types" class="col-sm-5 control-label" style="text-align:left;">Types d'impression</label>
                  <div class="col-sm-7">
                    <select name="" id="typesCommande" class="form-control">
                      <option value="1">Facture</option>
                      <option value="2">Bon de Livraison & Facture</option>
                      <option value="3">Bon de Livraison</option>
                    </select>
                  </div>
                </div>

                <div class="form-group">
                  <label for="customer_name" class="col-sm-5 control-label" style="text-align:left;">Nom du client</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" id="customer_name" name="customer_name" placeholder="Enter Customer Name" value="<?php echo $order_data['order']['customer_name'] ?>" autocomplete="off" />
                  </div>
                </div>

                <div class="form-group">
                  <label for="customer_address" class="col-sm-5 control-label" style="text-align:left;">Adresse du client</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" id="customer_address" name="customer_address" placeholder="Enter Customer Address" value="<?php echo $order_data['order']['customer_address'] ?>" autocomplete="off">
                  </div>
                </div>

                <div class="form-group">
                  <label for="customer_phone" class="col-sm-5 control-label" style="text-align:left;">Téléphone du client</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" id="customer_phone" name="customer_phone" placeholder="Enter Customer Phone" value="<?php echo $order_data['order']['customer_phone'] ?>" autocomplete="off">
                  </div>
                </div>

                <div class="form-group">
                  <label for="customer_cin" class="col-sm-5 control-label" style="text-align:left;">CIN du client</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" id="customer_cin" name="customer_cin" placeholder="Enter Customer CIN" value="<?php echo $order_data['order']['customer_cin'] ?>" autocomplete="off">
                  </div>
                </div>

                <!-- ✅ Type de client -->
                <div class="form-group">
                  <label for="customer_type" class="col-sm-5 control-label" style="text-align:left;">Type de client <span class="text-danger">*</span></label>
                  <div class="col-sm-7">
                    <select class="form-control" id="customer_type" name="customer_type" required>
                      <option value="">-- Sélectionner --</option>
                      <option value="particulier" <?php echo (isset($order_data['order']['customer_type']) && strtolower($order_data['order']['customer_type']) == 'particulier') ? 'selected' : ''; ?>>Particulier</option>
                      <option value="revendeur" <?php echo (isset($order_data['order']['customer_type']) && strtolower($order_data['order']['customer_type']) == 'revendeur') ? 'selected' : ''; ?>>Revendeur</option>
                    </select>
                  </div>
                </div>

                <!-- ✅ Source -->
                <div class="form-group">
                  <label for="source" class="col-sm-5 control-label" style="text-align:left;">Source <span class="text-danger">*</span></label>
                  <div class="col-sm-7">
                  <select class="form-control" id="source" name="source" required>
                      <option value="">-- Sélectionner --</option>
                      <option value="facebook_perso" <?php echo (isset($order_data['order']['source']) && $order_data['order']['source'] == 'facebook_perso') ? 'selected' : ''; ?>>Facebook perso</option>
                      <option value="page_motorbike" <?php echo (isset($order_data['order']['source']) && $order_data['order']['source'] == 'page_motorbike') ? 'selected' : ''; ?>>Page motorbike</option>
                      <option value="bouche_a_oreille" <?php echo (isset($order_data['order']['source']) && $order_data['order']['source'] == 'bouche_a_oreille') ? 'selected' : ''; ?>>Bouche à oreille</option>
                      <option value="commercial_interne" <?php echo (isset($order_data['order']['source']) && $order_data['order']['source'] == 'commercial_interne') ? 'selected' : ''; ?>>Commercial interne</option>
                      <option value="autre" <?php echo (isset($order_data['order']['source']) && $order_data['order']['source'] == 'autre') ? 'selected' : ''; ?>>Autre</option>
                    </select>
                  </div>
                </div>

              </div>

              <br /> <br />
              <table class="table table-bordered" id="product_info_table">
                <thead>
                  <tr>
                    <th style="width:35%">Produit</th>
                    <!-- ✅ COLONNE QUANTITÉ (cachée par défaut) -->
                    <th class="qty-column" style="width:10%; display:none;">Quantité</th>
                    <th style="width:12%">Puissance (CC)</th>
                    <th style="width:15%">Prix unitaire</th>
                    <th style="width:18%">Montant</th>
                    <th style="width:10%"><button type="button" id="add_row" class="btn btn-default"><i class="fa fa-plus"></i></button></th>
                  </tr>
                </thead>

                <tbody>
  <?php if (isset($order_data['order_item'])): ?>
    <?php $x = 1; ?>
    <?php foreach ($order_data['order_item'] as $key => $val): ?>
      <tr id="row_<?php echo $x; ?>">
        <td>
          <select class="form-control select_group product" data-row-id="row_<?php echo $x; ?>" 
                  id="product_<?php echo $x; ?>" name="product[]" style="width:100%;" 
                  onchange="getProductData(<?php echo $x; ?>)" required>
            <option value=""></option>
            <?php foreach ($products as $k => $v): ?>
              <option value="<?php echo $v['id'] ?>" 
                      <?php if ($val['product_id'] == $v['id']) { echo "selected='selected'"; } ?>>
                <?php 
                    echo $v['sku'] . ' | ' . $v['name'];
                    if (!empty($v['numero_de_moteur'])) {
                        echo ' | ' . $v['numero_de_moteur'];
                    }
                ?>
              </option>
            <?php endforeach ?>
          </select>
        </td>
        
        <!-- ✅ CHAMP QUANTITÉ (caché par défaut) -->
        <td class="qty-column" style="display:none;">
          <input type="number" name="qty[]" id="qty_<?php echo $x; ?>" 
                 class="form-control numeric-input" 
                 value="<?php echo isset($val['qty']) ? esc($val['qty']) : '1'; ?>" 
                 min="1" disabled autocomplete="off">
        </td>
        
        <td>
          <input type="number" name="puissance[]" id="puissance_<?php echo $x; ?>" 
                 class="form-control" placeholder="Puissance" 
                 value="<?php echo esc($val['puissance'] ?? '1') ?>" 
                 autocomplete="off" min="1">
        </td>
        
        <td>
          <input type="text" name="rate[]" id="rate_<?php echo $x; ?>" 
                 class="form-control" disabled 
                 value="<?php echo esc($val['rate']) ?>" autocomplete="off">
          <input type="hidden" name="rate_value[]" id="rate_value_<?php echo $x; ?>" 
                 class="form-control" value="<?php echo esc($val['rate']) ?>" autocomplete="off">
          <input type="hidden" id="min_price_<?php echo $x; ?>" name="min_price[]" value="">
        </td>
        
        <td>
          <input type="text" name="amount[]" id="amount_<?php echo $x; ?>" 
                 class="form-control" disabled 
                 value="<?php echo esc($val['amount']) ?>" autocomplete="off">
          <input type="hidden" name="amount_value[]" id="amount_value_<?php echo $x; ?>" 
                 class="form-control" value="<?php echo esc($val['amount']) ?>" autocomplete="off">
        </td>
        
        <td>
          <button type="button" class="btn btn-default" 
                  onclick="removeRow('<?php echo $x; ?>')">
            <i class="fa fa-close"></i>
          </button>
        </td>
      </tr>
      <?php $x++; ?>
    <?php endforeach; ?>
  <?php endif; ?>
</tbody>
              </table>

              <br /> <br />

              <div class="col-md-6 col-xs-12 pull pull-right">

                <div class="form-group">
                  <label for="gross_amount" class="col-sm-5 control-label">Prix affiché</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" id="gross_amount" name="gross_amount" disabled value="<?php echo $order_data['order']['gross_amount'] ?>" autocomplete="off">
                    <input type="hidden" class="form-control" id="gross_amount_value" name="gross_amount_value" value="<?php echo $order_data['order']['gross_amount'] ?>" autocomplete="off">
                  </div>
                </div>

                <div class="form-group">
                  <label for="discount" class="col-sm-5 control-label">Prix demandé</label>
                  <div class="col-sm-7">
                    <div id="discount_error" class="alert alert-danger" style="display:none; padding: 8px; margin-bottom: 5px; font-size: 13px;">
                      <i class="fa fa-exclamation-triangle"></i> <span id="discount_error_text"></span>
                    </div>
                    <?php 
                        $users = session()->get('user');
                        if($users && $users['group_name'] == 'COMMERCIALE'): 
                    ?>
                        <input type="number" class="form-control numeric-input" id="discount" name="discount" 
                               placeholder="Prix demandé" onkeyup="subAmount()" 
                               oninput="validatePrixDemande(this)"
                               value="<?php echo $order_data['order']['discount'] ?>" autocomplete="off">
                    <?php else: ?>
                        <input type="text" class="form-control" id="discount" name="discount" readonly 
                               value="<?php echo $order_data['order']['discount'] ?>" autocomplete="off">
                    <?php endif; ?>
                  </div>
                </div>

                <div class="form-group">
                  <label for="net_amount" class="col-sm-5 control-label">Remise</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" id="net_amount" name="net_amount" disabled value="<?php echo $order_data['order']['net_amount'] ?>" autocomplete="off">
                    <input type="hidden" class="form-control" id="net_amount_value" name="net_amount_value" value="<?php echo $order_data['order']['net_amount'] ?>" autocomplete="off">
                  </div>
                </div>

                <?php 
                  $users = session()->get('user'); 
                  if ($users && $users['group_name'] !== 'COMMERCIALE'): 
                ?>

                <div class="form-group">
                  <label for="paid_status" class="col-sm-5 control-label">Tranche de paiement</label>
                  <div class="col-sm-7">
                    <select class="form-control" id="payment_mode" name="payment_mode">
                      <option value="1" selected>une tranche</option>
                      <option value="2">deux tranches</option>
                    </select>
                  </div>
                </div>

                <div class="form-group" id="montant_reference" style="display: none">
                  <label class="col-sm-5 control-label">Montant à répartir</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" id="montant_total_tranches" disabled>
                    <input type="hidden" id="montant_total_tranches_value">
                    <small class="text-muted" id="montant_source_label"></small>
                  </div>
                </div>

                <div id="payment-tranches">
                  <div class="form-group" id="paid_status_1" style="display: none">
                    <label for="paid_status_1" class="col-sm-5 control-label">Tranche 1</label>
                    <div class="col-sm-3">
                      <select class="form-control" id="payment_mode_1" name="order_payment_mode_1">
                        <option value="MVOLA">MVOLA</option>
                        <option value="Virement Bancaire">Virement Bancaire</option>
                        <option value="En espèce">En espèce</option>
                      </select>
                    </div>
                    <div class="col-sm-4">
                      <input type="number" class="form-control" id="payment_amount_1" 
                            name="tranche_1" placeholder="Montant" onkeyup="calculerTranche2()">
                    </div>
                  </div>
                  
                  <div class="form-group" id="paid_status_2" style="display: none">
                    <label for="paid_status_2" class="col-sm-5 control-label">Tranche 2 (Reste)</label>
                    <div class="col-sm-3">
                      <select class="form-control" id="payment_mode_2" name="order_payment_mode_2">
                        <option value="MVOLA">MVOLA</option>
                        <option value="Virement Bancaire">Virement Bancaire</option>
                        <option value="En espèce">En espèce</option>
                      </select>
                    </div>
                    <div class="col-sm-4">
                      <input type="number" class="form-control" id="payment_amount_2" 
                            name="tranche_2" placeholder="Montant" readonly>
                    </div>
                  </div>
                </div>
                <?php endif; ?>

                <?php 
                  $users = session()->get('user'); 
                  if ($users && $users['group_name'] !== 'COMMERCIALE'): 
                ?>

                <div class="form-group">
                  <label for="paid_status" class="col-sm-5 control-label">Statut payant</label>
                  <div class="col-sm-7">
                    <select type="text" class="form-control" id="paid_status" name="paid_status">
                      <option value="1">Payé</option>
                      <option value="2">Refusé</option>
                    </select>
                  </div>
                </div>
                <?php endif; ?>
              </div>
            </div>
            
            <div class="box-footer">
              <input type="hidden" name="service_charge_rate" value="<?php echo $company_data['service_charge_value'] ?>" autocomplete="off">
              <input type="hidden" name="vat_charge_rate" value="<?php echo $company_data['vat_charge_value'] ?>" autocomplete="off">

              <a target="__blank" id="Imprimente" href="<?php echo base_url() . 'orders/printDiv/' . $order_data['order']['id'] ?>" class="btn btn-default">Imprimer</a>
              <button type="submit" class="btn btn-primary">Enregistrer</button>
              <a href="<?php echo base_url('orders/') ?>" class="btn btn-warning">Retour</a>
            </div>
          </form>
        </div>
      </div>
    </div>
  </section>
</div>

<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
var idData = "<?php echo $order_data['order']['id']; ?>";
let Imprimente = document.getElementById('Imprimente');
let typesCommande = document.getElementById('typesCommande');
let documentType = document.getElementById('document_type');

// ✅ Fonction pour afficher/masquer la colonne quantité
function toggleQuantityColumn() {
    var customerType = $('#customer_type').val();
    
    if (customerType === 'revendeur') {
        $('.qty-column').show();
        $('input[name="qty[]"]').prop('disabled', false);
    } else {
        $('.qty-column').hide();
        $('input[name="qty[]"]').val(1).prop('disabled', true);
        recalculateAllRows();
    }
}

// ✅ Fonction pour recalculer tous les montants
function recalculateAllRows() {
    var tableProductLength = $("#product_info_table tbody tr").length;
    for (var i = 1; i <= tableProductLength; i++) {
        if ($("#row_" + i).length > 0) {
            getTotal(i);
        }
    }
}

function validatePositiveNumber(input) {
    let value = parseFloat(input.value);
    if (isNaN(value) || value < 0) {
        input.value = '';
        return false;
    }
    return true;
}

function showDiscountError(message) {
    $('#discount_error_text').text(message);
    $('#discount_error').slideDown(200);
    $('#discount').addClass('border-danger');
}

function hideDiscountError() {
    $('#discount_error').slideUp(200);
    $('#discount').removeClass('border-danger');
}

function validatePrixDemande(input) {
    let prixDemande = parseFloat(input.value);
    let prixAffiche = parseFloat($('#gross_amount').val()) || 0;
    
    if (isNaN(prixDemande) || prixDemande < 0) {
        input.value = '';
        showDiscountError('Le prix demandé ne peut pas être négatif.');
        setTimeout(hideDiscountError, 3000);
        return false;
    }
    
    if (prixDemande > prixAffiche) {
        showDiscountError('Le prix demandé (' + prixDemande.toFixed(2) + ') ne peut pas être supérieur au prix affiché (' + prixAffiche.toFixed(2) + ').');
        input.value = prixAffiche;
        subAmount();
        setTimeout(hideDiscountError, 4000);
        return false;
    }
    
    hideDiscountError();
    return true;
}

function preventNegativeInput(e) {
    if (e.key === '-' || e.key === 'e' || e.key === 'E' || e.key === '+') {
        e.preventDefault();
        return false;
    }
}

function updatePrintLink() {
  let type = documentType ? documentType.value : 'facture';
  
  if (typesCommande) {
    if (type === 'facture') {
      typesCommande.value = 1;
    } else if (type === 'bl') {
      typesCommande.value = 3;
    } else if (type === 'both') {
      typesCommande.value = 2;
    }
  }
  
  if (Imprimente) {
    Imprimente.removeAttribute("href");
    
    switch(type) {
      case 'facture':
        Imprimente.setAttribute("href", base_url + 'orders/printDiv/' + idData);
        break;
      case 'bl':
        Imprimente.setAttribute("href", base_url + 'orders/printDivBL/' + idData);
        break;
      case 'both':
        Imprimente.setAttribute("href", base_url + 'orders/printDivBLF/' + idData);
        break;
      default:
        Imprimente.setAttribute("href", base_url + 'orders/printDiv/' + idData);
    }
  }
}

if (documentType) {
  documentType.addEventListener('change', updatePrintLink);
  updatePrintLink();
}

if (typesCommande) {
  typesCommande.addEventListener('change', function () {
    if (documentType) {
      if (typesCommande.value == 1) {
        documentType.value = 'facture';
      } else if (typesCommande.value == 3) {
        documentType.value = 'bl';
      } else {
        documentType.value = 'both';
      }
    }
    updatePrintLink();
  });
}

$(document).ready(function() {
    $(".select_group").select2();

    $("#mainOrdersNav").addClass('active');
    $("#manageOrdersNav").addClass('active');

    // ✅ Initialiser l'affichage selon le type de client
    toggleQuantityColumn();
    
    // ✅ Écouter les changements du type de client
    $('#customer_type').on('change', function() {
        toggleQuantityColumn();
    });

    // ✅ Gérer les changements de quantité
    $(document).on('input', 'input[name="qty[]"]', function() {
        var row_id = $(this).attr('id').replace('qty_', '');
        var qty = parseInt($(this).val()) || 1;
        
        if (qty < 1) {
            $(this).val(1);
            qty = 1;
        }
        
        getTotal(row_id);
    });

    $(document).on('keydown', '.numeric-input, input[type="number"]', function(e) {
        preventNegativeInput(e);
    });

    $(document).on('input', '.numeric-input, input[type="number"]', function() {
        validatePositiveNumber(this);
    });

    $("#discount").on('input', function() {
        validatePrixDemande(this);
    });

    $("#discount").on('blur', function() {
        validatePrixDemande(this);
        checkMinimalPrice();
    });

    $('form').on('submit', function(e) {
        let hasNegative = false;
        $('.numeric-input, input[type="number"]').each(function() {
            if (parseFloat($(this).val()) < 0) {
                hasNegative = true;
                $(this).val('');
            }
        });

        if (hasNegative) {
            alert('Les valeurs négatives ne sont pas autorisées.');
            e.preventDefault();
            return false;
        }

        if (!checkMinimalPrice()) {
            e.preventDefault();
            return false;
        }
    });

    var paymentTranche = 1;
    
    function getMontantTotal() {
        var discount = parseFloat($('#discount').val()) || 0;
        var grossAmount = parseFloat($('#gross_amount_value').val()) || 0;
        return discount > 0 ? discount : grossAmount;
    }
    
    var netAmount = getMontantTotal();
    $('#payment_amount_1').val(netAmount);

    function addPaymentTranche(paymentTranche) {
      if (parseInt(paymentTranche) === 2) {
        $("#paid_status_1").show();
        $("#paid_status_2").show();
        $("#montant_reference").show();

        var amount1 = parseFloat($('#payment_amount_1').val()) || 0;
        var montantTotal = getMontantTotal();
        var amount2 = montantTotal - amount1;
        $('#payment_amount_2').val(amount2.toFixed(2));
      } else {
        $("#paid_status_1").show();
        $("#paid_status_2").hide();
        $("#montant_reference").hide();
        $('#payment_mode_2').val('');
        
        var montantTotal = getMontantTotal();
        $('#payment_amount_1').val(montantTotal.toFixed(2));
      }
    }

    $("#payment_mode").on("change", function() {
      addPaymentTranche($(this).val());
      updateMontantTranches();
    });

    $('#payment_amount_1').on("input", function() {
      var amount1 = parseFloat($(this).val()) || 0;
      var montantTotal = getMontantTotal();
      var amount2 = montantTotal - amount1;
      
      if (amount2 < 0) amount2 = 0;
      
      $('#payment_amount_2').val(amount2.toFixed(2));
    });

    addPaymentTranche(paymentTranche);

    $("#add_row").unbind('click').bind('click', function() {
      var table = $("#product_info_table");
      var count_table_tbody_tr = $("#product_info_table tbody tr").length;
      var row_id = count_table_tbody_tr + 1;

      $.ajax({
        url: base_url + '/orders/getTableProductRow/',
        type: 'post',
        dataType: 'json',
        success: function(response) {
          var customerType = $('#customer_type').val();
          var qtyColumnVisible = (customerType === 'revendeur') ? '' : 'style="display:none;"';
          var qtyDisabled = (customerType === 'revendeur') ? '' : 'disabled';
          
          var html = '<tr id="row_' + row_id + '">' +
            '<td>' +
            '<select class="form-control select_group product" data-row-id="' + row_id + '" id="product_' + row_id + '" name="product[]" style="width:100%;" onchange="getProductData(' + row_id + ')">' +
            '<option value=""></option>';
          
          $.each(response, function(index, value) {
            var displayText = value.sku + ' | ' + value.name;
            if (value.numero_de_moteur) {
              displayText += ' | ' + value.numero_de_moteur;
            }
            html += '<option value="' + value.id + '">' + displayText + '</option>';
          });

          html += '</select></td>' +
            '<td class="qty-column" ' + qtyColumnVisible + '><input type="number" name="qty[]" id="qty_' + row_id + '" class="form-control numeric-input" min="1" value="1" ' + qtyDisabled + ' autocomplete="off"></td>' +
            '<td><input type="number" name="puissance[]" id="puissance_' + row_id + '" class="form-control" placeholder="CC" min="1" autocomplete="off"></td>' +
            '<td><input type="text" name="rate[]" id="rate_' + row_id + '" class="form-control" disabled><input type="hidden" name="rate_value[]" id="rate_value_' + row_id + '" class="form-control"><input type="hidden" id="min_price_' + row_id + '" name="min_price[]" value=""></td>' +
            '<td><input type="text" name="amount[]" id="amount_' + row_id + '" class="form-control" disabled><input type="hidden" name="amount_value[]" id="amount_value_' + row_id + '" class="form-control"></td>' +
            '<td><button type="button" class="btn btn-default" onclick="removeRow(\'' + row_id + '\')"><i class="fa fa-close"></i></button></td>' +
            '</tr>';

          if (count_table_tbody_tr >= 1) {
            $("#product_info_table tbody tr:last").after(html);
          } else {
            $("#product_info_table tbody").html(html);
          }

          $(".product").select2();
        }
      });

      return false;
    });
  });

  function getTotal(row = null) {
    if (row) {
      var rate = Number($("#rate_value_" + row).val()) || 0;
      var qty = Number($("#qty_" + row).val()) || 1;
      
      if (rate < 0) rate = 0;
      if (qty < 1) qty = 1;
      
      var total = rate * qty;
      total = total.toFixed(2);
      $("#amount_" + row).val(total);
      $("#amount_value_" + row).val(total);

      subAmount();
    } else {
      alert('no row !! please refresh the page');
    }
  }

  function getProductData(row_id) {
    var product_id = $("#product_" + row_id).val();
    if (product_id == "") {
      $("#rate_" + row_id).val("");
      $("#rate_value_" + row_id).val("");
      $("#min_price_" + row_id).val("");
      $("#puissance_" + row_id).val("");
      $("#qty_" + row_id).val("1");
      $("#amount_" + row_id).val("");
      $("#amount_value_" + row_id).val("");
    } else {
      $.ajax({
        url: base_url + 'orders/getProductValueById',
        type: 'post',
        data: { product_id: product_id },
        dataType: 'json',
        success: function(response) {
          var prixVente = parseFloat(response.prix_vente) || 0;
          var prixMinimal = parseFloat(response.prix_minimal) || 0;
          
          if (prixVente < 0) prixVente = 0;
          if (prixMinimal < 0) prixMinimal = 0;

          $("#rate_" + row_id).val(prixVente);
          $("#rate_value_" + row_id).val(prixVente);
          $("#min_price_" + row_id).val(prixMinimal);
          
          var puissanceValue = response.puissance || '';
          $("#puissance_" + row_id).val(puissanceValue);

          var qty = parseInt($("#qty_" + row_id).val()) || 1;
          var total = prixVente * qty;
          total = total.toFixed(2);
          $("#amount_" + row_id).val(total);
          $("#amount_value_" + row_id).val(total);

          subAmount();
        }
      });
    }
  }

  function subAmount() {
    var service_charge = <?php echo ($company_data['service_charge_value'] > 0) ? $company_data['service_charge_value'] : 0; ?>;
    var vat_charge = <?php echo ($company_data['vat_charge_value'] > 0) ? $company_data['vat_charge_value'] : 0; ?>;

    var tableProductLength = $("#product_info_table tbody tr").length;
    var totalSubAmount = 0;
    for (x = 0; x < tableProductLength; x++) {
        var tr = $("#product_info_table tbody tr")[x];
        var count = $(tr).attr('id');
        count = count.substring(4);
        var amount = Number($("#amount_" + count).val());
        if (amount < 0) amount = 0;
        totalSubAmount = Number(totalSubAmount) + amount;
    }

    totalSubAmount = totalSubAmount.toFixed(2);
    $("#gross_amount").val(totalSubAmount);
    $("#gross_amount_value").val(totalSubAmount);

    var vat = (Number($("#gross_amount").val()) / 100) * vat_charge;
    vat = vat.toFixed(2);
    $("#vat_charge").val(vat);
    $("#vat_charge_value").val(vat);

    var service = (Number($("#gross_amount").val()) / 100) * service_charge;
    service = service.toFixed(2);
    $("#service_charge").val(service);
    $("#service_charge_value").val(service);

    var discount = Number($("#discount").val()) || 0;
    if (discount < 0) {
        discount = 0;
        $("#discount").val('');
    }
    
    var grossAmount = Number(totalSubAmount);
    var netAmount = grossAmount - discount;
    
    if (netAmount < 0) netAmount = 0;
    
    netAmount = netAmount.toFixed(2);
    $("#net_amount").val(netAmount);
    $("#net_amount_value").val(netAmount);

    var paid_amount = Number($("#paid_amount").val());
    if (paid_amount) {
        var net_amount_value = Number($("#net_amount_value").val());
        var remaning = net_amount_value - paid_amount;
        $("#remaining").val(remaning.toFixed(2));
        $("#remaining_value").val(remaning.toFixed(2));
    }

    updateMontantTranches();
  }

  function checkMinimalPrice() {
    var discount = Number($("#discount").val()) || 0;
    
    if (discount < 0) {
        alert("Le prix demandé ne peut pas être négatif.");
        $("#discount").val('');
        subAmount();
        return false;
    }
    
    if (discount === 0) return true;
    
    var tableProductLength = $("#product_info_table tbody tr").length;
    var error = false;
    var messages = [];

    for (var i = 0; i < tableProductLength; i++) {
        var tr = $("#product_info_table tbody tr")[i];
        var rowId = $(tr).attr('id').replace('row_', '');
        var minPrice = Number($("#min_price_" + rowId).val()) || 0;

        if (minPrice > 0 && discount < minPrice) {
            error = true;
            var productText = $("#product_" + rowId + " option:selected").text();
            messages.push("Le prix demandé (" + discount.toFixed(2) + ") pour « " + productText + " » est inférieur au prix minimal (" + minPrice.toFixed(2) + ")");
        }
    }

    if (error) {
        alert(messages.join("\n"));
        $("#discount").val('');
        subAmount();
        return false;
    }
    return true;
  }

  function paidAmount() {
    var grandTotal = $("#net_amount_value").val();
    if (grandTotal) {
      var dueAmount = Number($("#net_amount_value").val()) - Number($("#paid_amount").val());
      dueAmount = dueAmount.toFixed(2);
      $("#remaining").val(dueAmount);
      $("#remaining_value").val(dueAmount);
    }
  }

  function removeRow(tr_id) {
    $("#product_info_table tbody tr#row_" + tr_id).remove();
    subAmount();
  }

  function getMontantPourTranches() {
    var discount = parseFloat($("#discount").val()) || 0;
    var grossAmount = parseFloat($("#gross_amount_value").val()) || 0;
    return discount > 0 ? (grossAmount - discount) : grossAmount;
  }

  function updateMontantTranches() {
    var montant = getMontantPourTranches();
    var discount = parseFloat($("#discount").val()) || 0;

    $("#montant_total_tranches").val(montant.toFixed(2));
    $("#montant_total_tranches_value").val(montant);

    if (discount > 0) {
        $("#montant_source_label").text("(Prix avec remise)");
    } else {
        $("#montant_source_label").text("(Montant brut)");
    }

    var paymentMode = $("#payment_mode").val();
    if (parseInt(paymentMode) === 1) {
        $("#payment_amount_1").val(montant.toFixed(2));
    } else {
        calculerTranche2();
    }
  }

  function calculerTranche2() {
    var montantTotal = getMontantPourTranches();
    var tranche1 = parseFloat($("#payment_amount_1").val()) || 0;
    var tranche2 = montantTotal - tranche1;
    if (tranche2 < 0) tranche2 = 0;
    $("#payment_amount_2").val(tranche2.toFixed(2));
  }

  $("#discount").on('keyup', function() {
    subAmount();
  });

  const net_amount_value = document.getElementById('net_amount_value');
  const net_amount = document.getElementById('net_amount');
  const payment_amount_1 = document.getElementById('payment_amount_1');
  
  if (payment_amount_1 && net_amount) {
    payment_amount_1.value = net_amount.value;
  }
</script>