$(function () {
    console.log('vendor.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];
		page 		= "po";

        if(arr_url[5] == undefined) {
            ListPoTable(project_id, 'new');
        } 
		
    } else if(arr_url[3] == "do") {
		project_id 	= arr_url[4];
		page 		= "po";
		
		 if(arr_url[5] == undefined) {
            ListDoTable(project_id, 'new');
			
        }  else if(arr_url[5] == "edit") {
			var id 	= arr_url[6];
			
			// console.log('[edit] id: '+id);
			EditGetDoDetail(project_id, id);
		}
		
	} 
	
	$(document).on("change", "#do_file", function() {
    // $("#item_image").change(function() {
        // var id 		= $(this).attr("id");
        var id 		= 0;
		var files 	= document.getElementById('do_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', 'vendor_do');
		// formData.append('source', 'do');

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

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: APP_URL + '/vendors/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);
                }                
            },

        });
    });

	
	$(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', '.modal-links.do', function() {
		var id = $(this).data('id');
		console.log('[DO Modal] ID: '+id);
		
		GetDoDetail(project_id, id);
	});
	
	$(document).on('click', '.btnProceed', function() {
        var total_empty = 0;
        var total_row   = 0;
		var type		= 'new';
		var do_id		= $("#DoDetail").data('do-id');		
		var do_file		= $("#DoDetail .img_item").data('file');	
		var vendor_id	= $("#SelectVendor").val();
		var do_date		= $("#kt_datepicker_4_1").val();
		var do_no		= $("#DoDetail #do_no").val();
		var po_id		= $("#kt_repeater_2").data('po-id');
		
        var arr_selected = $("table.table_rf_new_item input[name=qty]").map(function(){ 
            var id      	= $(this).data('id');
			var po_item_id  = $(this).data('po-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,                
                'po_item_id'    : po_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 Delivery Order.");
            return;
        }

        if(total_empty > 0) {
            alert("Please fill in the quantity.");
            return;
        }                

        // console.log('[.btnProceed()] [arr_selected]', arr_selected);
        var ajax_url    = APP_URL + '/vendors/do/store/';
		
		if(arr_url[5] == "edit") {
			do_id		= arr_url[6];
			ajax_url    = APP_URL + '/vendors/do/update/'+do_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,       
                'do_id'         : do_id,   			
                'do_no'         : do_no,   			
                'do_file'		: do_file, 
				'vendor_id'		: vendor_id,
				'po_id'			: po_id,
            },
            success: function(data) {                
                console.log('Create DO Success!');        
                console.log('Error: ', data.error);       

                if(data.status == "success"){
                    alert(data.msg);
                }else{
                    printErrorMsg(data.error);                    
                }               
            },
        });

    });
	
	
	$(document).on('click', '#add_newDOItem .btnConfirm', function() {
		var po_id 			= $('#add_newDOItem #ListItem').data('po-id');	
		var po_no 			= $('#add_newDOItem #ListItem').data('po-no');	
		var selectedPo 		= $('#kt_repeater_2').data('po-id');	
		var selectedRfNo 	= $('#kt_repeater_2').data('po-no');	
		
		if(selectedPo == "" || selectedPo == undefined) {
			$('#kt_repeater_2').data('po-id', po_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(selectedPo != po_id) {
				alert('Different PO ID!');
				return;
			}
		}		
		
        var row = '';
        var searchIDs = $("#add_newDOItem #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 po_item_id	= $(this).closest('tr').find('td').eq(4).data('po-item-id');
            var img     	= $(this).closest('tr').find('td').eq(4).data('img');
           
            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-po-item-id="'+po_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_newDOItem').modal('hide');

        // console.log('[.btnConfirm] [rf_id: '+rf_id+'] searchIDs: ',searchIDs);
        // console.log('[arrPO] ', arrPO);
    });
	
	$(document).on('click', '#add_newDOItem table .btnSelect', function() {
		var id = $(this).data('id');
		
		console.log('[.btnSelect] ID:'+ id);
		ListPoItem(project_id, id);
	});
	
	$(document).on('click', '.btnAddNew, #add_newDOItem .btnBack', function() {
		$('#add_newDOItem #ListItem').empty();
		$('#add_newDOItem .btnConfirm').hide();
		$('#add_newDOItem .btnBack').hide();
		$('#add_newDOItem .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);
        ListPoLessTable(project_id, 'approve', source, rf_id);
    });
	
	$(document).on('click', '.btnUpdateAction', function() {
		var id 		= $(this).data('id');
		var ref_no	= $(this).data('ref-no');
		var action	= $(this).data('action');
		
		switch(action) {
			case "accept"	: 
					$("#ConfirmPopup p").html("Accept this Purchase Order?<br><strong>"+ref_no+" </strong>");       
					$("#ConfirmPopup .btnConfirm").data("source", 'vendor_po');
					$("#ConfirmPopup .btnConfirm").data("id", id);
				break;
		}
	});
	
	$(document).on("click", "#ConfirmPopup .btnConfirm", function() {        
        var id      	= $(this).data('id');
		var ref_no		= $(this).data('ref-no');
		var action		= $(this).data('action');       
		var action_url	= APP_URL + '/vendors/po/update_status/'+id;
		var formData = {
			'id'	    	: id,
			'project_id'	: project_id,
			'update_status'	: 'accept',
		};
		// formData.append('action', 'update_status');		
		
		if(page == "do")
			action_url	= APP_URL + '/vendors/do/update_status/'+id;
		
		console.log('[.btnConfirm] [action: '+action+'] [project_id: '+project_id+ '] formData:', formData);
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            
            url: action_url,
            type: "PUT",
            data: formData, 
            // contentType: false,
			// processData: false,       
            // dataType: 'json',            
            success:function(data){
                console.log(data);
                $('#ConfirmPopup').modal('hide');
                var row = '';
                if(data.status == "success"){
                    // $(".img__preview").empty();    
                    // $(".doc_preview").empty();    
					if(arr_url[3] == "po") {						
						ListPoTable(project_id, 'new');
					}
                } else{
                    // printErrorMsg(data.status);
					console.log('Error');
                }
                // window.location.href = window.location.href;
            },

        });
    });
	
	$(document).on("click", ".delete_img, .remove-link", function() {
		var filename 	= $(this).data('file');
		var id 			= $(this).data('id');
        console.log('[.delete_img] Clicked!');
        console.log('[.delete_img] [id: '+id+'] [filename: '+filename+']');
        
        $("#ConfirmDelete p").html("Are you sure to delete this image?");       
        $("#ConfirmDelete .btnConfirm").data("file", filename);
        $("#ConfirmDelete .btnConfirm").data("id", id);
    });
	
	$(document).on("click", "#ConfirmDelete .btnConfirm", function() {        
        var id      = $(this).data('id');
        var filename = $(this).data('file');
        console.log('[.btnConfirm] Clicked! [id: '+id+'] [filename]'+filename);

        var formData = new FormData();	

		formData.append('id', id);
		formData.append('filename', filename);
		formData.append('source', 'vendor_do');

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },            
            url: APP_URL + '/vendors/fileUpload/delete',
            type: "POST",
            data: formData,
            contentType: false,
			processData: false,
            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);
                }
                // window.location.href = window.location.href;
            },

        });
    });
	
	
	$(document).on('click', '.modal-links.po', function() {
		var id = $(this).data('id');
		console.log('[PO Modal] ID: '+id);
		
		GetPoDetail(project_id, id);
	});
	
	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 + '/admin/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: 'create_by', name: 'create_by' },
                { data: 'contact', name: 'contact' },
             	{ 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: `
				<'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 + '/vendors/po/list',
				type: "post",  		
				data: formData,
				error: function(){  
					console.log("error");
				}
			}, 
            columnDefs: [				
				{
					"targets"	: [0,2,3,4,5,6],
					"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 ListDoTable(project_id, by_status, source) {
        console.log('ListDoTable() ==> 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%">DO #</th>';	      	            
		row += '<th class="excelExport" style="width:5%">Total Item</th>';			
		row += '<th class="excelExport" style="width:6%">Created by</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 + '/vendors/do/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: 'do_no', name: 'do_no' },                  
                { data: 'total_item', name: 'total_item' },                   
                { data: 'create_by', name: 'create_by' },
				{ data: 'create_at', name: 'create_at' },
				{ data: 'status', name: 'status' },
                { 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 + '/vendors/do/list',
				type: "post",  		
				data: formData,
				error: function(){  
					console.log("error");
				}
			}, 
            columnDefs: [				
				{
					"targets"	: [0,2,3,4,5,6],
					"className"	: "text-center",
				}
			],
			buttons: [
				{
					extend: 'collection',
					text: 'Export',
					buttons: [
						'copy',		
						{ extend: 'csv', filename: 'DO_List_'+today },
						{ extend: 'excel', filename: 'DO_List_'+today },						
						{ extend: 'pdf', filename: 'PO_List_'+today },										
						'print'
					]
				}
			],
			columns: columns,
            order: [[1, 'desc']]
        });         
        
    }
	
	function GetPoDetail(project_id, 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 + '/vendors/po/detail',
            type: "POST",
            data: {					
				'project_id'	: project_id,
                'id'      		: id,
            },             
            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; 
				
				// 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]);
               
                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 += '</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);
                }
                // window.location.href = window.location.href;
            },

        });
	}
	
	function ListPoLessTable(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%">Created By</th>';				
		} else if(by_status == "do") {			            
            row += '<th class="excelExport" style="width:30%">Vendor</th>';          
			row += '<th class="excelExport" style="width:5%">Total Item</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);
		$('#add_newDOItem #ListSearch').html(row);

        var formData = {
			'by_status'	    : by_status,
			'project_id'	: project_id,
			'source'		: 'vendor_add_do',
		};
        
        console.log('ajax_url ==>  ' + APP_URL + '/admin/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: 'create_by', name: 'create_by' },             
				{ 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: 'create_by', name: 'create_by' },
                { data: 'contact', name: 'contact' },              
				{ data: 'create_at', name: 'create_at' },
                { data: 'action', name: 'action'},
			];
		}
		
        var po_table = $('#'+tableName).DataTable({
            processing  : true,
            serverSide  : true,
			responsive: true,          			
            ajax        : {
				headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: APP_URL + '/vendors/po/list',
				type: "post",  		
				data: formData,
				error: function(){  
					console.log("error");
				}
			}, 
            columnDefs: [				
				{
					"targets"	: [0,2,3,4,5,6],
					"className"	: "text-center",
				}
			],			
			columns: columns,
            order: [[1, 'desc']]
        });         
        
    }

	function ListPoItem(project_id, id) {
		$('#add_newDOItem #ListSearch').empty();
		$("#add_newDOItem .po_no").html('No. : ');
		
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },           
            url: APP_URL + '/vendors/po/detail',
            type: "POST",
            data: {				
				'project_id'	: project_id,	
                'id'      		: id,         
            },           
            dataType: 'json',            
            success:function(data){
                $('#requisition_form .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+ '] [rf_detail_length: '+data.po_detail.length+']');
				// console.log('po_detail: ', data.po_detail[0]);
				// console.log('po_list: ', data.po_list[0]);
               
                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.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 creator_name= (po_detail.creator_name == null) ? "" : po_detail.creator_name;
						var creator_tel	= (po_detail.creator_tel == null) ? "" : po_detail.creator_tel;
						
						$("#requisition_form .rf_no").html('No. : '+po_detail.po_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_newDOItem .modal-title').text('Add PO Item - '+po_detail.po_no);
						$('#add_newDOItem #ListItem').data('po-id', po_detail.id);
						$('#add_newDOItem #ListItem').data('po-no', po_detail.po_no);
					}
					
					if(data.po_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(po_list, function(i, row) {									
							$.each(row, function(idx, item) {
								var num 	= idx + 1;
								var remark		=  (item.remark == null) ? "" : item.remark;
								var po_item_id	=  (item.po_item_id == null) ? "" : item.po_item_id;
								
								console.log(idx+' [po_list] item: ', item);
								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-po-item-id="'+po_item_id+'">'+item.qty+'</td>';
								row2 += '<td>'+ remark +'</td>';								
								row2 += '</tr>';
							});
						});
						
						row2 += '</table>'
						
						$('#add_newDOItem #ListItem').append(row2);
						$('#add_newDOItem .btnConfirm').show();
						$('#add_newDOItem .btnBack').show();
					}
					
                } else{
                    printErrorMsg(data.status);
                }
                // window.location.href = window.location.href;
            },
		});
	}

	function GetDoDetail(project_id, id) {
		$('#do_form .table-po').empty();
		$("#do_form .do_no").html('No. : ');
		
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },           
            url: APP_URL + '/vendors/do/detail',
            type: "POST",
            data: {					
				'project_id'	: project_id,
                'id'      		: id,
            },             
            dataType: 'json',            
            success:function(data){
                $('#do_form .request-info').empty();				
				var company_info	= data.company_info[0]; 
				var do_detail 		= data.do_detail[0];
				var do_list			= data.do_list; 
				
				// console.log('[company_info_length: '+ data.company_info.length+ '] [do_detail_length: '+data.do_detail.length+']');
				console.log('company_info: ', data.company_info[0]);
				// console.log('po_detail: ', data.po_detail[0]);
				// console.log('po_list: ', data.po_list[0]);
               
                var row 	= '';				
                if(data.status == "success" ){	
					if(data.company_info.length > 0) {						
						// $("#do_form .address-box").html('<div>'+company_info.residential_name+', </div>'+'<div>'+company_info.residential_addr+'</div><div>Tel:</div>');
						$("#do_form .to-info").html('<strong>To:</strong><br><strong>'+company_info.residential_name+'</strong><br>'+company_info.residential_addr);  
						$("#do_form .logo-rf").css('background-image', 'url('+ APP_URL + '/images/logo/' + company_info.logo + ')');
					}
					
					if(data.do_detail.length > 0) {
						var create_dt 	= new Date(do_detail.create_at);
							create_dt 	= ('0' + create_dt.getDate()).slice(-2) + '/' + ('0' + (create_dt.getMonth() + 1)).slice(-2) + '/' + create_dt.getFullYear();
						
						var do_date		= (do_detail.do_date == null) ? "" : do_detail.do_date;
						var creator_name= (do_detail.creator_name == null) ? "" : do_detail.creator_name;
						var creator_tel	= (do_detail.creator_tel == null) ? "" : do_detail.creator_tel;
						var vendor_company	= (do_detail.vendor_company == null) ? "" : do_detail.vendor_company;
						var vendor_addr	= (do_detail.vendor_addr == null) ? "" : do_detail.vendor_addr;
						
						$("#do_form .do_no").html('No. : '+do_detail.do_no);						
						// $("#do_form .to-info").html('<strong>To:</strong><br>'+vendor_company+'<br>'+ vendor_addr);  
						row += '<table class="table table-borderless">';
						row += '<tr><td>DO Date :</td><td>'+ create_dt +'</td></tr>';
						row += '<tr><td>Created by :</td><td>'+ creator_name +'</td></tr>';						
						row += '</table>';
						
						$('#do_form .request-info').append(row);
					}
					
					if(data.do_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(do_list, function(i, row) {									
							$.each(row, function(idx, item) {
								var num 	= idx + 1;
								var remark	=  (item.remark == null) ? "" : item.remark;
								
								console.log(idx+' [do_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>';
							}); 
						});
						
						$('#do_form .table-po').append(row2);
					}
					
                } else{
                    printErrorMsg(data.status);
                }
                // window.location.href = window.location.href;
            },

        });
	}	
	
	function EditGetDoDetail(project_id, id) {
		console.log('EditGetDoDetail() . . .');
		$('#add_newDOItem .table-rf').empty();
		$("#add_newDOItem .po_no").html('No. : ');
		
		$("#PoDetail .selectPO").hide();
		$("#PoDetail .uploadPO").show();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: APP_URL + '/vendors/do/detail',
            type: "POST",
            data: {				
				'project_id'	: project_id,
                'id'      		: id,
            },
            dataType: 'json',            
            success:function(data){
                $('#add_newDOItem .request-info').empty();				
				var company_info	= data.company_info[0]; 
				var do_detail 		= data.do_detail[0];
				var do_list			= data.do_list; 
				
				// console.log('[company_info_length: '+ data.company_info.length+ '] [do_detail_length: '+data.do_detail.length+']');
				console.log('company_info: ', data.company_info[0]);
				console.log('do_detail: ', data.do_detail[0]);
				console.log('do_list: ', data.do_list[0]);
                // $('#ConfirmDelete').modal('hide');
                var row 	= '';
				var row2 	= '';
                if(data.status == "success" ){						
					if(data.do_list.length > 0) { 
						var do_date = formatDate (do_detail.do_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(do_detail.po_no);
						$("#kt_repeater_2").data('rf-id', do_detail.po_id);
						$(".rf_no").data('id', do_detail.po_no);
						$(".rf_no").text(do_detail.po_no);
						$("#DoDetail #do_no").val(do_detail.do_no);
						$("#DoDetail #SelectVendor").selectpicker('val', do_detail.vendor_id);
						$("#DoDetail #kt_datepicker_4_1").datepicker('update', do_date);					
						
						if(do_detail.do_file != undefined && do_detail.do_file != "" && do_detail.do_file != null) {
							var img_url = APP_URL+'/document/'+do_detail.company_id+'/do/'+do_detail.do_file
							console.log('GOT FILE!  do_file: ', do_detail.do_file);
							row += '<div class="img_item" data-file="'+do_detail.do_file+'">';
							row += '<a href="#imgPDF" class="font-weight-bold">'+do_detail.do_no+'</a>&nbsp;&nbsp;';
							row += '<a href="#" class="remove-link" data-id="'+do_detail.id+'" data-file="'+do_detail.do_file+'" data-toggle="modal" data-target="#ConfirmDelete"><i class="fas fa-trash-alt"></i></a>';						
							row += '<a href="#" class="lightbox" id="imgPDF"><iframe src="'+ img_url+'" title="'+do_detail.do_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>';
							$("#DoDetail .doc_preview").append(row);
						}
						
						$.each(do_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 po_item_id	=  (item.po_item_id == null) ? "" : item.po_item_id;
								var do_item_id	=  (item.do_item_id == null) ? "" : item.do_item_id;
								
								if(arrPO.includes(item_id) == false) {
									arrPO.push(item_id);
									 
									var temp = {
										'id'    : do_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-po-item-id="'+po_item_id+'" value="'+qty+'" /></td>';
									row2 += '<td><input type="text" name="remark_'+ 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);
                }                
            },

        });
	}

	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;
	}
	
});