$(function () {
    console.log('po-site.js');

    var arrPO       = [];
    var cur_url     = window.location.pathname;
    var arr_url     = cur_url.split('/');
    var project_id  = 0;
	var page 		= "";
	
	if(arr_url[3] == "po") {
        project_id = arr_url[4];

        if(arr_url[5] == undefined) {
            ListPoTable(project_id, 'new');			
        } 
		else if(arr_url[5] == "edit") {
			var id 	= arr_url[6];
			EditGetPoDetail(project_id, id);
			
			$( ".datepicker" ).datepicker({
				format: 'dd/mm/yyyy',
				minDate: moment("12/01/2000"),				
			});
		}
		page	= arr_url[5];
    }
	
	$(document).on('click', '.modal-links', function() {
		var id = $(this).data('id');
		console.log('[RF Modal] ID: '+id);
		
		GetRfDetail(project_id, id);
	});
	
	$(document).on("click", ".delete_img, .remove-link", function() {
        console.log('[.delete_img] Clicked');
        var filename = $(this).data('file');
        $("#ConfirmDelete p").html("Are you sure to delete this image?");       
        $("#ConfirmDelete .btnConfirm").data("file", filename);
    });
	
	$(document).on("click", "#ConfirmDelete .btnConfirm", function() {        
        var id      = $(this).data('id');
        var filename = $(this).data('file');
        console.log('[.btnConfirm] Clicked! [filename]'+filename);

        var formData = new FormData();	

		formData.append('id', id);
		formData.append('filename', filename);
		formData.append('page', 'po');

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            // url: "../../../imageUpload/1",
            url: APP_URL + '/site/imageUpload/delete',
            type: "POST",
            data: formData, 
            contentType: false,
			processData: false,       
            // dataType: 'json',            
            success:function(data){
                console.log(data);
                $('#ConfirmDelete').modal('hide');
                var row = '';
                if(data.status == "success"){
                    $(".img__preview").empty();    
                    $(".doc_preview").empty();    

                } else{
                    // printErrorMsg(data.status);
					AlertPopup("<strong>WARNING</strong><br>" + data.status);
                }
                // window.location.href = window.location.href;
            },

        });
    });
	
	$(document).on("change", "#po_file", function() {
    // $("#item_image").change(function() {
        // var id 		= $(this).attr("id");
        var id 		= 0;
		var files 	= document.getElementById('po_file').files[0];
		// var files 	= $('#'+id)[0].files;
		
		if(arr_url[5] == "edit") {
			id 	= arr_url[6];		
		}

        var formData = new FormData();	
		
		formData.append('id', id);
		formData.append('file', files);
		formData.append('source', 'po');

        console.log('[POST data]', formData.get('file'));

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: APP_URL + '/site/fileUpload',
            type: "POST",
            data: formData,
            contentType: false,
			processData: false,
            cache:false,
            // dataType: 'json',            
            success:function(data){
                console.log(data);
                var row = '';
                if(data.status == "success"){
                    $(".img_preview").empty();               
                    $(".doc_preview").empty();  
					
					if(data.file_ext == "pdf") {
						row += '<div class="img_item" data-file="'+data.path+'">';
						row += '<a href="#imgPDF" class="font-weight-bold">'+data.filename+'</a>&nbsp;&nbsp;';
						row += '<a href="#" class="remove-link" data-id="0" data-file="'+data.path+'" data-toggle="modal" data-target="#ConfirmDelete"><i class="fas fa-trash-alt"></i></a>';						
						row += '<a href="#" class="lightbox" id="imgPDF"><iframe src="'+APP_URL+data.path+'" title="'+data.filename+'" class="lightbox-pdf"></iframe></a>';
						row +=  '</div>'; 			
					
						// row += '<a href="#" class="lightbox" id="img1"><iframe src="'+APP_URL+data.path+'" class="lightbox-pdf">PO File</iframe></a>';
						$(".doc_preview").append(row);
					} else {
						row += '<div class="img_item" data-file="'+data.path+'">';
						row += '<a href="#img1"><div class="thumb_img" style="background-image: url('+APP_URL+data.path+');"></div></a>';
						row += '<a href="#" class="delete_img" data-id="0" data-file="'+data.path+'" data-toggle="modal" data-target="#ConfirmDelete"><i class="fas fa-times"></i></a>';
						row += '<a href="#" class="lightbox" id="img1"><span style="background-image: url('+APP_URL+data.path+')"></span></a>';
						row +=  '</div>';        

						$(".img_preview").append(row);
					}
                } else{
                    // printErrorMsg(data.status);
					AlertPopup("<strong>WARNING</strong><br>" + data.status);
                }                
            },

        });
    });


	$(document).on('click', '#PoDetail input[name=po_type]', function() {
		var val 	= $(this).val();
		console.log('[PoDetail - radio] val: '+val);
		
		// $('#PoDetail .doc_preview').empty();
		// $('#PoDetail .img_preview').empty();
		
		if(val == "select_po") {
			$('#PoDetail .selectPO').show();
			$('#PoDetail .uploadPO').hide();
		} else {
			$('#PoDetail .selectPO').hide();
			$('#PoDetail .uploadPO').show();			
		}
	});
	
	$(document).on('click', '.btnProceed', function() {
        var total_empty = 0;
        var total_row   = 0;
		var type		= 'new';
		var po_id		= $("#PoDetail").data('po-id');		
		var po_file		= $("#PoDetail .img_item").data('file');	
		var vendor_id	= $("#SelectVendor").val();
		var po_date		= $("#kt_datepicker_4_1").val();
		var po_no		= $("#PoDetail #po_no").val();
		var rf_id		= $("#kt_repeater_2").data('rf-id');
		
        var arr_selected = $("table.table_rf_new_item input[name=qty]").map(function(){ 
            var id      	= $(this).data('id');
			var rf_item_id  = $(this).data('rf-item-id');
            var qty     	= $(this).val();
            var remark  	= $('table.table_rf_new_item input[name=remark_'+id+']').val();        
			
            var temp = {
                'id'        	: id,
                'qty'       	: qty,
                'remark'    	: remark,                
                'rf_item_id'    : rf_item_id,                
            };    

            total_row++;

            if(qty == "") {               
                total_empty++;
                return;
            } else {                
                return temp;
            }
            // console.log('[.btnProceed] [id:'+id+'] [qty: '+qty+']');
        }).get();

        if(total_row == 0) {
            // alert("Please add at least one(1) item into the Purchase Order.");
			AlertPopup("<strong>WARNING</strong><br>Please select at least one(1) in order to create Purchase Order.");
            return;
        }

        if(total_empty > 0) {
            // alert("Please fill in the quantity.");
			AlertPopup("<strong>WARNING</strong><br>PPlease fill in the quantity.");
            return;
        }                

        console.log('[.btnProceed()] [arr_selected]', arr_selected);
        var ajax_url    = APP_URL + '/site/po/store/';
		
		if(arr_url[5] == "edit") {
			po_id		= arr_url[6];
			ajax_url    = APP_URL + '/site/po/update/'+po_id;	
		}

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },           
            url : ajax_url,
            type: 'PUT',           
            data: {				
                'project_id'    : project_id,
                'list'          : arr_selected,       
                'po_id'         : po_id,   			
                'po_no'         : po_no,   			
                'po_file'		: po_file, 
				'vendor_id'		: vendor_id,
				'rf_id'			: rf_id,
            },
            success: function(data) {                
                console.log('Create PO Success!');        
                console.log('Error: ', data.error);       

                if(data.status == "success"){
                    // alert(data.msg);
					SuccessPopup('<strong>Success</strong><br>' + data.msg);
                }else{
					AlertPopup("<strong>WARNING</strong><br>" + data.error);
                    // printErrorMsg(data.error);                    
                }               
            },
        });

    });
	
	$(document).on('click', 'table.table_rf_new_item .btnDelete', function() {
        var id      = $(this).data('id');
        console.log('[btnDelete] Clicked! id: '+id);

        arrPO = arrPO.filter(function(item) {
            // console.log('[arrRF - loop] item" ',item);
            return item !== id;
        });

        $('table.table_rf_new_item tr#'+id).remove();
        console.log('[arrPO] ',arrPO);
    });
	
	// $(document).on('click', '#add_newPOItem .btnBack', function() {		
		// $("#add_newPOItem #ListItem").empty();
		// ListRfTable(project_id, 'approve');
	// });
	
	$(document).on('click', '#add_newPOItem .btnConfirm', function() {
		var rf_id 			= $('#add_newPOItem #ListItem').data('rf-id');	
		var rf_no 			= $('#add_newPOItem #ListItem').data('rf-no');	
		var selectedRf 		= $('#kt_repeater_2').data('rf-id');	
		var selectedRfNo 	= $('#kt_repeater_2').data('rf-no');	
		// var selectedRf	= $("#selectedRf").val();
		
		if(selectedRf == "" || selectedRf == undefined) {
			$('#kt_repeater_2').data('rf-id', rf_id);	
			// $("#selectedRf").val(rf_id);
			
			if(page == "create") {
				var row = '<label style="font-size:20px; font-weight:400;">RF No: </label>&nbsp;&nbsp;<label class="rf_no" style="font-size:20px; font-weight:600;">'+rf_no+'</label>';
				
				$('#kt_content .container .title').append(row);
			}
		} else {
			if(selectedRf != rf_id) {
				AlertPopup("<strong>WARNING</strong><br>Different RF ID!");
				return;
			}
		}		
		
        var row = '';
        var searchIDs = $("#add_newPOItem #ListItem table.table_po_item input:checkbox:checked").map(function(){
            var id      	= $(this).data('id');
            var name   	 	= $(this).closest('td').next('td').text();
            var desc    	= $(this).closest('tr').find('td').eq(2).text();
            var unit    	= $(this).closest('tr').find('td').eq(3).text();
            var qty    		= $(this).closest('tr').find('td').eq(4).text();
			var rf_item_id	= $(this).closest('tr').find('td').eq(4).data('rf-item-id');
            var img     	= $(this).closest('tr').find('td').eq(4).data('img');
            
            // console.log('[img] ', $(this).closest('tr').find('td').eq(2));

            if(arrPO.includes(id) == false) { 
                arrPO.push(id);
                var temp = {
                    'id'    : id,
                    'name'  : name,
                    'desc'  : desc,
                    'unit'  : unit,
                    'img'   : img
                };    

                row += '<tr id="'+id+'">';
                row += '<td></td>';
                row += '<td class="text-left">'+name+' - '+desc+'</td>';
                row += '<td>'+unit+'</td>';
                row += '<td><input type="number" name="qty" class="form-control" placeholder="Qty" min="0" max="'+qty+'" data-id="'+id+'" data-rf-item-id="'+rf_item_id+'" /></td>';
                row += '<td><input type="text" name="remark_'+id+'" class="form-control" placeholder="Remarks" /></td>';
                row += '<td><a href="javascript:;" data-repeater-delete=""  data-toggle="modal" data-target="#delete_rf_item" class="btn btn-sm font-weight-bolder btn-light-danger btnDelete" data-id="'+id+'"><i class="fas fa-trash-alt"></i></a></td>';
                row += '</tr>';

                return temp;
            } else {
                return;
            }
        }).get();

        $("table.table_rf_new_item").append(row);	
        $('#add_newPOItem').modal('hide');

        console.log('[.btnConfirm] [rf_id: '+rf_id+'] searchIDs: ',searchIDs);
        console.log('[arrPO] ', arrPO);
    });
	
	$(document).on('click', '#add_newPOItem table .btnSelect', function() {
		var id = $(this).data('id');
		
		console.log('[.btnSelect] ID:'+ id);
		ListRfItem(project_id, id);
	});
	
	$(document).on('click', '.btnAddNew, #add_newPOItem .btnBack', function() {
		$('#add_newPOItem #ListItem').empty();
		$('#add_newPOItem .btnConfirm').hide();
		$('#add_newPOItem .btnBack').hide();
		$('#add_newPOItem .modal-title').text('Add PO Item');
		
		var source	= (arr_url[5] == "edit") ? "po_edit" : "po_create";
		var rf_id 	= $("#kt_repeater_2").data('rf-id');
		
		console.log('[.btnAddNew] rf_id: '+rf_id);
        ListRfTable(project_id, 'approve', source, rf_id);
    });
	
	$(document).on('click', '.modal-links.po', function() {
		var id = $(this).data('id');
		console.log('[RF Modal] ID: '+id);
		
		GetPoDetail(project_id, id);
		// GetRfDetail(project_id, id);
	});
	
	// function formatDate (input) {
		
		// var datePart 	= input.match(/\d+/g),
			// year 		= datePart[0], // get only two digits
			// month 		= datePart[1], 
			// day 		= datePart[2];
		
		// console.log('[formatDate()] input: '+input + '[datePart]', datePart);
		// console.log('[formatDate()] [year: '+year + '] [month: '+month+'] [day: '+day+']');
		
		// return day+'/'+month+'/'+year;
	// }

	function printErrorMsg (msg) {
		console.log(msg);
        // $(".print-error-msg").find("ul").html('');
        // $(".print-error-msg").css('display','block');
        // $.each( msg, function( key, value ) {
            // $(".print-error-msg").find("ul").append('<li>'+value+'</li>');
        // });
    }
	
	function ListPoTable(project_id, by_status, source) {
        console.log('ListPoTable() ==> status: ' + by_status);
        var date		= new Date();
		var month 		= date.getMonth() + 1;
			month 		= (month < 10) ? '0'+month : month;
		var day			= date.getDate();			
		var today		= date.getFullYear() + month + day;      
        var tableName	= "po_list";	//+by_status;

        var row = '';
		row += '<table id="'+tableName+'" class="table table-bordered mt-15 table_polist_'+by_status+' table-hover" data-category="0">';
		row += '<thead>';
		row += '<tr>';
		row += '<th style="width:3%">#</th>';
		row += '<th class="excelExport" style="width:10%">PO #</th>';	

        if(by_status == "new" || by_status == "pending" || by_status == "approve" || by_status == "completed" || by_status == "rejected") {		            	
            row += '<th class="excelExport" style="width:5%">Total Item</th>';	            	
            row += '<th class="excelExport" style="width:15%">Vendor</th>';	
            row += '<th class="excelExport" style="width:15%">Created By</th>';	
			
		} else if(by_status == "do") {			            
            row += '<th class="excelExport" style="width:30%">Vendor</th>';		
            row += '<th class="excelExport" style="width:10%">DO #</th>';	
			row += '<th class="excelExport" style="width:5%">Total Item</th>';	

		} 
		// row += '<th class="excelExport" style="width:6%">Status</th>';
		row += '<th class="excelExport" style="width:10%">Create Date</th>';			
		row += '<th class="excelExport" style="width:10%">Status</th>';			
		row += '<th style="width:6%">Action</th>';
		row += '</tr>';
		row += '</thead>';
		row += '<tbody>';
		row += '</tbody>';
		row += '</table>';
		$('#ListTable').html(row);

        var formData = {
			'by_status'	    : by_status,
			'project_id'	: project_id,
			'source'		: 'index',
		};
        
        console.log('ajax_url ==>  ' + APP_URL + '/site/po/list',);
        console.log('[tableName: '+tableName+'] formData ==>  ', formData);

		var columns = "";
		
		if(by_status == "new" || by_status == "pending" || by_status == "approve" || by_status == "completed" || by_status == "rejected") {
			columns 	= [
				{ "data": null,"sortable": false, 
                    render: function (data, type, row, meta) {
                                return meta.row + meta.settings._iDisplayStart + 1;
                    }  
                },				
                { data: 'po_no', name: 'po_no' },                  
                { data: 'total_item', name: 'total_item' },    
                { data: 'vendor', name: 'vendor' },    
                { data: 'create_by', name: 'create_by' },                  
                // { data: 'po', name: 'po' },                  
                // { data: 'do', name: 'do' },            
				{ data: 'create_at', name: 'create_at' },	
				{ data: 'status', name: 'status' }, 			
                { data: 'action', name: 'action'},
			];
			
		} else {
			columns 	= [
				{ "data": null,"sortable": false, 
                    render: function (data, type, row, meta) {
                                return meta.row + meta.settings._iDisplayStart + 1;
                    }  
                },				
                { data: 'requisition_no', name: 'requisition_no' },  
				// { data: 'total_item', name: 'total_item' }, 				
                { data: 'create_by', name: 'create_by' },                  
                { data: 'contact', name: 'contact' },                  
                // { data: 'status', name: 'status' },    
				{ data: 'create_at', name: 'create_at' },				
                { data: 'action', name: 'action'},
			];
		}
		
		// console.log('[columns]', columns);
		
        var po_table = $('#'+tableName).DataTable({
            processing  : true,
            serverSide  : false,
			responsive: true,
            // dom		    : 'lBfrtip',
			dom: `
				<'row'<'col-sm-12 col-md-5 text-left'f><'col-sm-12 col-md-7 text-right dataTables_pager'lB>>
				<'row'<'col-sm-12'tr>>
				<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 'p>>`,
            ajax        : {
				headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: APP_URL + '/site/po/list',
				type: "post",  		
				data: formData,
				error: function(){  
					console.log("error");
				}
			}, 
            columnDefs: [				
				{
					"targets"	: [0,2,3,4,5,6,7],
					"className"	: "text-center",
				}
			],
			buttons: [
				{
					extend: 'collection',
					text: 'Export',
					buttons: [
						'copy',		
						{ extend: 'csv', filename: 'PO_List_'+today },
						{ extend: 'excel', filename: 'PO_List_'+today },						
						{ extend: 'pdf', filename: 'PO_List_'+today },										
						'print'
					]
				}
			],
			columns: columns,
            order: [[1, 'desc']]
        });         
        
    }

	
	function GetRfDetail(project_id, id) {
		// var formData = {
			// 'by_status'	    : by_status,
			// 'project_id'	: project_id,			
		// };
		$('#requisition_form .table-rf').empty();
		$("#requisition_form .rf_no").html('No. : ');
		
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },           
            url: APP_URL + '/site/requisition/detail',
            type: "POST",
            data: {
				// 'project_id'	: project_id,	
				'project_id'	: project_id,	
                'id'      		: id,         
            },
            // contentType: false,
			// processData: false,       
            dataType: 'json',            
            success:function(data){
                $('#requisition_form .request-info').empty();				
				var company_info	= data.company_info[0]; 
				var rf_detail 		= data.rf_detail[0];
				var rf_list			= data.rf_list; 
				// return;
				console.log('[company_info_length: '+ data.company_info.length+ '] [rf_detail_length: '+data.rf_detail.length+']');
				console.log('rf_detail: ', data.rf_detail[0]);
				console.log('rf_list: ', data.rf_list[0]);
                // $('#ConfirmDelete').modal('hide');
                var row 	= '';				
                if(data.status == "success" ){	
					if(data.company_info.length > 0) {						
						$("#requisition_form .address-box").html('<div>'+company_info.residential_name+', </div>'+'<div>'+company_info.residential_addr+'</div><div>Tel:</div>');
						$("#requisition_form .to-info").html('<strong>To:</strong><br>Headquarters<br>'+company_info.company_addr);  
						$("#requisition_form .logo-rf").css('background-image', 'url('+ APP_URL + '/images/logo/' + company_info.logo + ')');
					}
					
					if(data.rf_detail.length > 0) {
						var create_dt 	= new Date(rf_detail.create_at);
							create_dt 	= ('0' + create_dt.getDate()).slice(-2) + '/' + ('0' + (create_dt.getMonth() + 1)).slice(-2) + '/' + create_dt.getFullYear();
						
						var creator_name= (rf_detail.creator_name == null) ? "" : rf_detail.creator_name;
						var creator_tel	= (rf_detail.creator_tel == null) ? "" : rf_detail.creator_tel;
						
						$("#requisition_form .rf_no").html('No. : '+rf_detail.requisition_no);
						row += '<table class="table table-borderless">';
						row += '<tr><td>Request Date :</td><td>'+ create_dt +'</td></tr>';
						row += '<tr><td>Requested by :</td><td>'+ creator_name +'</td></tr>';
						row += '<tr><td>Contact # :</td><td>'+ creator_tel +'</td></tr>';
						row += '</table>';
						
						$('#requisition_form .request-info').append(row);
					}
					
					if(data.rf_list.length > 0) { 
						var row2 	= '';						
						row2 += '<tr><th>#</th><th>Item Name</th><th>Item Description</th><th>Unit</th><th>Qty</th><th>Remarks</th></tr>';
					
						$.each(rf_list, function(i, row) {									
							$.each(row, function(idx, item) {
								var num 	= idx + 1;
								var remark	=  (item.remark == null) ? "" : item.remark;
								
								console.log(idx+' [rf_list] item: ', item);
								row2 += '<tr><td style="text-align:center;">'+num+'</td>';
								row2 += '<td style="text-align:left;">'+item.name+'</td>';
								row2 += '<td style="text-align:left;">'+item.description+'</td>';
								
								if(item.unit == null) {
									row2 += '<td>-</td>';
								} else {
									row2 += '<td style="text-align:center;">'+item.unit+'</td>';
								}								
								row2 += '<td style="text-align:center;">'+item.qty+'</td>';
								row2 += '<td>'+ remark +'</td>';
								row2 += '</tr>';
							}); 
							
								
						});
						
						$('#requisition_form .table-rf').append(row2);
					}
					
                } else{
                    // printErrorMsg(data.status);
					AlertPopup("<strong>WARNING</strong><br>" + data.status);
                }
                // window.location.href = window.location.href;
            },

        });
	}
	
	function ListRfTable(project_id, by_status, source, rf_id) {
        console.log('ListRfTable() ==> status: ' + by_status);
        var date	= new Date();
		var month 	= date.getMonth() + 1;
			month 	= (month < 10) ? '0'+month : month;
		var day		= date.getDate();			
		var today	= date.getFullYear() + month + day;      
        var tableName   = "rflist_"+by_status;
		
		if(rf_id == "" || rf_id == undefined) {
			rf_id = "";
		}

        var row = '';
		row += '<table id="'+tableName+'" class="table table-bordered mt-15 table_rflist_'+by_status+' table-hover" data-category="0">';
		row += '<thead>';
		row += '<tr>';
		row += '<th style="width:5%">#</th>';
		row += '<th class="excelExport" style="width:10%">RF #</th>';	

        if(by_status == "pending" || by_status == "approve" || by_status == "completed" || by_status == "rejected") {		            	
            row += '<th class="excelExport" style="width:5%">Total Item</th>';	            	
            row += '<th class="excelExport" style="width:15%">Requested by</th>';	
			// row += '<th class="excelExport" style="width:10%">PO #</th>';	
			// row += '<th class="excelExport" style="width:10%">DO #</th>';			
			
		} else if(by_status == "po") {			            
            row += '<th class="excelExport" style="width:30%">Requested by</th>';		
            row += '<th class="excelExport" style="width:10%">PO #</th>';	
			row += '<th class="excelExport" style="width:5%">Total Item</th>';			
		   
		} else if(by_status == "do") {			            
            row += '<th class="excelExport" style="width:30%">Requested by</th>';		
            row += '<th class="excelExport" style="width:10%">DO #</th>';	
			row += '<th class="excelExport" style="width:5%">Total Item</th>';	

		} 
		// row += '<th class="excelExport" style="width:6%">Status</th>';
		row += '<th class="excelExport" style="width:10%">Create Date</th>';			
		row += '<th style="width:6%">Action</th>';
		row += '</tr>';
		row += '</thead>';
		row += '<tbody>';
		row += '</tbody>';
		row += '</table>';
		$('#add_newPOItem #ListSearch').html(row);

        var formData = {
			'by_status'	    : by_status,
			'project_id'	: project_id,
			'source'		: source,
			'rf_id'			: rf_id,
		};
        
        console.log('ajax_url ==>  ' + APP_URL + '/site/requisition/list',);
        console.log('[tableName: '+tableName+'] formData ==>  ', formData);

		var columns = "";
		
		if(by_status == "pending" || by_status == "approve" || by_status == "completed" || by_status == "rejected") {
			columns 	= [
				{ "data": null,"sortable": false, 
                    render: function (data, type, row, meta) {
                                return meta.row + meta.settings._iDisplayStart + 1;
                    }  
                },				
                { data: 'requisition_no', name: 'requisition_no' },                  
                { data: 'total_item', name: 'total_item' },    
                { data: 'create_by', name: 'create_by' },                  
                // { data: 'po', name: 'po' },                  
                // { data: 'do', name: 'do' },                  
                // { data: 'status', name: 'status' }, 
				{ data: 'create_at', name: 'create_at' },				
                { data: 'action', name: 'action'},
			];
			
		} else {
			columns 	= [
				{ "data": null,"sortable": false, 
                    render: function (data, type, row, meta) {
                                return meta.row + meta.settings._iDisplayStart + 1;
                    }  
                },				
                { data: 'requisition_no', name: 'requisition_no' },  
				// { data: 'total_item', name: 'total_item' }, 				
                { data: 'create_by', name: 'create_by' },                  
                { data: 'contact', name: 'contact' },                  
                // { data: 'status', name: 'status' },    
				{ data: 'create_at', name: 'create_at' },				
                { data: 'action', name: 'action'},
			];
		}
		
		// console.log('[columns]', columns);
		
        var rf_table = $('#'+tableName).DataTable({
            processing  : true,
            serverSide  : false,
			responsive: false,
            // dom		    : 'lBfrtip',
			// dom: `
				// <'row'<'col-sm-12 col-md-5 text-left'f><'col-sm-12 col-md-7 text-right dataTables_pager'lB>>
				// <'row'<'col-sm-12'tr>>
				// <'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 'p>>`,
            ajax        : {
				headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: APP_URL + '/site/requisition/list',
				type: "post",  		
				data: formData,
				error: function(){  
					console.log("error");
				}
			}, 
            columnDefs: [				
				{
					"targets"	: [0,2,3, 4, 5],
					"className"	: "text-center",
				}
			],
			
			columns: columns,
            order: [[1, 'desc']]
        });         
        
    }

	function ListRfItem(project_id, id) {
		$('#add_newPOItem #ListSearch').empty();
		$("#add_newPOItem .po_no").html('No. : ');
		
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },           
            url: APP_URL + '/site/requisition/detail',
            type: "POST",
            data: {
				// 'project_id'	: project_id,	
				'project_id'	: project_id,	
                'id'      		: id,         
            },
            // contentType: false,
			// processData: false,       
            dataType: 'json',            
            success:function(data){
                $('#requisition_form .request-info').empty();				
				var company_info	= data.company_info[0]; 
				var rf_detail 		= data.rf_detail[0];
				var rf_list			= data.rf_list; 
				// return;
				console.log('[company_info_length: '+ data.company_info.length+ '] [rf_detail_length: '+data.rf_detail.length+']');
				console.log('rf_detail: ', data.rf_detail[0]);
				console.log('rf_list: ', data.rf_list[0]);
                // $('#ConfirmDelete').modal('hide');
                var row 	= '';				
                if(data.status == "success" ){	
					if(data.company_info.length > 0) {						
						$("#requisition_form .address-box").html('<div>'+company_info.residential_name+', </div>'+'<div>'+company_info.residential_addr+'</div><div>Tel:</div>');
						$("#requisition_form .to-info").html('<strong>To:</strong><br>Headquarters<br>'+company_info.company_addr);  
						$("#requisition_form .logo-rf").css('background-image', 'url('+ APP_URL + '/images/logo/' + company_info.logo + ')');
					}
					
					if(data.rf_detail.length > 0) {
						var create_dt 	= new Date(rf_detail.create_at);
							create_dt 	= ('0' + create_dt.getDate()).slice(-2) + '/' + ('0' + (create_dt.getMonth() + 1)).slice(-2) + '/' + create_dt.getFullYear();
						
						var creator_name= (rf_detail.creator_name == null) ? "" : rf_detail.creator_name;
						var creator_tel	= (rf_detail.creator_tel == null) ? "" : rf_detail.creator_tel;
						
						$("#requisition_form .rf_no").html('No. : '+rf_detail.requisition_no);
						row += '<table class="table table-borderless">';
						row += '<tr><td>Request Date :</td><td>'+ create_dt +'</td></tr>';
						row += '<tr><td>Requested by :</td><td>'+ creator_name +'</td></tr>';
						row += '<tr><td>Contact # :</td><td>'+ creator_tel +'</td></tr>';
						row += '</table>';
						
						$('#requisition_form .request-info').append(row);
						$('#add_newPOItem .modal-title').text('Add PO Item - '+rf_detail.requisition_no);
						$('#add_newPOItem #ListItem').data('rf-id', rf_detail.id);
						$('#add_newPOItem #ListItem').data('rf-no', rf_detail.requisition_no);
					}
					
					if(data.rf_list.length > 0) { 
						var row2 	= '';	
						row2 += '<table class="table table-bordered table_po_item">';
						row2 += '<tr><th>#</th><th>Item Name</th><th>Item Description</th><th>Unit</th><th>Qty</th><th>Remark</th></tr>';
					
						$.each(rf_list, function(i, row) {									
							$.each(row, function(idx, item) {
								var num 	= idx + 1;
								var remark		=  (item.remark == null) ? "" : item.remark;
								var rf_item_id	=  (item.rf_item_id == null) ? "" : item.rf_item_id;
								
								console.log(idx+' [rf_list] item: ', item);
								if(item.is_available == "yes") {
									row2 += '<td><input type="checkbox" name="po_item" data-id="'+item.item_id+'"></td>';
								} else {
									row2 += '<td></td>';
								}
								// row2 += '<tr><td><input type="checkbox" name="po_item" data-id="'+item.item_id+'"></td>';
								row2 += '<td style="text-align:left;">'+item.name+'</td>';
								row2 += '<td style="text-align:left;">'+item.description+'</td>';
								
								if(item.unit == null) {
									row2 += '<td>-</td>';
								} else {
									row2 += '<td style="text-align:center;">'+item.unit+'</td>';
								}								
								row2 += '<td style="text-align:center;" data-rf-item-id="'+rf_item_id+'">'+item.qty+'</td>';
								row2 += '<td>'+ remark +'</td>';
								// row2 += '<td style="text-align:center;"><input type="number" name="po_qty_'+item.item_id+'" class="form-control" min="0" max="'+item.qty+'"></td>';
								// row2 += '<td><textarea class="form-control" name="po_remark_'+item.item_id+'"></textarea></td>';
								row2 += '</tr>';
							}); 		
								
						});
						
						row2 += '</table>'
						
						$('#add_newPOItem #ListItem').append(row2);
						$('#add_newPOItem .btnConfirm').show();
						$('#add_newPOItem .btnBack').show();
					}
					
                } else{
                    // printErrorMsg(data.status);
					AlertPopup("<strong>WARNING</strong><br>" + data.status);
                }
                // window.location.href = window.location.href;
            },
		});
	}

	function GetPoDetail(project_id, id) {
		// var formData = {
			// 'by_status'	    : by_status,
			// 'project_id'	: project_id,			
		// };
		$('#po_form .table-po').empty();
		$("#po_form .po_no").html('No. : ');
		
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },           
            url: APP_URL + '/site/po/detail',
            type: "POST",
            data: {					
				'project_id'	: project_id,
                'id'      		: id,
            },
            // contentType: false,
			// processData: false,       
            dataType: 'json',            
            success:function(data){
                $('#po_form .request-info').empty();				
				var company_info	= data.company_info[0]; 
				var po_detail 		= data.po_detail[0];
				var po_list			= data.po_list; 
				// return;
				console.log('[company_info_length: '+ data.company_info.length+ '] [rf_detail_length: '+data.po_detail.length+']');
				console.log('po_detail: ', data.po_detail[0]);
				console.log('po_list: ', data.po_list[0]);
                // $('#ConfirmDelete').modal('hide');
                var row 	= '';				
                if(data.status == "success" ){	
					if(data.company_info.length > 0) {						
						$("#po_form .address-box").html('<div>'+company_info.residential_name+', </div>'+'<div>'+company_info.residential_addr+'</div><div>Tel:</div>');
						$("#po_form .to-info").html('<strong>To:</strong><br>Headquarters<br>'+company_info.company_addr);  
						$("#po_form .logo-rf").css('background-image', 'url('+ APP_URL + '/images/logo/' + company_info.logo + ')');
					}
					
					if(data.po_detail.length > 0) {
						var create_dt 	= new Date(po_detail.create_at);
							create_dt 	= ('0' + create_dt.getDate()).slice(-2) + '/' + ('0' + (create_dt.getMonth() + 1)).slice(-2) + '/' + create_dt.getFullYear();
						
						var po_date		= (po_detail.po_date == null) ? "" : po_detail.po_date;
						var creator_name= (po_detail.creator_name == null) ? "" : po_detail.creator_name;
						var creator_tel	= (po_detail.creator_tel == null) ? "" : po_detail.creator_tel;
						var vendor_company	= (po_detail.vendor_company == null) ? "" : po_detail.vendor_company;
						var vendor_addr	= (po_detail.vendor_addr == null) ? "" : po_detail.vendor_addr;
						
						$("#po_form .po_no").html('No. : '+po_detail.po_no);						
						$("#po_form .to-info").html('<strong>To:</strong><br>'+vendor_company+'<br>'+ vendor_addr);  
						row += '<table class="table table-borderless">';
						row += '<tr><td>PO Date :</td><td>'+ create_dt +'</td></tr>';
						row += '<tr><td>Created by :</td><td>'+ creator_name +'</td></tr>';
						// row += '<tr><td>Vendor :</td><td>'+ vendor_company +' - - '+vendor_company+'</td></tr>';
						// row += '<tr><td>Contact # :</td><td>'+ creator_tel +'</td></tr>';
						row += '</table>';
						
						$('#po_form .request-info').append(row);
					}
					
					if(data.po_list.length > 0) { 
						var row2 	= '';						
						row2 += '<tr><th>#</th><th>Item Name</th><th>Item Description</th><th>Unit</th><th>Qty</th><th>Remarks</th></tr>';
					
						$.each(po_list, function(i, row) {									
							$.each(row, function(idx, item) {
								var num 	= idx + 1;
								var remark	=  (item.remark == null) ? "" : item.remark;
								
								console.log(idx+' [po_list] item: ', item);
								row2 += '<tr><td style="text-align:center;">'+num+'</td>';
								row2 += '<td style="text-align:left;">'+item.name+'</td>';
								row2 += '<td style="text-align:left;">'+item.description+'</td>';
								
								if(item.unit == null) {
									row2 += '<td>-</td>';
								} else {
									row2 += '<td style="text-align:center;">'+item.unit+'</td>';
								}								
								row2 += '<td style="text-align:center;">'+item.qty+'</td>';
								row2 += '<td>'+ remark +'</td>';
								row2 += '</tr>';
							}); 
							
								
						});
						
						$('#po_form .table-po').append(row2);
					}
					
                } else{
                    // printErrorMsg(data.status);
					AlertPopup("<strong>WARNING</strong><br>" + data.status);
                }
                // window.location.href = window.location.href;
            },

        });
	}
	
	
	function EditGetPoDetail(project_id, id) {		
		$('#add_newPOItem .table-rf').empty();
		$("#add_newPOItem .po_no").html('No. : ');
		
		$("#PoDetail .selectPO").hide();
		$("#PoDetail .uploadPO").show();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },           
            url: APP_URL + '/site/po/detail',
            type: "POST",
            data: {
				// 'project_id'	: project_id,	
				'project_id'	: project_id,	
                'id'      		: id,         
            },
            // contentType: false,
			// processData: false,       
            dataType: 'json',            
            success:function(data){
                $('#add_newPOItem .request-info').empty();				
				var company_info	= data.company_info[0]; 
				var po_detail 		= data.po_detail[0];
				var po_list			= data.po_list; 
				
				console.log('[company_info_length: '+ data.company_info.length+ '] [po_detail_length: '+data.po_detail.length+']');
				console.log('po_detail: ', data.po_detail[0]);
				console.log('po_list: ', data.po_list[0]);
                // $('#ConfirmDelete').modal('hide');
                var row 	= '';
				var row2 	= '';
                if(data.status == "success" ){						
					if(data.po_list.length > 0) { 
						var po_date = formatDate (po_detail.po_date); // "18/01/2022"
						// var row2 	= '';						
						// row2 += '<tr><th>#</th><th>Item Name</th><th>Item Description</th><th>Unit</th><th>Qty</th><th>Remarks</th></tr>';
						$("#kt_content .container .po_no").text(po_detail.po_no);
						$("#kt_repeater_2").data('rf-id', po_detail.requisition_id);
						$(".rf_no").data('id', po_detail.requisition_id);
						$(".rf_no").text(po_detail.requisition_no);
						$("#PoDetail #po_no").val(po_detail.po_no);
						$("#PoDetail #SelectVendor").selectpicker('val', po_detail.vendor_id);
						$("#PoDetail #kt_datepicker_4_1").datepicker('update', po_date);
						// $("#PoDetail #kt_datepicker_4_1").datepicker('update', po_detail.po_date);
						// $("#PoDetail #kt_datepicker_4_1").val(po_detail.po_date);						
						
						if(po_detail.po_file != undefined || po_detail.po_file != "") {
							row += '<div class="img_item" data-file="'+po_detail.po_file+'">';
							row += '<a href="#imgPDF" class="font-weight-bold">'+po_detail.po_no+'</a>&nbsp;&nbsp;';
							row += '<a href="#" class="remove-link" data-id="0" data-file="'+po_detail.po_file+'" data-toggle="modal" data-target="#ConfirmDelete"><i class="fas fa-trash-alt"></i></a>';						
							row += '<a href="#" class="lightbox" id="imgPDF"><iframe src="'+APP_URL+po_detail.po_file+'" title="'+po_detail.po_no+'" class="lightbox-pdf"></iframe></a>';
							row +=  '</div>'; 			
						
							// row += '<a href="#" class="lightbox" id="img1"><iframe src="'+APP_URL+data.path+'" class="lightbox-pdf">PO File</iframe></a>';
							$("#PoDetail .doc_preview").append(row);
						}
						
						$.each(po_list, function(i, line) {									
							$.each(line, function(idx, item) {								
								var item_id		=  (item.item_id == null) ? "" : item.item_id;
								var name		=  (item.name == null) ? "" : item.name;
								var unit		=  (item.unit == null) ? "" : item.unit;
								var qty			=  (item.qty == null) ? "" : item.qty;
								var desc		=  (item.description == null) ? "" : item.description;
								var remark		=  (item.remark == null) ? "" : item.remark;
								var img			=  (item.img == null) ? "" : item.img;
								var rf_item_id	=  (item.requisition_item_id == null) ? "" : item.requisition_item_id;
								
								if(arrPO.includes(item_id) == false) {
									arrPO.push(item_id);
									 
									var temp = {
										'id'    : item_id,
										'name'  : name,
										'desc'  : desc,
										'unit'  : unit,
										'img'   : img
									};  
				
									row2 += '<tr id="'+ item_id+'">';								
									row2 += '<td></td>';
									row2 += '<td class="text-left">'+name+' - '+desc+'</td>';
									row2 += '<td>'+unit+'</td>';
									row2 += '<td><input type="number" name="qty" class="form-control" placeholder="Qty" min="0" data-id="'+ item_id +'" data-rf-item-id="'+rf_item_id+'" value="'+qty+'" /></td>';
									row2 += '<td><input type="text" name="remark_'+ item.item_id +'" class="form-control" placeholder="Remarks" /></td>';
									row2 += '<td><a href="javascript:;" data-repeater-delete=""  data-toggle="modal" data-target="#delete_rf_item" class="btn btn-sm font-weight-bolder btn-light-danger btnDelete" data-id="'+ item_id +'"><i class="fas fa-trash-alt"></i></a></td>';
									row2 += '</tr>';
								
									return temp;
								} else {
									return;
								}
								
							}); 							
								
						});
												
						// $('#requisition_form .table-rf').append(row2);
						$("#kt_repeater_2 table.table_rf_new_item").append(row2);
					}
					
                } else{
                    // printErrorMsg(data.status);
					AlertPopup("<strong>WARNING</strong><br>" + data.status);
                }                
            },

        });
	}

});