<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<?php
	$D_ = "";
	if(isset($_GET['d'])){
		if(!empty($_GET['d'])){
			$D_ = $_GET['d'];
		}
	}
?>
<style>
	@media (max-width:480px){
		.pagination{
			display: inline-block;
		}
		div.dataTables_wrapper div.dataTables_filter input {
			display: block;
			padding-left: 0px !important;
		}
		.installID{
			width: 144% !important;
			margin-left: 1.5% !important;
		}
	}

	#ItemEntry{
		padding-right: 30% !important;
	}

	#myTableOrderModel{
		padding-right: 30% !important;
	}

	#cboPonPort option, #cboSlotID option, #cboServicePort option, #cboPort option { direction: rtl; }
	
</style>
<div class="content-wrapper" style="min-height: 1203.6px;">
	<!-- Content Header (Page header) -->
	<section class="content-header">
		<div class="container-fluid">
		</div>
	</section>
	<section class="content">
		<div class="container-fluid">
			<div class="row">
				
				<div class="col-md-12">

					<div class="card card-outline card-primary">	
		                <div class="card-header">
		                    <h3 class="card-title">Installation</h3>
		                </div>
		                <div class="overlay white" id="loading" style="display:none;position: absolute;width: 100%;height: 100%;z-index: 10000;">
						<i class="fas fa-3x fa-sync-alt rotate360"  style="margin: 20% 48%;"></i>
					</div>
		                <form role="form">
		                	<div class="card-body">
		                		
								<div class="row">
									<!-- <div class="row mb-2" style='padding-top:2%;'> -->
										<div class="col-md-5">
					                        <div class="form-group clearfix">
					                            <label class="col-md-4 col-form-label" style="text-align: right;"></label>
					                            <div class="icheck-info d-inline">
					                                <input type="radio" id="radioPrimary1" name="r1" checked="" value="Cable">
					                                <label for="radioPrimary1">
					                                    CABLE
					                                </label>
					                            </div>
					                            <label class="col-md-1 col-form-label" style="text-align: right;"></label>
					                            <div class="icheck-info d-inline">
					                                <input type="radio" id="radioPrimary2" name="r1" value="ONU">
					                                <label for="radioPrimary2">
					                                    ONU
					                                </label>
					                            </div>
					                        </div>
											<div class="form-group row">
												<label for="txtDatePicker" class="col-md-4 col-form-label text-right">Install Date: </label>
												<div class="col-md-8">
													<div class="input-group">
														<div class="input-group-prepend">
															<span class="input-group-text" style="width: 40px;">
																<i class="far fa-calendar-alt"></i>
															</span>
														</div>
														<input type="text" class="form-control" id="txtDatePicker" value="2020-02-04" aria-label="Date Picker" placeholder="Select a date">
													</div>
												</div>
											</div>
					                        <div class="form-group row">
					                            <label class="col-md-4 col-form-label" style="text-align: right;">City:</label>
					                            <div class="col-md-8">
					                                <select type="text" class="form-control" id="cboCity"></select>
					                            </div>
					                        </div>
					                        <div class="form-group row" >
												<label class="col-md-4 col-form-label" style="text-align: right;">Order No.: </label>
												<div class="col-md-8 input-group">
													<input type="text" class="form-control" id="txtOrderNo" disabled>
													<input type="text" class="form-control" id="txtCustomerName" disabled>
													<input type="text" class="form-control" id="txtCustomerID"  disabled style="text-align: right;display:none;">
													<input type="text" class="form-control" id="txtCustomerPhone"  disabled style="text-align: right;display:none;">
					                                <span class="input-group-append">
					                                    <button type="button" class="btn btn-info btn-flat" onclick="getOrder()">...</button>
					                                </span>
												</div>
											</div>
					      <!--                  <div class="form-group row" >-->
					      <!--                  	<label class="col-md-4 col-form-label" style="text-align: right;">Slot ID:</label>-->
					      <!--                      <div class="col-md-3">-->
					      <!--                          <select type="text" class="form-control" id="cboSlotID" style="text-align: right;" onchange="iDNo()">-->
					      <!--                          	<option value=""></option>-->
					      <!--                          	<option value="2">2</option>-->
					      <!--                          	<option value="3">3</option>-->
					      <!--                          	<option value="4">4</option>-->
					      <!--                          </select>-->
					      <!--                      </div>-->
											<!--	<label class="col-md-2 col-form-label" style="text-align: right;">Pon Port:</label>-->
					      <!--                      <div class="col-md-3">-->
					      <!--                          <select type="text" class="form-control" id="cboPonPort" style="text-align: right;" onchange="iDNo()">-->
					      <!--                          	<option value=""></option>-->
					      <!--                          	<option value="0">0</option>-->
					      <!--                          	<option value="1">1</option>-->
					      <!--                          	<option value="2">2</option>-->
					      <!--                          	<option value="3">3</option>-->
					      <!--                          	<option value="4">4</option>-->
					      <!--                          	<option value="5">5</option>-->
					      <!--                          	<option value="6">6</option>-->
					      <!--                          	<option value="7">7</option>-->
					      <!--                          	<option value="8">8</option>-->
					      <!--                          	<option value="9">9</option>-->
					      <!--                          	<option value="10">10</option>-->
					      <!--                          	<option value="11">11</option>-->
					      <!--                          	<option value="12">12</option>-->
					      <!--                          	<option value="13">13</option>-->
					      <!--                          	<option value="14">14</option>-->
					      <!--                          	<option value="15">15</option>-->
					      <!--                          </select>-->
					      <!--                      </div>-->
											<!--</div>-->
											<!--<div class="form-group row" >-->
											<!--	<label class="col-md-4 col-form-label" style="text-align: right;">ODB:</label>-->
					      <!--                      <div class="col-md-3">-->
					      <!--                          <select type="text" class="form-control" id="cboODB"  onchange="iDNo()">-->
					      <!--                          	<option value=""></option>-->
					      <!--                          </select>-->
					      <!--                      </div>-->
					      <!--                      <label class="col-md-2 col-form-label" style="text-align: right;">Service Port:</label>-->
					      <!--                      <div class="col-md-3">-->
					      <!--                          <select type="text" class="form-control" id="cboServicePort" style="text-align: right;"  onchange="iDNo()">-->
					      <!--                          	<option value=""></option>-->
					      <!--                          </select>-->
					      <!--                      </div>-->
					                            
											<!--</div>-->
											<div class="form-group row" >
												<label class="col-md-4 col-form-label" style="text-align: right;">ID No.: </label>
												<div class="col-md-8 input-group">
													<input type="text" class="form-control" id="txtIDNo" >
													
												</div>
											</div>
											<div class="form-group row customer_info">
												<label class="col-md-4 col-form-label" style="text-align: right;">Install Address: </label>
												<div class="col-md-8">
													<textarea type="text" class="form-control" id="txtAddress"  rows="2" ></textarea>
												</div>
											</div>
											<div class="form-group row">
												<label class="col-md-4 col-form-label" style="text-align: right;">Geolocation:</label>
												<div class="col-md-8">
													<input type="text" class="form-control" id="txtGeolocation" >
												</div>
											</div>
											
											<div class="form-group row" >
												<label class="col-md-4 col-form-label" style="text-align: right;">Technician 1: </label>
												<div class="col-md-8">
													<input type="text" class="form-control" id="txtTechnician1">
												</div>
											</div>
											<div class="form-group row" >
												<label class="col-md-4 col-form-label" style="text-align: right;">Technician 2: </label>
												<div class="col-md-8">
													<input type="text" class="form-control" id="txtTechnician2">
												</div>
											</div>
											<div class="form-group row" >
												<label class="col-md-4 col-form-label" style="text-align: right;">Technician 3: </label>
												<div class="col-md-8">
													<input type="text" class="form-control" id="txtTechnician3">
												</div>
											</div>
											<div class="form-group row customer_info">
												<label class="col-md-4 col-form-label" style="text-align: right;">Remark: </label>
												<div class="col-md-8">
													<textarea type="text" class="form-control" id="txtRemark"  rows="2" ></textarea>
												</div>
											</div>
										</div>
										<div class="col-md-7">
						
											<div class="card card-outline">
												<div class="card-header">
													<h3 class="card-title">Item List<span id="total_records1" style="font-weight:bold;"> </span> </h3>
													<div class="card-tools">
														<button type="button" class="btn btn-info float-right" onclick='addItem()'><i class="fas fa-plus"></i> Add item</button>
														<!-- <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
														<button type="button" class="btn btn-tool" data-card-widget="remove"><i class="fas fa-remove"></i></button> -->
													</div>
												</div>
												<div class="card-body p-0">
													<table class="table table-striped table-responsive table-head-fixed table-bordered" id="myTable1" style="max-height: 495px;">
														<thead>                  
															<tr>
																<th style="width: 3%">#</th>
																<th style="width: 20%">Item Code</th>
																<th style="width: 42%">Item Name</th>
																<th style="width: 20%">Quantity</th>
																<th style="width: 15%">Unit</th>
																<!-- <th style="width: 5%;">Action</th> -->
															</tr>
														</thead>
														<tbody>
														</tbody>
													</table>
												</div>
											</div>

											<div class="form-group row" style="margin-bottom: 0px;">
											<div class="col-md-6"></div>
												<div class="col-md-4">
												<!-- <button type="button" class="btn btn-primary btn-block" id="btnSubmit" onclick="gotoPhotoUploader()">Photo</button> -->
												</div>
												<div class="col-md-2">
													<button type="button" class="btn btn-success btn-block" onclick="validateAndSave()">Save</button>
												</div>
											</div>				
										</div>
									<!-- </div> -->
								</div>
							</div>		                	
						</form>
					</div>



				    <div class="modal fade" id="ItemEntry">
						<div class="modal-dialog" style="max-width: 100% !important;">
							<div class="modal-content installID" style="width: 100%; top: 30px; margin-left: 23.5%;">
								<div class="modal-header">
									<h4 class="modal-title">Item - Entry</h4>
									<button type="button" class="close" data-dismiss="modal" aria-label="Close">
										<span aria-hidden="true">&times;</span>
									</button>
								</div>
								<section class="content">
									<div class="container-fluid">
										<div class="row">
											<div class="col-md-12">
												<div class="card-body">
													<div class="row">
														<div class="col-md-6">

															<div class="form-group row">
																<!-- <input class="form-control" type="text" id="txtID" style="display:none;"> -->
																<label class="col-md-4 col-form-label" style="text-align: right;">Category:  </label>
																<div class="col-md-8">
																	<input type="text" class="form-control" id="txtCategoryEntry" disabled>
																</div>
															</div>
															<div class="form-group row">
																<label class="col-md-4 col-form-label" style="text-align: right;">Item Code:</label>
																<div class="col-md-8">
																	<input type="text" class="form-control" id="txtItemCodeEntry">
																</div>
															</div>																							
														</div>

														<div class="col-md-6">
															<div class="form-group row">
																<label class="col-md-4 col-form-label" style="text-align: right;">Item Name:</label>
																<div class="col-md-8">
																	<input type="text" class="form-control" id="txtItemNameEntry">
																</div>
															</div>			
															<div class="form-group row">
																<label class="col-md-4 col-form-label" style="text-align: right;">Unit:</label>
																<div class="col-md-8">
																	<input type="text" class="form-control" id="txtUnitEntry">
																</div>
															</div>			
															<div class="form-group row">
																<div class="col-md-4"></div>
																<div class="col-md-4 btnSave"></div>
																<div class="col-md-4 btnSave">
																	<button type="button" class="btn btn-success btn-block" onclick="createItem();" id="btnSaveEntry">Add</button>
																</div>
															</div>
														</div>
													</div>
												</div>						
											</div>

											<div class='col-md-12'>
												<div class="card card-outline ">
													<div class="card-header">
														<h3 class="card-title">Item List<span id="total_records" style="font-weight:bold;"> </span></h3>
													</div>
													<div class="card-body p-0 table-responsive" style="max-height: 300px;">
														<table class="table table-striped table-responsive table-head-fixed table-bordered" id="myTableItemEntry">
															<thead>                  
																<tr>
																	<th style="width: 3%">#</th>
																	<th style="width: 25%">Category</th>
																	<th style="width: 25%">Item Code</th>
																	<th style="width: 25%">Item Name</th>
																	<th style="width: 15%">Unit</th>
																	<th style="width: 3%;">Delete</th>
																</tr>
															</thead>
															<tbody>
															</tbody>
														</table>
													</div>
												</div>
											</div>

										</div>
									</div>
								</section>	
							</div>
						</div>
					</div>

					<div class="modal fade" id="myTableOrderModel">
					    <div class="modal-dialog" style="max-width: 100% !important;">
					        <div class="modal-content " style="width: 100%; top: 3px; margin-left: 23.5%;">
					            <div class="modal-header">
					                <h4 class="modal-title">Order List </h4>
			
					            </div>
					            <section class="content">
					                <div class="container-fluid">
					                    <div class="row">
					                        <div class="col-md-12">
					                        <div class="card card-outline">
					                            <form role="form" id="frmEntry">
					                                <div class="card-body">
					                                    <div class="card-body" id="tab1">
					                                        <table class="table table-bordered table-hover" id="myTableOrder" style="width: 100%;">
					                                            <thead>
					                                                <tr>
					                                                    <th style="width: 5%;">#</th>
					                                                    <th style="text-align: center;">Order No.</th>
					                                                    <th style="text-align: center;">Order Date</th>
					                                                    <th style="text-align: center;">Customer Name</th>
					                                                    <th style="text-align: center;">Customer Phone</th>
					                                                    <th style="text-align: center;">Address</th>
					                                                    <!-- <th style="text-align: center;">Action</th> -->
					                                                </tr>
					                                            </thead>
					                                            <tbody>
					                                            </tbody>
					                                        </table>
					                                    </div>
					                                </div>
					                            </form>
					                            </div>
					                        </div>
					                    </div>
					                </div>
					            </section>
					        </div>
					    </div>
					</div>

				</div>
			</div>
		</div>
	</section>
</div>
<?php include '../footer.php'; ?>
<script>	
	var C = '<?php echo $_SESSION['city']?>';
	var code = '<?php echo isset($_SESSION['code'])?$_SESSION['code']:""?>';

	var d = new Date();
	var mm = (d.getMonth("MM")+1);
	var dd = d.getDate();
	var customDate = d.getFullYear() + "-" + ((mm<10)?"0" + mm:mm) + "-" +  ((dd<10)?"0" + dd:dd);

	$(function(){	
		$("body").addClass("sidebar-collapse");
		$('#txtDatePicker').datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'yy-mm-dd',
			showButtonPanel: true,
            showAnim: 'clip',
            autoclose: true
        }).val(customDate);
// 		getODB();
// 		getServicePort();

	if(C=='Main Office'){
			getAllCity();
			$("#txtDatePicker").attr("disabled", false);
		}else{
			$("#cboCity").append("<option value= '" + C + "'  data-code= '" + code + "' >" + C + "</option>");	
			fillGrid();
			$("#txtDatePicker").attr("disabled", false);
		}
		getInstallItemList();
		// fillNumbers();
	});


	function getODB() {
	    for (var letterCode = 'A'.charCodeAt(0); letterCode <= 'P'.charCodeAt(0); letterCode++) {
	        var letter = String.fromCharCode(letterCode);
	        for (var number = 1; number <= 8; number++) {
	            var value = letter + number;
	            $("#cboODB").append("<option value= '" + value + "'>" + value + "</option>");
	        }
	    }
	}

	function getServicePort() {
	  for (var numbers = 0; numbers <= 127; numbers++) {
	    // Use a conditional operator to add leading zero if needed
	    var formattedNumber = (numbers < 10) ? '0' + numbers : numbers;

	    // Append an option element to the dropdown list with id "cboServicePort"
	    $("#cboServicePort").append("<option value='" + formattedNumber + "'>" + formattedNumber + "</option>");
	  }
	}



	function iDNo() {
		if($("#cboSlotID").val()=="" || $("#cboPonPort").val()=="" || $("#cboODB").val()=="" || $("#cboServicePort").val()==""){
			$("#txtIDNo").val("");
		}else{
			$("#txtIDNo").val("sls@p" + $("#cboSlotID").val() + "/" +  $("#cboPonPort").val() + $("#cboODB").val() + $("#cboServicePort").val());
		}
	}

	// function fillNumbers(){
    //     for (var a = 1; a <= 100; a++){
    //         $("#cboPort").append("<option value= '" + a + "'>" + a + "</option>");
    //     }
    // } 

	function getAllCity(){
		$("#cboCity").find("option").remove();
		$("#cboCity").append("<option value= '' data-id = ''></option>");
		$.ajax({
			url: APP_URL + "api/city/get_all_rows.php"
		}).done(function(data) {
			$.each(data.records, function(i, v) {
				if(v.name!='Main Office'){
					$("#cboCity").append("<option value= '" + v.name + "' data-code= '" + v.code + "' >" + v.name + "</option>");	
				}		
			});		
		});
	}

	$('input[type=radio][name=r1]').on('change', function() {
		$("#loading").css("display","block");
		clearForm();
        getInstallItemList();
        let selectedValue = $('input[name=r1]:checked').val();

        if (selectedValue === "ONU") {
            $("#txtIDNo").prop("disabled", true);
        } else {
            $("#txtIDNo").prop("disabled", false);
        }
	});

	function addItem(){
		$("#ItemEntry").modal('show');
        $("#txtCategoryEntry").val($('input[name=r1]:checked').val());
		getItemList();
	}


	function getInstallItemList(nr){

		$("#myTable1").find("tbody").find("tr").remove();
		$.ajax({
            type: "POST",
			url: APP_URL + "/api/install_items/get_all_rows.php",
            data: JSON.stringify({ category: $('input[name=r1]:checked').val() }),
		}).done(function(data) {
			$("#loading").css("display","none");
			$.each(data.records, function(i, v) {
				$("#myTable1").find("tbody")
				.append($('<tr>')
					.append("<td>" + (i+1) + "</td>")
					.append("<td>" + v.item_code + "</td>")
					.append("<td>" + v.item_name + "</td>")
					.append("<td><input type='number' style='text-align:right;' class='form-control' onfocus='this.select();' value=''></td>")
					.append("<td>" + v.unit + "</td>")
				)  
			});
		});
	}

	function getItemList(){

		$("#myTableItemEntry").find("tbody").find("tr").remove();
		$.ajax({
	        type: "POST",
			url: APP_URL + "/api/install_items/get_all_rows.php",
	        data: JSON.stringify({ category: $('input[name=r1]:checked').val() }),
		}).done(function(data) {
			$.each(data.records, function(i, v) {
				$("#myTableItemEntry").find("tbody")
				.append($('<tr>')
					.append("<td>" + (i+1) + "</td>")
					.append("<td>" + v.category + "</td>")
					.append("<td>" + v.item_code + "</td>")
					.append("<td>" + v.item_name + "</td>")
					.append("<td>" + v.unit + "</td>")
					.append("<td style='text-align:center;'><span class='btn btn-danger btn-sm fas fas fa-trash-alt' style='cursor: pointer;padding: 5px 9px 5px 10px;font-size: 17px;' onclick='del(\"" + v.id + "\",this)' title='Delete'></span></td>")
				)  
			});
		});
	}

	function getOrder(){
		$("#myTableOrderModel").modal('show');
		fillGrid();
	}

	// function fillGrid() {
	//     let table = $('#myTableOrder').DataTable({
	//         "destroy": true,
	//         "paging": true,
	//         "lengthChange": true,
	//         "searching": true,
	//         "ordering": true,
	//         "info": true,
	//         select: {
	//             style: 'single'
	//         },
	//         keys: {
	//             keys: [13 /* ENTER */, 38 /* UP */, 40 /* DOWN */]
	//         },
	//         "autoWidth": false,
	//         "lengthMenu": [5, 10, 50, 100],
	//         "pageLength": 5,
	//         "order": [[0, "asc"]],
	//         columnDefs: [
	//             {
	//                 // Date printable
	//                 responsivePriority: 2,
	//                 targets: 2
	//             },
	//             {
	//                 searchable: false,
	//                 targets: [0]
	//             }
	//      		// {
	//             //     targets: 6, // eq3 column
	//             //     visible: false // Hide the eq3 column
	//             // }
	//         ],
	//         ajax: {
	//             url: APP_URL + "api/order_list/get_to_install_order.php",
	//             data: function (d) {
	//                 d.city = $("#cboCity").val();
	//                 d.ty = $('input[name=r1]:checked').val();
	//             }
	//         }
	//     });

	//     $('#myTableOrder').on('click', 'tbody td:not(:first-child)', function (e) {
	//         const row = $(this).closest('tr');
	//         $("#txtOrderNo").val(row.find("td").eq(1).text());
	//         $("#txtCustomerName").val(row.find("td").eq(3).text());
	//         $("#txtCustomerPhone").val(row.find("td").eq(4).text());
	//         $("#txtAddress").val(row.find("td").eq(5).text());
	//         // $("#txtIDNo").val(row.find("td").eq(7).text());

	//         const rowIndex = 0; // Replace this with the actual row index you want to retrieve the value from
	//     	const eq6Value = table.row(rowIndex).data()[6];
	//     	const eq7Value = table.row(rowIndex).data()[7];
	//     	const eq8Value = table.row(rowIndex).data()[8];
	//     	const eq9Value = table.row(rowIndex).data()[9];
	//     	const eq10Value = table.row(rowIndex).data()[10];
	//     	const eq11Value = table.row(rowIndex).data()[11];
	//     	const eq12Value = table.row(rowIndex).data()[12];

	//         $("#txtCustomerID").val(eq6Value);
	//         $("#txtIDNo").val(eq7Value);
	//         $("#cboSlotID").val(eq8Value);
	//         $("#cboPonPort").val(eq9Value);
	//         $("#cboODB").val(eq10Value);
	//         $("#cboServicePort").val(eq11Value);
	//         $("#txtGeolocation").val(eq12Value);

	//         if($('input[name=r1]:checked').val()=='ONU'){
	//         	$("#cboSlotID").attr("disabled", true);
	// 	        $("#cboPonPort").attr("disabled", true);
	// 	        $("#cboODB").attr("disabled", true);
	// 	        $("#cboServicePort").attr("disabled", true);
	//         }


	//         $("#myTableOrderModel").modal('hide');
	//     });
	// }

function fillGrid() {
    let table = $('#myTableOrder').DataTable({
        "destroy": true,
        "paging": true,
        "lengthChange": true,
        "searching": true,
        "ordering": true,
        "info": true,
        select: {
            style: 'single'
        },
        keys: {
            keys: [13 /* ENTER */, 38 /* UP */, 40 /* DOWN */]
        },
        "autoWidth": false,
        "lengthMenu": [5, 10, 50, 100],
        "pageLength": 5,
        "order": [[0, "asc"]],
        columnDefs: [
            {
                // Date printable
                responsivePriority: 2,
                targets: 2
            },
            {
                searchable: false,
                targets: [0]
            }
        ],
        ajax: {
            url: APP_URL + "api/order_list/get_to_install_order.php",
            data: function (d) {
                d.city = $("#cboCity").val();
                d.ty = $('input[name=r1]:checked').val();
            }
        }
    });

    $('#myTableOrder').on('click', 'tbody td:not(:first-child)', function (e) {

    	 const row = $(this).closest('tr');

	    // Check if the clicked row has data
	    if (!table.row(row).data()) {
	        // No data available, handle it as needed (you can show a message or perform other actions)
	        return;
	    }
    
        const rowIndex = table.row($(this).closest('tr')).index();
        const rowData = table.row(rowIndex).data();

        $("#txtOrderNo").val(rowData[1]);
        $("#txtCustomerName").val(rowData[3]);
        $("#txtCustomerPhone").val(rowData[4]);
        $("#txtAddress").val(rowData[5]);

        $("#txtCustomerID").val(rowData[6]);
        $("#txtIDNo").val(rowData[7]);
        $("#cboSlotID").val(rowData[8]);
        $("#cboPonPort").val(rowData[9]);
        $("#cboODB").val(rowData[10]);
        $("#cboServicePort").val(rowData[11]);
        $("#txtGeolocation").val(rowData[12]);

        if ($('input[name=r1]:checked').val() === 'ONU') {
            $("#cboSlotID, #cboPonPort, #cboODB, #cboServicePort").attr("disabled", true);
        }

        $("#myTableOrderModel").modal('hide');
    });
}

	function createItem(){
		var category = $("#txtCategoryEntry").val();
		var item_code = $("#txtItemCodeEntry").val();
		var item_name = $("#txtItemNameEntry").val();
		var unit = $("#txtUnitEntry").val();

		if( item_code==""){
			bootbox.alert("Please fill item code.");
		}else{
	  		$.ajax({
	  			type: "POST",
	  			url: APP_URL + "api/install_items/create.php",
	  			data: JSON.stringify({ category: category, item_code: item_code, item_name: item_name, unit: unit }),
	  			success: function(data){	
	  				if(data.message=="created"){
						getItemList();
						getInstallItemList();
	  				}else if(data.message=="duplicate"){
						bootbox.alert("Don't allow duplicate item code.");
	  				}else{
	  					bootbox.alert("Error on server side.");
	  				}
	  			}
	  		});
  		}
	}

	function del(id, obj){
        // bootbox for good looking 'confirm pop up'
        bootbox.confirm({
        	message: "<h4>Are you sure that you want to delete?</h4>",
        	buttons: {
        		confirm: {
        			label: '<span class="glyphicon glyphicon-ok"></span> Yes',
        			className: 'btn-danger'
        		},
        		cancel: {
        			label: '<span class="glyphicon glyphicon-remove"></span> No',
        			className: 'btn-primary'
        		}
        	},
        	callback: function (result) {
        		if(result){
        			$.ajax({
        				type: "POST",
        				url: APP_URL + "api/install_items/delete.php",
        				data: JSON.stringify({ id: id }),
        				success: function(data){
        					if(data=="deleted"){
        						$(obj).parent().parent().remove();
								getInstallItemList();
        					}else{
        						bootbox.alert("Error on server side.");
        					}
        				}
        			});
        		}
        	}
        });
    }

	function validateAndSave(){
	$("#loading").css("display","block");
		var item_details = [];
		$("#myTable1 tbody tr").each(function (){
			var item_detail = {
				"item_code" : ($(this).find("td").eq(1).text()),
				"item_name" : ($(this).find("td").eq(2).text()),
                "quantity" : (parseInt($(this).find("td").eq(3).find("input").val().replace(/,/g, '')))? (parseInt($(this).find("td").eq(3).find("input").val().replace(/,/g, ''))):0,
				"unit" : ($(this).find("td").eq(4).text())
			}
			item_details.push(item_detail);
		});

		var sales = {
			"install_type":$('input[name=r1]:checked').val(),
			"install_date":$("#txtDatePicker").val(),
			"city":$("#cboCity").val(),
			"order_no":$("#txtOrderNo").val(),
			"id_no":$("#txtIDNo").val(),
			"customer_id":$("#txtCustomerID").val(),
			"customer_name":$("#txtCustomerName").val(),
			"customer_phone":$("#txtCustomerPhone").val(),
			"slot_id":"",//$("#cboSlotID").val(),
			"pon_port":"",//$("#cboPonPort").val(),
			"odb":"",//$("#cboODB").val(),
			"service_port":"",//$("#cboServicePort").val(),
			"install_address":$("#txtAddress").val(),
			"geolocation":$("#txtGeolocation").val(),
			"technician1":$("#txtTechnician1").val(),
			"technician2":$("#txtTechnician2").val(),
			"technician3":$("#txtTechnician3").val(),
			"remark":$("#txtRemark").val(),
			"item_details":item_details
		};
		if($("#txtOrderNo").val()=="" ){
			bootbox.alert("Please fill the box.");
			$("#loading").css("display","none");
		}else{
			$.ajax({
				url: APP_URL + "api/installation/create.php",
				type: "POST",
				data: JSON.stringify(sales)
			}).done(function(data) {	
				$("#loading").css("display","none");
				if(data.message=="created"){
				// 	gotoPhotoUploader(data.last_id);
					clearFormAll();
					fillGrid();
					// getInstallItemList();
				}else if(data.message=="duplicate"){
					bootbox.alert("Duplicate ID No.");
				}else{
					bootbox.alert("Error on server side.");
				}
			});
		}
	}


	function gotoPhotoUploader(id){
		
		bootbox.confirm({
			message: "<h4>Do u want to upload photos?</h4>",
			// message: "<h4>"+status+"</h4>",
			buttons: {
				confirm: {
					label: '<span class="glyphicon glyphicon-ok"></span> Yes',
					className: 'btn-danger'
				},
				cancel: {
					label: '<span class="glyphicon glyphicon-remove"></span> No',
					className: 'btn-primary'
				}
			},
			callback: function (result) {
				if(result){
					window.open("<?=$app_url;?>upload/install.php?for=install&c=" + id  , "_blank");
				}
			}
		});

		
	}

	function clearForm(){
		$("#txtOrderNo").val("");
		$("#txtIDNo").val("");
		$("#txtCustomerID").val("");
		$("#txtCustomerName").val("");
		$("#txtCustomerPhone").val("");
		$("#txtDatePicker").val(customDate);
		$("#txtAddress").val("");
		$("#txtGeolocation").val("");
		$("#cboSlotID").val("");
		$("#cboPonPort").val("");
		$("#cboODB").val("");
		$("#cboServicePort").val("");
		if($('input[name=r1]:checked').val()=='Cable'){
			$("#cboSlotID").attr("disabled", false);
	        $("#cboPonPort").attr("disabled", false);
	        $("#cboODB").attr("disabled", false);
	        $("#cboServicePort").attr("disabled", false);
		}
	}

	function clearFormAll(){
		$("#txtOrderNo").val("");
		$("#txtIDNo").val("");
		$("#txtCustomerID").val("");
		$("#txtCustomerName").val("");
		$("#txtCustomerPhone").val("");
		$("#txtDatePicker").val(customDate);
		$("#cboCity").val("");
		$("#txtAddress").val("");
		$("#txtGeolocation").val("");
		$("#cboSlotID").val("");
		$("#cboPonPort").val("");
		$("#cboODB").val("");
		$("#cboServicePort").val("");
		$("#txtTechnician1").val("");
		$("#txtTechnician2").val("");
		$("#txtTechnician3").val("");
		$("#txtRemark").val("");
		$("#myTable1").find("tbody").find("input[type='number']").val("");

	}


</script>	
