	
		<div class="page-wrapper">
    <form action="store" method="post" enctype='multipart/form-data'>

<div class="page-content">

<div class="d-flex justify-content-between align-items-center flex-wrap grid-margin">
<div>
<h4 class="mb-3 mb-md-0">Create Invoice</h4>
</div>
<div class="d-flex align-items-center flex-wrap text-nowrap">
<div class="input-group date datepicker dashboard-date mr-2 mb-2 mb-md-0 d-md-none d-xl-flex" >
  <span class="input-group-addon "><i data-feather="calendar" class=" text-primary"></i></span>
  <input  type="date" class="form-control" id="tanggal_order" name="tanggal_order" autocomplete="off">
        
</div>

</div>
</div>




<div class="row">
        <div class="col-lg-6 grid-margin stretch-card">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">Invoice Details</h4>
                    <p class="card-description"></p>
                        <fieldset>
        <div class="form-group">
        <select class="form-control" id="client" name="client" style="width:80%;"  required>
        <option value=""></option>
        </select>
          <button id="refreshClientData" class="btn btn-outline-primary btn-icon" type="button"><i data-feather="refresh-ccw"></i></button><button id="modalclientbtn" class="btn btn-outline-primary btn-icon" type="button" style="margin-left: 5px;" data-toggle="modal" data-target="#modalclient"><i data-feather="plus"></i></button>
        </div>    
                            <div class="form-group">
                                <label for="customer_name">Customer Name</label>
          <input type="text" class="form-control" id="customer_name" name="customer_name" placeholder="Enter Customer Name" autocomplete="off" / required>
                            </div>
                            
                            <div class="form-group">
                                <label for="customer_phone">Customer Phone</label>
          <input type="text" class="form-control" id="customer_phone" name="customer_phone" placeholder="Enter Customer Phone" autocomplete="off" required>
                            </div>

        <div class="form-group">
                                <label for="customer_address">Customer Address</label>

          <textarea id="customer_address" name="customer_address" class="form-control" maxlength="100" rows="8" placeholder="Enter Customer Address"></textarea>

                            </div>
                        </fieldset>
                </div>
            </div>
        </div>
        <div class="col-lg-6 grid-margin stretch-card">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">Order Details</h4>
                    <p class="card-description"></p>
                    <fieldset>

        <div class="form-group">
          <label for="customer_name">Status Order</label>
          <select type="text" class="form-control" id="status_order" name="status_order">

              <option value="1">Belum Siap Produksi</option>

              <option value="2">Siap Produksi</option>

            </select>
        </div>    
                            
                        
                            <div class="form-group">
                                <label for="cat_order">Kategori Order</label>
          <select type="text" class="form-control" id="cat_order" name="cat_order">
            <option value="1">Retail</option>
            <option value="0">Mass-Production</option>
          </select>										
        </div>

        <div class="form-group">
                                <label for="cat_order2">Layanan Order</label>
          <select type="text" class="form-control" id="cat_order2" name="cat_order2">
            <option value="0">Regular</option>
            <option value="1">Sameday</option>
          </select>										
        </div>
        <div class="form-group">
                                <label for="type_produksi">Jenis Produksi</label>
          <select type="text" class="form-control" id="type_produksi" name="type_produksi">
            <option value="0">Order Baru</option>
            <option value="1">Pergantian Reject</option>
          </select>										
        </div>


                        </fieldset>
                </div>
            </div>
        </div>
    </div>


        <div class="row">
          <div class="col-12 col-xl-12 grid-margin stretch-card">
            <div class="card">
                <div class="card-body">
                    <h6 class="card-title">Product Details</h6>
                        
                      <div class="container-fluid w-100">
                        <br/></br>
                        <div class="table-responsive">
                          <table id="order_items" class="table table-hover">
                              <tr>
                                  <th style="width:10%">Image</th>
                                  <th style="width:15%">Product</th>
                                  <th style="width:15%">File Name</th>
                                  <th style="width:5%">Width</th>
                                  <th style="width:5%">Length</th>
                                  <th style="width:8%">Qty</th>
                                  <th style="width:7%">Total(m)</th>
                                  <th style="width:15%">Price</th>
                                  <th style="width:15%">Amount</th>
                                  <th style="width:5%"><button type="button" id="add_row" class="btn btn-outline-primary btn-icon float-right mt-1"><i data-feather="plus"></i></button></th>

                              </tr>

                            
                              
                          </table>
                        </div>
                      </div>

                      <div class="container-fluid w-100" >
                        <div class="row">
                          <div class="col-md-6" style="margin-left:auto!important;">
                              <div class="table-responsive">
                                <table id="total" class="table">
                                    <tbody>
                                      <tr>
                                        <td>Sub Total</td>
                                        <td class="text-end"><p id="subtotal"></p></td>
                                      </tr>
                                      <tr>
                                        <td>TAX (0%)</td>
                                        <td class="text-end">0</td>
                                      </tr>
                                      <tr>
                                        <td>Paid</td>
                                        <td class="text-end"><p id="paid"></p></td>
                                      </tr>                                    
                                      <tr class="bg-light">
                                        <td class="text-bold-800">Total</td>
                                        <td class="text-bold-800 text-end"><p id="subtotal2"></p></td>
                                      </tr>
                                    </tbody>
                                </table>
                              </div>
                          </div>
                        </div>
                      </div>
                    <!--- Card Body END -->
                </div>
            </div>
        </div>

       

    </div>

    <div class="row">
          <div class="col-12 col-xl-12 grid-margin stretch-card">
                    <div class="card">
                        <div class="card-body">
                            <h6 class="card-title">Payment Details</h6>
                                
                            <div class="mb-3">
                              <div class="form-group">
                                <label for="paid_status" class="form-label">Payment Status</label>
                                <select required class="form-select" id="paid_status" name="paid_status">
                                  <option value="2">Unpaid</option>
                                  <option value="1">Paid</option>
                                  
                                  <option value="3">Partial</option>
                                
                                </select>
                              </div>
                              <div class="form-group">
                              <label for="payment_amount" class="form-label">Payment Amount</label>
                              <input type="text" class="form-control" id="payment_amount" value="0" onkeyup="subAmount()" name="payment_amount" placeholder="Enter Payment Amount" autocomplete="off" / required>
                              </div>
                              <div class="form-group">
                              <label for="image_payment" class="form-label">Payment Image</label>
                              <input type="file" name="image_payment" id="image_payment"  class="dropify" style="border:1px solid #e9ecef;border-radius:.25rem;max-width:100%;" >

                              </div>
                            </div>
               
                              
                            <!--- Card Body END -->
                        </div>
                    </div>
            </div>
        </div>
    <!---ROW END -->
    <button class="btn btn-primary w-100" type="submit">Simpan</button>

</div>


</form>

<style>.dropify-wrapper{border:1px solid #e9ecef;border-radius:.25rem;max-width:70px;}
.dropify-wrapper .dropify-message span.file-icon{font-size:.875rem;color:#7987a1}
.dropify-wrapper .dropify-message span.file-icon::before{font-family:feather;content:"\e8e3";font-size:24px}
.table td{
    padding-left: 5px;
    padding-right: 5px;
}

.custom-dropify .dropify-wrapper {
    border: 1px solid #e9ecef;
    border-radius: .25rem;
    max-width: 70px;
}
.custom-dropify .dropify-wrapper .dropify-message span.file-icon {
    font-size: .875rem;
    color: #7987a1;
}
.custom-dropify .dropify-wrapper .dropify-message span.file-icon::before {
    font-family: feather;
    content: "\e8e3";
    font-size: 24px;
}

</style>
<!-- partial:partials/_footer.html -->
<script>

    // Menangkap elemen dropdown status_order
      var paymentDropdown = document.getElementById('paid_status');
      var paymentAmountInput = document.getElementById('payment_amount');
      var paymentAmountFormGroup = paymentAmountInput.closest('.form-group');
      paymentAmountFormGroup.style.display = 'none';

      paymentDropdown.addEventListener('change', function() {
          // Mengatur nilai payment_amount menjadi 0 setiap kali dropdown diubah
          paymentAmountInput.value = '0';

          // Menampilkan atau menyembunyikan form group berdasarkan nilai dropdown
          if (this.value === '1' || this.value === '3') {
              paymentAmountFormGroup.style.display = 'block';
          } else {
              paymentAmountFormGroup.style.display = 'none';
          }
      });


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

$.ajax({
    url:'<?= site_url('products/getproducts') ?>',
    type: 'post',
    dataType: 'json',
    success:function(response) {
        // console.log(reponse.x);
         var html = '<tr id="row_'+row_id+'">'+
        '<td><input type="file" name="image[]" id="image_'+row_id+'" data-height="50" data-default-file="https://is3.cloudhost.id/texapp/order_items/1712926011_c6fa6b3e880d20152561.jpg"></td>'+
        '<td>'+ 
              '<select class="form-control select_group product" data-row-id="'+row_id+'" id="product_'+row_id+'" name="product_id[]" style="width:100%;" onchange="getProductData('+row_id+')" required>'+
                  '<option value=""></option>';
                  $.each(response, function(index, value) {
                    html += '<option value="'+value.id+'">'+value.name+'</option>';             
                  });
              html += '</select>'+
        '</td>'+ 
        '<td><textarea name="details[]" id="details_'+row_id+'" maxlength="100" rows="4" class="form-control"></textarea></td>'+
        '<td><input required type="text" name="width[]" id="width_'+row_id+'" class="form-control"></td>'+
        '<td><input required type="text" name="length[]" id="length_'+row_id+'" class="form-control" onkeyup="getQTY('+row_id+')"></td>'+
        '<td><input  requiredtype="text" name="pcs[]" id="pcs_'+row_id+'" class="form-control" onkeyup="getQTY('+row_id+')"></td>'+
        '<td><input required type="text" readonly name="qty[]" id="qty_'+row_id+'" class="form-control" onchange="getQTY('+row_id+')"><input type="hidden" name="hasilqc[]" id="hasilqc_'+row_id+'" class="form-control" value="0" onkeyup="getQTY(1)"><input type="hidden"  name="totalqc[]" id="totalqc_'+row_id+'" class="form-control" value="0" onkeyup="getQTY(1)"></td>'+
        '<td><input required type="hidden" name="rate[]" id="rate_'+row_id+'" class="form-control" disabled><input type="number" name="rate_value[]" id="rate_value_'+row_id+'" class="form-control" onkeyup="getQTY('+row_id+')"><select class="form-control select_group" data-row-id="'+row_id+'" id="type_'+row_id+'" name="type[]" onchange="getQTY('+row_id+')" style="width:100%;"  required><option value="meter">Meter</option><option value="pcs">pcs</option></select></td>'+
        '<td><input required 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-outline-primary btn-icon float-right mt-1" onclick="removeRow(\''+row_id+'\')">X</button></td>'+
        
        '</tr>';
          if(count_table_tbody_tr >= 1) {
          $("#order_items tbody tr:last").after(html);  
  }

        else {
          $("#order_items tbody").html(html);
        }
        $(".product").select2();
        $("#image_"+row_id).dropify({
          previewWidth: 50,
          previewHeight: 50});
    }
  });
 
return false;

});



function getQTY(row = null) {

  if(row) {
    console.log($("#type_"+row).val())
    var tempqty = Number($("#length_"+row).val()) * Number($("#pcs_"+row).val());
    tempqty = tempqty.toFixed(2);
    $("#qty_"+row).val(tempqty);
    var temphasilqc = (Number($("#length_"+row).val()) * Number($("#reject_"+row).val())) + (Number($("#length_"+row).val()) * Number($("#hasilqc_"+row).val()));
    temphasilqc = temphasilqc.toFixed(2);
    $("#totalqc_"+row).val(temphasilqc);
   // Perhitungan total berdasarkan nilai type_
   var type = $("#type_"+row).val();
    var total;
    if (type === 'meter') {
        total = Number($("#rate_value_"+row).val()) * tempqty;
    } else if (type === 'pcs') {
        total = Number($("#rate_value_"+row).val()) * Number($("#pcs_"+row).val());
    }
    total = total.toFixed(2);
    $("#amount_"+row).val(total);
    $("#amount_value_"+row).val(total);
    subAmount();
  } else {
    alert('no row !! please refresh the page');
  }
}
function removeRow(tr_id)

  {

    $("#order_items  tbody tr#row_"+tr_id).remove();

    subAmount();

  }


function subAmount() {





var tableProductLength = $("#order_items tbody tr").length;

var totalSubAmount = 0;
var paidamount = Number($("#payment_amount").val());
for(x = 0; x < tableProductLength; x++) {
  var tr = $("#order_items tbody tr")[x];
  var count = $(tr).attr('id');
  if (count && count.length > 4) {
            count = count.substring(4);
            totalSubAmount += parseFloat($("#amount_" + count).val()) || 0;
        }
} // /for
totalSubAmount = totalSubAmount.toFixed(2);
var totalpaid = totalSubAmount - paidamount;
var formattedsubTotal = formatRupiah(totalSubAmount);
var formattedTotal = formatRupiah(totalpaid);
var formattedpaid = formatRupiah(paidamount);
$("#subtotal").text("Rp. " + formattedsubTotal);
$("#subtotal2").text("Rp. " + formattedTotal);
$("#paid").text("Rp. " + formattedpaid);

} // /sub total amount

function formatRupiah(angka) {
    var reverse = angka.toString().split('').reverse().join('');
    var ribuan = reverse.match(/\d{1,3}/g);
    var formatted = ribuan.join('.').split('').reverse().join('');
    return formatted;
}
function addOrderItem() {
var table = document.getElementById("order_items");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3); // Added cell for image upload
var cell5 = row.insertCell(4); // Added cell for remove button
var cell6 = row.insertCell(5); // Added cell for remove button


var productIdSelectId = 'products_' + Math.floor(Math.random() * 1000000);

// Add more cells as needed
cell1.innerHTML = '<select class="form-control" id="' + productIdSelectId + '" name="product_id[]"><option value="1">Product 1</option><option value="2">Product 2</option></select>';
cell2.innerHTML = '<input type="text" name="item_code[]">';
cell3.innerHTML = '<input type="number" name="qty[]">';
cell4.innerHTML = '<input type="text" name="rate[]">';
cell5.innerHTML = '<input type="file" class="dropify border" name="image[]">'; // Added file input for image
cell6.innerHTML = '<button type="button" class="btn btn-outline-primary btn-icon" onclick="removeOrderItem(this)">X</button>'; // Added remove button


$('.dropify').dropify();
        // Retrieve product data for the newly added row
$.getJSON("<?= site_url('products/getproducts') ?>", function(data) {
    // Iterasi data dan tambahkan opsi ke select box
    $.each(data, function(key, value) {
        $('#' + productIdSelectId).append('<option value="' + value.id + '">' + value.name + '</option>');
        if (value.price) {
          cell4.innerHTML = value.price; // Update the rate cell with the rate from the product data
      }
    });
});
}

function removeOrderItem(button) {
var row = button.parentNode.parentNode;
row.parentNode.removeChild(row);
}

$(document).ready(function() {
  $(".select_group").select2();
        $.getJSON("<?= site_url('dashboard/client') ?>", function(data) {
            // Iterasi data dan tambahkan opsi ke select box
            $.each(data, function(key, value) {
                $('#client').append('<option value="' + value.client_key + '">' + value.client_name + '</option>');
            });
        });
        $('#client').select2({
            placeholder: 'Pilih Client',
            allowClear: true
        });
        
        $('#refreshClientData').on('click', function() {
            refreshclient();
        });

        $('#client').change(function(){
            getClientData();
        });

        function refreshclient() {
            $('#client').find('option').not(':first').remove();
            $('.overlay').addClass('active');
            $.getJSON("<?= site_url('dashboard/client') ?>", function(data) {
                $.each(data, function(key, value) {
                    $('#client').append('<option value="' + value.client_key + '">' + value.client_name + '</option>');
                });
                $('.overlay').removeClass('active');
                $('#client').val(null).trigger('change');
            });
        }
        function getClientData() {
            var client_key = $("#client").val();
            $("#client").val(client_key);
            if (client_key == "") {
                $("#customer_name").val("");
            } else {
                console.log("Sending AJAX request for client_key:", client_key);

                $.ajax({
                    url: '<?= site_url('dashboard/clientbyid') ?>',
                    type: 'post',
                    data: { client_key: client_key },
                    dataType: 'json',
                    success: function(response) {
                        $("#customer_name").val(response[0].client_name);
                        $("#customer_phone").val(response[0].client_phone);
                        $("#customer_address").val(response[0].client_address);
                        console.log(response);
                    }
                });
            }
        }


});


</script>