    <!-- Main Content -->
    <div class="hk-pg-wrapper">
			<!-- Container -->
			<form action="qcpost" method="post" enctype='multipart/form-data'>
            <div class="container-fluid mt-xl-50 mt-sm-30 mt-15">

            <div class="hk-pg-header mb-10">
                    <div>
						<h4 class="hk-pg-title"><span class="pg-title-icon"><span class="feather-icon"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-activity"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline></svg></span></span>Invoice #<?php echo $result['order']['bill_no'] ?> <?php
                        $type_produksi = $result['order']['type_produksi'];

                        // Periksa apakah nilai $cat_order adalah 1
                        if ($type_produksi == 1) {
                            $badge_label = 'Pergantian Reject';
                            $badge_color = 'danger';
                            echo '<span style="color:white;" class="badge rounded-pill bg-' . $badge_color . '">' . $badge_label . '</span>';
                        }
                        ?></h4>
                    </div>
					<div class="d-flex dropdown">
                    </div>
                </div>

				<!-- Row -->
         
<input type="text" hidden class="form-control" id="id" name="id" value="<?php echo $result['order']['id'] ?>" placeholder="Enter Customer Name" autocomplete="off" / required>
                        <input type="text" hidden class="form-control" id="bill_no" name="bill_no" value="<?php echo $result['order']['bill_no'] ?>" placeholder="Enter Customer Name" autocomplete="off" / required>


<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="mt-1 mb-1"><b><?php echo $result['order']['customer_name'] ?></b></p>
                        <fieldset>
                        <?php echo $result['order']['customer_phone'] ?> <br/>
                        <?php echo $result['order']['customer_address'] ?> <br/>
                        <?php
                        $cat_order = $result['order']['cat_order'];
                        $badge_label = '';
                        $badge_color = '';
                        switch ($cat_order) {
                            case 1:
                                $badge_label = 'Retail';
                                $badge_color = 'light';
                                break;
                            case 0:
                                $badge_label = 'Mass-Production';
                                $badge_color = 'secondary';
                                break;
                            default:
                                $badge_label = 'Unknown';
                                $badge_color = 'danger'; // Anda bisa ganti dengan warna yang sesuai
                                break;
                        }
                        echo '<span class="badge rounded-pill bg-' . $badge_color . '">' . $badge_label . '</span>';
                        ?>
                        <?php
                        $cat_order2 = $result['order']['cat_order2'];
                        $badge_label = '';
                        $badge_color = '';
                        switch ($cat_order2) {
                            case 1:
                                $badge_label = 'Sameday';
                                $badge_color = 'danger';
                                break;
                            case 0:
                                $badge_label = 'Regular';
                                $badge_color = 'secondary';
                                break;
                            default:
                                $badge_label = 'Unknown';
                                $badge_color = 'info'; // Anda bisa ganti dengan warna yang sesuai
                                break;
                        }
                        echo '<span style="color:white;" class="badge rounded-pill bg-' . $badge_color . '  mt-2">' . $badge_label . '</span>';
                        ?>
                        <br/>
                        
           
                        </fieldset>
                        <h4><span class="badge rounded-pill border border-secondary text-secondary mt-2"><b><?php echo $result['order']['tanggal_order'] ?></b></span></h4>
                </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="status_produksi">Status Produksi</label>
                        <select type="text" class="form-control" id="status_produksi" name="status_produksi">
                            <option value="1" <?php if($result['order']['status_produksi'] == 1) { echo "selected='selected'"; } ?>>Siap Dikirim</option>
                            <option value="2" <?php if($result['order']['status_produksi'] == 2) { echo "selected='selected'"; } ?>>Dalam Pengerjaan</option>
                            <option value="3" <?php if($result['order']['status_produksi'] == 3) { echo "selected='selected'"; } ?>>Kirim Parsial</option>     
                        </select>										
                        </div>
                        </fieldset>
                </div>
            </div>
        </div>
    </div>



            
                            <div class="example">
                                <div class="row" >
                                    <?php if(isset($result['order_item'])): ?>
                                    <?php $x = 1; ?>
                                    <?php foreach ($result['order_item'] as $key => $val): ?>
                                    <?php //print_r($v); ?>
                                        <div id="row_<?php echo $x; ?>" class="col-12 col-xl-12 grid-margin stretch-card mb-4">
                                            <div class="card">
                                                <div class="row" >
                                                    <div class="col-lg-2">
                                                   <?php
                                                    $file = $val['image']; // Mengambil path file dari $val['image']
                                                    $file_extension = pathinfo($file, PATHINFO_EXTENSION); // Mendapatkan ekstensi file

                                                    if (in_array($file_extension, array('jpg', 'jpeg', 'png', 'gif'))) {
                                                        // Jika file merupakan gambar, tampilkan gambar
                                                        echo '<img src="' . $file . '" class="card-img-top" alt="...">';
                                                    } else {
                                                        // Jika bukan gambar, tampilkan tombol untuk memuat pratinjau di modal
                                                        echo '<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#previewModal_' . $x . '">Lihat Preview</button>';
                                                    }
                                                    ?>

                                                    </div>
                                                        <div class="col-lg-10  mt-2 mb-1">
                                                            <div class="isi p-2">    
                                                            <h5 class="card-title mt-2 mb-1">
                                                                <?php 
                                                                    $productName = '';
                                                                    foreach($result['product'] as $product) {
                                                                        if($product['id'] == $val['product_id']) {
                                                                            $productName = $product['name'];
                                                                            break;
                                                                        }
                                                                    }
                                                                    echo $productName;
                                                                ?>
                                                            </h5>
                                                            <h6 class="card-subtitle mb-2 text-muted"><?php echo $val['details'] ?></h6>
                                                                <div class="table-responsive">
                                                                    <table class="table table-hover">
                                                                    <tbody>
                                                                        <tr>
                                                                        <th>Ukuran</th>
                                                                        <td><?php echo $val['width'] ?> X <?php echo $val['length'] ?></td>
                                                                        <tr>
                                                                        <tr>
                                                                        <th>Qty</th>
                                                                        <td><?php echo $val['hasilqc'] ?> / <?php echo $val['pcs'] ?> pcs</td>
                                                                        <tr>
                                                                        <tr>
                                                                        <th>Total</th>
                                                                        <td><?php echo $val['totalqc'] ?> / <?php echo $val['qty'] ?> m</td>
                                                                        <tr>
                                                                        <th>Total Reject</th>
                                                                        <td><?php echo $val['reject'] ?> pcs</td>
                                                                        <tr>
                                                                        <th>Hasilqc</th>
                                                                        <td> 
                                                                            <input type="text" name="hasilqc_new[]" id="hasilqc2_<?php echo $x; ?>" class="form-control" value="" autocopmlete="off">
                                                                            <input type="text"hidden name="item_code[]" id="item_code_<?php echo $x; ?>" class="form-control" value="<?php echo $val['item_code'] ?>" autocopmlete="off">
                                                                            <input type="text" hidden name="hasilqc[]" id="hasilqc_<?php echo $x; ?>" class="form-control" value="<?php echo $val['hasilqc'] ?>" autocopmlete="off">
                                                                            <input type="text"hidden name="reject[]" id="reject_<?php echo $x; ?>" class="form-control" value="<?php echo $val['reject'] ?>" autocopmlete="off">
                                                                            <input type="text"hidden name="pcs[]" id="pcs_<?php echo $x; ?>" class="form-control" value="<?php echo $val['pcs'] ?>" autocopmlete="off">
                                                                            <input type="text"hidden name="length[]" id="length_<?php echo $x; ?>" class="form-control" value="<?php echo $val['length'] ?>" autocopmlete="off">

                                                                        </td>
                                                                        <tr>
                                                                        <th>Reject</th>
                                                                        <td><input type="text" name="reject_new[]" id="reject2_<?php echo $x; ?>" class="form-control" value="" autocomplete="off"></td>
                                                                        <tr>
                                                                    </tbody>
                                                                    </table>
                                                                </div>
                                                            </div>
                                                        </div>
                                                </div>        
                                            </div>

                                            <!-- Modal untuk setiap item -->
                                        <div class="modal fade" id="previewModal_<?php echo $x; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                                            <div class="modal-dialog" role="document">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title" id="exampleModalLabel">Pratinjau File</h5>
                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                            <span aria-hidden="true">&times;</span>
                                                        </button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <!-- Embed untuk pratinjau file -->
                                                        <embed id="filePreview_<?php echo $x; ?>" src="<?php echo $file; ?>" class="file-preview" type="application/pdf" style="width: 100%; height: 500px;">
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                                                        </div id="row_<?php echo $x; ?>">
                                    <?php $x++; ?>
                                    <?php endforeach; ?>
                                    <?php endif; ?>
                                </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">Records Details</h6>
                                                        
                                                    <div class="mb-3">
                                                    <div class="container-fluid w-100">
                                                        <div class="table-responsive">
                                                        <table id="history_data" class="table table-hover">
                                                            <tr>
                                                                <th style="width:25%">Nama File</th>
                                                                <th style="width:25%">Tanggal</th>
                                                                <th style="width:25%">Hasil QC</th>
                                                                <th style="width:25%">Reject</th>

                                                            </tr>

                                                            <tbody>

                                                                <?php if(isset($result['history_data'])): ?>
                                                                <?php $x = 1; ?>
                                                                <?php foreach ($result['history_data'] as $key => $val): ?>
                                                                    <?php //print_r($v); ?>
                                                                <tr id="row_<?php echo $x; ?>">
                                                                                <td> 
                                                                                    <?php foreach ($val['details'] as $detail): ?>
                                                                                     <?php echo $detail['details']; ?><br> 
                                                                                <?php endforeach; ?></td>        
                                                                                <td><?php echo date('Y-m-d', $val['date_time']) ?></td>
                                                                                <td><?php echo $val['hasilqc'] ?></td>
                                                                                <td><?php echo $val['reject'] ?></td>                                                     
                                                                </tr>
                                                                <?php $x++; ?>
                                                                <?php endforeach; ?>
                                                                <?php endif; ?>
                                                                </tbody>
                                                            
                                                        </table>
                                                        </div>
                                                    </div>
                                                    
                                                    <!--- Card Body END -->
                                                </div>
                                            </div>
                                    </div>
                                </div>

			
            <!-- /Container -->
			<button class="btn btn-primary w-100" type="submit">Simpan</button>

            <nav class="navbar navbar-light bg-light fixed-bottom navbar-demo">
                              
                                                        <div class="input-group d-inline-flex">
                                                                <span class="btn btn-light"><?php echo $result['order']['bill_no'] ?></span>

                 
                                                            <input type="date" class="form-control" id="tgl_selesai" name="tgl_selesai" value="<?php echo $result['order']['tgl_selesai'] ?>" autocomplete="off">
                                                            <div class="input-group-append">
                                                                <button class="btn btn-dark w-300" type="submit"><i class="fa fa-save my-float"></i> Simpan</button>
                                                            </div>
                                                        </div>
                             
                                            </nav>
       </form>
       <script src="https://texapp.is3.cloudhost.id/api/v2/assets/vendors/sweetalert2/sweetalert2.min.js"></script>
  <script src="https://texapp.is3.cloudhost.id/api/v2/assets/vendors/promise-polyfill/polyfill.min.js"></script> 
<style>.dropify-wrapper{border:1px solid #e9ecef;border-radius:.25rem;max-width:100%;}
.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: 100%;
}
.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;
}
.tgl_selesai {
  min-width: 500px;
}
</style>    

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

$(document).ready(function() {




    const successMessage = '<?php echo session()->getFlashdata("success"); ?>';

    // Jika ada pesan sukses, tampilkan Sweet Alert
    if (successMessage) {
        Swal.fire({
            icon: 'success',
            title: 'Sukses!',
            text: successMessage,
            showConfirmButton: false,
            timer: 3000 // Tampilkan pesan selama 3 detik
        });
    }
    subAmount();
    $('.dropify').dropify();
    // 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" ></td>'+
        '<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+')" required>'+
                  '<option value=""></option>';
                  $.each(response, function(index, value) {
                    html += '<option value="'+value.id+'">'+value.name+'</option>';             
                  });
              html += '</select>'+
        '</td>'+ 
        '<td><input type="hidden" name="imagetext[]" id="imagetext_'+row_id+'" class="form-control" value="" autocomplete="off"><textarea name="details[]" id="details_'+row_id+'" maxlength="100" rows="4" class="form-control"></textarea></td>'+
        '<td><input type="number" name="width[]" id="width_'+row_id+'" class="form-control"></td>'+
        '<td><input type="number" name="length[]" id="length_'+row_id+'" class="form-control" onkeyup="getQTY('+row_id+')"></td>'+
        '<td><input type="number" name="pcs[]" id="pcs_'+row_id+'" class="form-control" onkeyup="getQTY('+row_id+')"></td>'+
        '<td><input type="number" 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 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 type="number" 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 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) {
        var option = '<option value="' + value.client_key + '">' + value.client_name + '</option>';
        // Menambahkan opsi ke dalam select box
        $('#client').append(option);

        // Memeriksa apakah nilai client_key sesuai dengan nilai pada opsi saat ini
        if (value.client_key == <?php echo json_encode($result['order']['client_key']); ?>) {
            // Menetapkan opsi sebagai terpilih jika nilainya cocok
            $('#client').find('option[value="' + value.client_key + '"]').prop('selected', true);
        }
    });
    // Memperbarui tampilan Select2 setelah menambahkan semua opsi
});
$('#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>