<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <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>

  <!-- Main content -->
  <section class="content">
    <!-- Small boxes (Stat box) -->
    <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-error 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-error alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
            <ul>
              <?php foreach ($errors as $error): ?>
                <li><?= esc($error) ?></li>
              <?php endforeach; ?>
            </ul>
          </div>
        <?php endif; ?>


        <div class="box">
          <div class="box-header">
            <h3 class="box-title">Ajouter une commande</h3>
          </div>
          <!-- /.box-header -->
          <form role="form" action="<?php base_url('orders/create') ?>" method="post" class="form-horizontal">
            <?php if (isset($validation) && $validation->getErrors()): ?>
              <div class="alert alert-danger">
                <ul>
                  <?= $validation->listErrors() ?>
                </ul>
              </div>

            <?php endif; ?>
            <div class="box-body">


              <div class="form-group">
                <label for="gross_amount" class="col-sm-12 control-label"> Date : <?php echo date('Y-m-d') ?></label>
              </div>
              <div class="form-group">
                <label for="gross_amount" 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">

                <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="Entrer le nom du client" required value="<?= old('customer_name') ?>" autocomplete="off" />
                    <span id="name_error"></span>
                  </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="Entrer l'adresse du client" required autocomplete="off" value="<?= old('customer_address') ?>">
                  </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="Entrer le téléphone du client" required value="<?= old('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="Entrer ne CIN du client" autocomplete="off" required value="<?= old('customer_cin') ?>">
                  </div>
                </div>
              </div>


              <br /> <br />
              <table class="table table-bordered" id="product_info_table">
                <thead>
                  <tr>
                    <th style="width:50%">Produit</th>
                    <!-- <th style="width:10%">Quantité</th> -->
                    <th style="width:10%">Prix unitaire</th>
                    <th style="width:20%">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>
                  <tr id="row_1">
                    <td>
                      <select class="form-control select_group product" data-row-id="row_1" id="product_1"
                        name="product[]" style="width:100%;" onchange="getProductData(1)" required>
                        <option value=""></option>
                        <?php foreach ($products as $k => $v): ?>
                          <?php if ($v['product_sold'] == 0): ?>
                            <option value="<?php echo $v['id'] ?>">
                              <?= $v['sku'] . ' | ' . $v['name'] . ' | ' . $v['numero_de_moteur'] . ' | ' . $v['puissance'] ?>
                            </option>
                          <?php else: ?>
                            <option value="<?php echo $v['id'] ?>" disabled><?php echo $v['name'] ?> <span
                                style="background-color: #dc3545; color: #ffffff; padding: 2px 5px; border-radius: 5px;">
                                (Rupture de stock)</span></option>
                          <?php endif; ?>
                        <?php endforeach ?>
                      </select>


                    </td>

                    <td>
                      <input type="text" name="rate[]" id="rate_1" class="form-control" disabled autocomplete="off">
                      <input type="hidden" name="rate_value[]" id="rate_value_1" class="form-control"
                        autocomplete="off">
                    </td>
                    <td>
                      <input type="text" name="amount[]" id="amount_1" class="form-control" disabled autocomplete="off">
                      <input type="hidden" name="amount_value[]" id="amount_value_1" class="form-control"
                        autocomplete="off">
                    </td>
                    <td><button type="button" class="btn btn-default" onclick="removeRow('1')"><i
                          class="fa fa-close"></i></button></td>
                    <input type="hidden" name="qty[]" id="qty_1" class="form-control" value="1" required
                      onkeyup="getTotal(1)">
                  </tr>
                </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">Montant brut</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" id="gross_amount" name="gross_amount" disabled
                      autocomplete="off">
                    <input type="hidden" class="form-control" id="gross_amount_value" name="gross_amount_value"
                      autocomplete="off">
                  </div>
                </div>
                <!-- <//?php if ($is_service_enabled == true): ?>
                  <div class="form-group">
                    <label for="service_charge" class="col-sm-5 control-label">S-Charge <//?php echo $company_data['service_charge_value'] ?> %</label>
                    <div class="col-sm-7">
                      <input type="text" class="form-control" id="service_charge" name="service_charge" disabled autocomplete="off">
                      <input type="hidden" class="form-control" id="service_charge_value" name="service_charge_value" autocomplete="off">
                    </div>
                  </div>
                <//?php endif; ?>
                <//?php if ($is_vat_enabled == true): ?>
                  <div class="form-group">
                    <label for="vat_charge" class="col-sm-5 control-label">T.V.A <//?php echo $company_data['vat_charge_value'] ?> %</label>
                    <div class="col-sm-7">
                      <input type="text" class="form-control" id="vat_charge" name="vat_charge" disabled autocomplete="off">
                      <input type="hidden" class="form-control" id="vat_charge_value" name="vat_charge_value" autocomplete="off">
                    </div>
                  </div>
                <//?php endif; ?> -->
                <div class="form-group">
                  <label for="discount" class="col-sm-5 control-label">Rabais</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" id="discount" name="discount" placeholder="Discount"
                      onkeyup="subAmount()" autocomplete="off">
                  </div>
                </div>
                <div class="form-group">
                  <label for="net_amount" class="col-sm-5 control-label">Montant net</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" id="net_amount" name="net_amount" disabled
                      autocomplete="off">
                    <input type="hidden" class="form-control" id="net_amount_value" name="net_amount"
                      autocomplete="off">
                  </div>
                </div>



              </div>
            </div>
            <!-- /.box-body -->

            <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">
              <button type="submit" class="btn btn-primary">Créer une commande</button>
              <a href="<?php echo base_url('orders/') ?>" class="btn btn-warning">Retour</a>
            </div>
          </form>
          <!-- /.box-body -->
        </div>
        <!-- /.box -->
      </div>
      <!-- col-md-12 -->
    </div>
    <!-- /.row -->


  </section>
  <!-- /.content -->
</div>
<!-- /.content-wrapper -->

<script type="text/javascript">
  var base_url = "<?php echo base_url(); ?>";

  $(document).ready(function () {
    $(".select_group").select2();
    // $("#description").wysihtml5();

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

    var btnCust = '<button type="button" class="btn btn-secondary" title="Add picture tags" ' +
      'onclick="alert(\'Call your custom code here.\')">' +
      '<i class="glyphicon glyphicon-tag"></i>' +
      '</button>';

    // Add new row in the table 
    $("#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) {

          // console.log(reponse.x);
          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) {
            if (value.product_sold == false) {
              html += '<option value="' + value.id + '">' + value.sku + ' | ' + value.name + ' | ' + value.numero_de_moteur + ' | ' + value.puissance + '</option>';
            } else {
              html += '<option value="' + value.id + '" disabled>' + value.sku + ' | ' + value.name + ' | ' + value.numero_de_moteur + ' | ' + value.puissance + '< span style = "background-color: #dc3545; color: #ffffff; padding: 2px 5px; border-radius: 5px;" > (Rupture de stock) < /span></option>';
            }
          });

          html += '</select>' +
            '</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"></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;
    });
  }); // /document

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

      subAmount();

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

  // get the product information from the server
  function getProductData(row_id) {
    var product_id = $("#product_" + row_id).val();
    if (product_id == "") {
      $("#rate_" + row_id).val("");
      $("#rate_value_" + row_id).val("");

      $("#qty_" + row_id).val("");

      $("#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) {
          // setting the rate value into the rate input field

          $("#rate_" + row_id).val(response.prix_vente);
          $("#rate_value_" + row_id).val(response.prix_vente);

          $("#qty_" + row_id).val(1);
          $("#qty_value_" + row_id).val(1);

          var total = Number(response.prix_vente) * 1;
          total = total.toFixed(2);
          $("#amount_" + row_id).val(total);
          $("#amount_value_" + row_id).val(total);

          subAmount();
        } // /success
      }); // /ajax function to fetch the product data 
    }
  }

  // calculate the total amount of the order
  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);

      totalSubAmount = Number(totalSubAmount) + Number($("#amount_" + count).val());
    } // /for

    totalSubAmount = totalSubAmount.toFixed(2);

    // sub total
    $("#gross_amount").val(totalSubAmount);
    $("#gross_amount_value").val(totalSubAmount);

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

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

    // total amount
    var totalAmount = (Number(totalSubAmount));
    totalAmount = totalAmount.toFixed(2);
    // $("#net_amount").val(totalAmount);
    // $("#totalAmountValue").val(totalAmount);

    var discount = $("#discount").val();
    if (discount) {
      var grandTotal = Number(totalAmount) - Number(discount);
      grandTotal = grandTotal.toFixed(2);
      $("#net_amount").val(grandTotal);
      $("#net_amount_value").val(grandTotal);
    } else {
      $("#net_amount").val(totalAmount);
      $("#net_amount_value").val(totalAmount);

    } // /else discount 

  } // /sub total amount

  function removeRow(tr_id) {
    $("#product_info_table tbody tr#row_" + tr_id).remove();
    subAmount();
  }
  function formatAllNumbers() {
    // Sélecteur pour tous les inputs que tu veux formater
    const inputs = document.querySelectorAll('input[type="text"], input[disabled]');

    inputs.forEach(input => {
        if (input.value && !isNaN(input.value.replace(/\s/g, ''))) {
            let val = input.value.replace(/\s/g, '');
            input.value = Number(val).toLocaleString('fr-FR'); // ajoute les espaces tous les 3 chiffres
        }
    });
}

// Appel après que la page et le DOM sont chargés
document.addEventListener('DOMContentLoaded', () => {
    formatAllNumbers();
});

console.log('%c🚀 MODE EDIT AS NEW ACTIVÉ', 'color: green; font-weight: bold; font-size: 16px;');

// DEBUG: Afficher les données reçues
var orderData = <?= json_encode($existing_order ?? []) ?>;
var itemsData = <?= json_encode($existing_items ?? []) ?>;

console.log('📦 Order Data:', orderData);
console.log('📦 Items Data:', itemsData);
console.log('📊 Nombre de produits:', itemsData.length);

$(document).ready(function() {
  
  // ============================================
  // ÉTAPE 1: PRÉ-REMPLIR LES CHAMPS CLIENT
  // ============================================
  console.log('✅ Étape 1: Pré-remplissage des champs client');
  
  $('#customer_name').val('<?= esc($existing_order['customer_name'] ?? '') ?>');
  $('#customer_address').val('<?= esc($existing_order['customer_address'] ?? '') ?>');
  $('#customer_phone').val('<?= esc($existing_order['customer_phone'] ?? '') ?>');
  $('#customer_cin').val('<?= esc($existing_order['customer_cin'] ?? '') ?>');
  
  var originalDiscount = parseFloat('<?= $existing_order['discount'] ?? 0 ?>') || 0;
  if (originalDiscount > 0) {
    $('#discount').val(originalDiscount);
    console.log('💰 Rabais appliqué:', originalDiscount);
  }
  
  // ============================================
  // ÉTAPE 2: NETTOYER LE TABLEAU
  // ============================================
  console.log('✅ Étape 2: Nettoyage du tableau');
  $('#product_info_table tbody').empty();
  
  // ============================================
  // ÉTAPE 3: CHARGER LES PRODUITS
  // ============================================
  <?php if (isset($existing_items) && !empty($existing_items)): ?>
    console.log('✅ Étape 3: Chargement de ' + itemsData.length + ' produit(s)');
    
    // Fonction de formatage
    function formatNumber(num) {
      return parseFloat(num).toLocaleString('fr-FR', {
        minimumFractionDigits: 0,
        maximumFractionDigits: 2
      });
    }
    
    // Charger chaque produit
    itemsData.forEach(function(item, index) {
      var rowId = index + 1;
      console.log('🔄 Chargement ligne ' + rowId + ':', item);
      
      // CONSTRUIRE LA LIGNE HTML
      var html = '<tr id="row_' + rowId + '">';
      
      // COLONNE 1: SELECT PRODUIT
      html += '<td>';
      html += '<select class="form-control select_group product" ';
      html += 'data-row-id="' + rowId + '" ';
      html += 'id="product_' + rowId + '" ';
      html += 'name="product[]" ';
      html += 'style="width:100%;" ';
      html += 'onchange="getProductData(' + rowId + ')" required>';
      html += '<option value="">Sélectionner...</option>';
      
      // OPTIONS DES PRODUITS
      <?php foreach ($products as $p): ?>
        <?php if ($p['product_sold'] == 0): ?>
          html += '<option value="<?= $p['id'] ?>"';
          if (item.product_id === <?= $p['id'] ?>) {
            html += ' selected="selected"';
            console.log('  ✓ Produit trouvé: <?= esc($p['name']) ?> (ID: <?= $p['id'] ?>)');
          }
          html += '>';
          html += '<?= esc($p['sku']) ?> | <?= esc($p['name']) ?> | ';
          html += '<?= esc($p['numero_de_moteur']) ?> | <?= esc($p['puissance']) ?>';
          html += '</option>';
        <?php endif; ?>
      <?php endforeach; ?>
      
      html += '</select></td>';
      
      // COLONNE 2: PRIX UNITAIRE
      html += '<td>';
      html += '<input type="text" name="rate[]" ';
      html += 'id="rate_' + rowId + '" ';
      html += 'class="form-control" disabled ';
      html += 'value="' + formatNumber(item.rate) + '">';
      html += '<input type="hidden" name="rate_value[]" ';
      html += 'id="rate_value_' + rowId + '" ';
      html += 'value="' + item.rate + '">';
      html += '</td>';
      
      // COLONNE 3: MONTANT
      html += '<td>';
      html += '<input type="text" name="amount[]" ';
      html += 'id="amount_' + rowId + '" ';
      html += 'class="form-control" disabled ';
      html += 'value="' + formatNumber(item.amount) + '">';
      html += '<input type="hidden" name="amount_value[]" ';
      html += 'id="amount_value_' + rowId + '" ';
      html += 'value="' + item.amount + '">';
      html += '</td>';
      
      // COLONNE 4: BOUTON SUPPRIMER
      html += '<td>';
      html += '<button type="button" class="btn btn-default" ';
      html += 'onclick="removeRow(\'' + rowId + '\')">';
      html += '<i class="fa fa-close"></i></button>';
      html += '</td>';
      
      // QTY CACHÉ (toujours 1 pour les motos)
      html += '<input type="hidden" name="qty[]" ';
      html += 'id="qty_' + rowId + '" ';
      html += 'value="' + item.qty + '" ';
      html += 'required onkeyup="getTotal(' + rowId + ')">';
      
      html += '</tr>';
      
      // AJOUTER AU TABLEAU
      $('#product_info_table tbody').append(html);
      console.log('  ✓ Ligne ' + rowId + ' ajoutée au DOM');
    });
    
    // ============================================
    // ÉTAPE 4: INITIALISER SELECT2 ET RECALCULER
    // ============================================
    console.log('✅ Étape 4: Finalisation');
    
    setTimeout(function() {
      // Initialiser Select2
      if ($.fn.select2) {
        $('.product').select2();
        console.log('  ✓ Select2 initialisé');
      }
      
      // Recalculer les montants
      if (typeof subAmount === 'function') {
        subAmount();
        console.log('  ✓ Montants recalculés');
      }
      
      // Formater les nombres
      if (typeof formatAllNumbers === 'function') {
        formatAllNumbers();
        console.log('  ✓ Nombres formatés');
      }
      
      console.log('%c🎉 CHARGEMENT TERMINÉ AVEC SUCCÈS!', 'color: green; font-weight: bold; font-size: 14px;');
      
      // Vérification finale
      var rowCount = $('#product_info_table tbody tr').length;
      console.log('📊 Nombre de lignes dans le tableau:', rowCount);
      
    }, 500);
    
  <?php else: ?>
    console.warn('⚠️ Aucun produit à charger');
  <?php endif; ?>
  
});
</script>