<?= $this->extend('layouts/main.php') ?>

<?= $this->section('content') ?>
<?php
if(!isset($productaliasid)) { $productaliasid=''; }
if(!isset($areaid)) { $areaid=''; }
if(!isset($producttypeid)) { $producttypeid=''; }
if(!isset($sitename)) { $sitename=''; }
?>
<div class="page-wrapper">
	<div class="container-fluid">
		
		<div class="row page-titles">
			<div class="col-md-5 align-self-center">
				<h4 class="text-themecolor">Products Management Page</h4>
			</div>
			<div class="col-md-7 align-self-center text-end">
				<a class='btn btn-info text-white btn-sm' href='products/create/' 
					onclick="window.open(this.href, 'Create Site','width=900,height=600,toolbar=1,resizable=0'); return false;">
					<i class="fas fa-plus-circle"></i> Create
				</a>
			</div>
		</div>
		
		<div class="row">
			<div class="col-12">
				<div class="card">
					<div class="card-body">
						<form method='post' >
							<div class='row mb-2'>
								<div class="col-md-6">
									<div class="form-group">
										<label for="open" class="form-label border-start border-5 border-primary ps-1">Product Alias</label>
										<select name='productaliasid' id='productaliasid' class='form-select form-select-sm select2' >
											<option value='0'>-</option>
											<?php
												foreach($productalias as $data) {
													$qproductaliasid = $data['productaliasid'];
													$qproductaliastext = $data['productaliastext'];
													if($productaliasid == $qproductaliasid) { echo "<option value='$qproductaliasid' selected>$qproductaliastext</option>"; }
													else { echo "<option value='$qproductaliasid'>$qproductaliastext</option>"; }
												}
											?>
										</select>
									</div>
								</div>
								<div class="col-md-6">
									<div class="form-group">
										<label class="form-label border-start border-5 border-primary ps-1">Area</label>
										<select name='areaid' id='areaid' class='form-select form-select-sm'>
											<option value=''>-</option>
											<?php
												foreach($areas as $data) {
													$qareaid = $data['areaid'];
													$qareaname = $data['areaname'];
													if($areaid == $qareaid) { echo "<option value='$qareaid' selected>$qareaname</option>"; }
													else { echo "<option value='$qareaid'>$qareaname</option>"; }
												}
											?>
										</select>
									</div>
								</div>
							</div>
							<div class='row mb-2'>
								<div class="col-md-6">
									<div class="form-group">
										<label class="form-label border-start border-5 border-primary ps-1">Product Type</label>
										<select name='producttypeid' id='producttypeid' class='form-select form-select-sm'>
											<option value=''>-</option>
											<?php
												foreach($producttype as $data) {
													$qproducttypeid = $data['producttypeid'];
													$qproducttypename = $data['texts'];
													if($producttypeid == $qproducttypeid) { echo "<option value='$qproducttypeid' selected>$qproducttypename</option>"; }
													else { echo "<option value='$qproducttypeid'>$qproducttypename</option>"; }
												}
											?>
										</select>
									</div>
								</div>
								<div class="col-md-6">
									<div class="form-group">
										<label class="form-label border-start border-5 border-primary ps-1">Sitename</label>
										<input type='text' class='form-control form-control-sm' name='sitename' id='sitename' value='<?=$sitename;?>'/>
									</div>
								</div>
							</div>
							<button type="submit" class="btn btn-success text-white"> <i class="fa fa-search"></i> Search</button>
						</form>
					</div>
				</div>
			</div>
		</div>
		
		<?php if(isset($products)) { ?>
		<div class="row">
			<div class="col-12">
				<div class="card">
					<div class="card-body">
						
						<button onclick="exportToExcel()" class="btn btn-success btn-xs text-white float-end"> <i class="fa fa-file-excel"></i> &nbsp;EXCEL </button>
						<div class="table-responsive">
							<table id="myTable" class="table display table-striped border">
								<thead class="text-center">
									<th>ID</th> <th>Site (Owner)</th> <th>Province</th> <th>Kab/Kota</th> <th>Product Name</th> <th>Install Date</th> <th>Monthly Production</th> <th>Action</th>
								</thead>
								<tbody>
									<?php
									foreach($products as $data) {
										$productid = $data['productid'];
										$sitename = $data['sitename'];
										$productname = $data['productname'];
										$productnumber = $data['productnumber'];
										$productaliasid = $data['productaliasid'];
										$accountname = $data['accountname'];
										$city = $data['city'];
										$prov = $data['prov'];

										if( $data['installationdate'] != '' ) {
											$installationdate = $data['installationdate'];
											$date = new DateTime($installationdate);
											$installationdate = $date->format('M d, Y');
										} else { $installationdate = ''; }

										if ($data['active'] == '2') {
											$bg='bg-danger';
										} else {
											$bg='';
										}
										
										/* if( $data['createdate'] != '' ) {
											$createdate = date('d-m-Y', strtotime($data['createdate']));
										} else { $createdate = ''; } */
									?>
									<tr class='<?php echo($bg); ?>'> 
										<td><?=$productid;?></td> 
										<td><?=$sitename;?> <br /> <?php if($accountname != '') { echo "($accountname)";}?></td> 
										<td><?=$prov;?></td> 
										<td><?=$city;?></td> 
										<td><?=$productname;?><?php if(isset($productnumber)) { echo "<br/>SN : $productnumber" ;} ?></td> 
										<td><?=$installationdate;?></td>
										
										<!-- Untuk CLQMS -->
										<td class="text-end">
											<?php if ($productaliasid == '20') { ?>
												<div class="text-end col-12 mb-1">
													<span class="badge bg-danger fw-bold fs-7">
														Dalam Perbaikan
													</span>
													<?php 
													// if (isset($testCountCLQMS)) { 
														
													// 	foreach ($testCountCLQMS as $key => $value) {
													// 		if ($key == $productnumber) {
													// 			$valueF = (float) $value;
													// 			$valueF = $valueF / 6;
													// 			$valueF = round($valueF, 1);
													// 			$formatted_number = number_format($valueF, 1, '.', ',');
													// 			echo "<span class='badge bg-danger fw-bold fs-4'>";
													// 			echo "$formatted_number";
													// 			echo " </span> ";
													// 		}
													// 	}
													// }
													?>
												</div>
												<div class="col-12 text-end">
													<span class="badge bg-info fw-bold fs-7">
														Dalam Perbaikan
													</span>
												</div>
											<?php } ?>
										</td>

										<td class='text-center'>
											<div class='row'>
												<div class='col'>
													<button type='button' class='btn btn-success btn-sm openViewProduct' data-productid='<?=$productid;?>'><i class="fas fa-eye"></i> View</button>
												</div>
												<div class='col'>
													<select class='form-select form-select-sm' name="action" onchange="action(this)">
														<option value="" selected> - </option>
														<option value="products/edit/<?=$productid;?>">Edit</option>
														<option value="products/movesite/<?=$productid;?>">Move Site</option>
														<option value="products/changeowner/<?=$productid;?>">Change Owner</option>
														<option value="products/upgrade/<?=$productid;?>">Upgrade Product</option>
													</select>
												</div>
											</div>
										</td>
									</tr>
									<?php } ?>
								</tbody>
							</table>
						</div>
					
					</div>
				</div>
			</div>
		</div>
		<div id="modal" class="modal" tabindex="-1" role="dialog" aria-labelledby="tooltipmodel" aria-hidden="true">
			<div class="modal-dialog modal-dialog-centered modal-xl">
				<div class="modal-content">
				</div>
			</div>
		</div>
		<?php } ?>
	</div>
</div>
<?= $this->endSection() ?>

<?= $this->section('script') ?>
<script>
$(function () {
	$('.select2').select2({
		theme: 'bootstrap-5',
		width: '100%'
	});
	
	$('#myTable').DataTable({
		"order" : []
	});
});

$('.openViewProduct').on('click',function(){
	const productid = $(this).data('productid');
	$('.modal-content').load('<?=base_url();?>/products/view/'+productid,function(){
		$('#modal').modal('show');
	});
});

function productslog_delete(logid) {
	if (confirm("Are you sure?")) {
		$.post("<?=base_url();?>/products/log/delete", { logid : logid }, function(data, status){
			console.log("Data: " + data +  logid + "\nStatus: " + status);
		});
	}
}

function action(e){
	//console.log(e.value);
	window.open(e.value);
}

// function exportToExcel() {
//     // Ambil seluruh data dari DataTables
//     const table = $('#myTable').DataTable();
//     const allData = table.rows().data().toArray(); // Mengambil semua data dalam bentuk array

//     // Ambil nama kolom dari header tabel
//     const headers = [];
//     $('#myTable thead th').each(function () {
//         headers.push($(this).text()); // Ambil teks header
//     });

//     // Buat elemen tabel baru untuk ekspor
//     const tempTable = document.createElement("table");

//     // Tambahkan header ke tabel sementara
//     const headerRow = tempTable.insertRow();
//     headers.forEach((header) => {
//         const cell = headerRow.insertCell();
//         cell.textContent = header; // Isi header
//     });

//     // Fungsi untuk menghapus HTML
//     function removeHtmlTags(input) {
//         return input.replace(/<\/?[^>]+(>|$)/g, ""); // Hapus semua elemen HTML
//     }

//     // Tambahkan data baris ke tabel sementara
//     allData.forEach((rowData) => {
//         const row = tempTable.insertRow();
//         rowData.forEach((cellData) => {
//             const cell = row.insertCell();

//             // Hapus elemen HTML dari data
//             let processedValue = removeHtmlTags(cellData);
//             cell.textContent = processedValue; // Isi data sel
//         });
//     });

//     // Konversi tabel sementara ke worksheet
//     var ws = XLSX.utils.table_to_sheet(tempTable);

// 	// Modifikasi jika diperlukan (contoh: menyembunyikan kolom ke-7)
//     ws["!cols"] = [];
//     ws["!cols"][7] = { hidden: true }; // Sembunyikan kolom ke-7

//     // Ekspor ke Excel
//     var wb = XLSX.utils.book_new();
//     XLSX.utils.book_append_sheet(wb, ws, "Sheet 1");
//     XLSX.writeFile(wb, "ActivityList.xlsx");
// }

function exportToExcel() {
	
	const productaliasid = $('#productaliasid').val();
	const areaid = $('#areaid').val();
	const producttypeid = $('#producttypeid').val();
	const sitename = $('#sitename').val();

	const url = `<?=base_url();?>products/export?productaliasid=${encodeURIComponent(productaliasid)}&areaid=${encodeURIComponent(areaid)}&producttypeid=${encodeURIComponent(producttypeid)}&sitename=${encodeURIComponent(sitename)}`;
	window.open(url, '_blank');
}

</script>
<?= $this->endSection() ?>