$(function () {
	console.log('do.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] == "do") {
        project_id = arr_url[4];

        if(arr_url[5] == undefined) {
            ListDoTable(project_id, 'new');			
        } 
		else if(arr_url[5] == "edit") {
			var id 	= arr_url[6];
			EditGetDoDetail(project_id, id);
			
			$( ".datepicker" ).datepicker({
				format: 'dd/mm/yyyy',
				minDate: moment("12/01/2000"),				
			});
		}
		page	= arr_url[5];
    }
	
	$(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', '.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 Delivery Order?<br><strong>"+ref_no+" </strong>");       
				$("#ConfirmPopup .btnConfirm").data("source", 'admin_do');
				$("#ConfirmPopup .btnConfirm").data("id", id);
				break;
		}
	});
	
	$(document).on('click', '#do_form .btnAccept, #do_form .btnReject', function() {
		var id 		= $(this).data('do-id');
		var ref_no	= $(this).data('ref-no');
		var action 	= $(this).data('action');
		
		var text	= "Update ";
		console.log('[.btnAccept / .btnReject] [action: '+ action +'] ID: '+ id);
		
		$('#ConfirmPopup .confirmRemark').removeClass('is-invalid');
		$("#ConfirmPopup .divRemark").hide();
		$("#ConfirmPopup .btnConfirm").data("action", action);
		$("#ConfirmPopup .btnConfirm").data("source", 'admin_do');
		$("#ConfirmPopup .btnConfirm").data("id", id);
		
		switch(action) {
			case "accept"	: 
				$("#ConfirmPopup p").html("Accept this Delivery Order?<br><strong>"+ref_no+" </strong>");				
				break;
				
			case "reject"	: 
				$("#ConfirmPopup p").html("Reject this Delivery Order?<br><strong>"+ref_no+" </strong>");				
				$("#ConfirmPopup .divRemark").show();
				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 + '/admin/do/update_status/'+id;
	
		if(page == "do")
			action_url	= APP_URL + '/admin/do/update_status/'+id;
		
		var remark	= $('#ConfirmPopup .confirmRemark').val();
		if(action == "reject"){
			if(remark == "" || remark == undefined) {
				$('#ConfirmPopup .confirmRemark').addClass('is-invalid');
				return;
			}
		}
		
		var formData = {
			'id'	    	: id,
			'project_id'	: project_id,
			'update_status'	: action,
			'remark'		: remark,
		};
		
		console.log('[.btnConfirm] [action: '+action+'] [project_id: '+project_id+ '] formData:', formData);
		// return;
        $.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"){
					ListDoTable(project_id, 'new');
					
                } else{
                    // printErrorMsg(data.status);
					console.log('Error');
                }
                // window.location.href = window.location.href;
            },

        });
    });
	

	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	= "do_list";	//+by_status;

        var row = '';
		row += '<table id="'+tableName+'" class="table table-bordered mt-15 table_dolist_'+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:5%">Status</th>';			
		// row += '<th style="width:10%">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/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: '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 + '/admin/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: 'DO_List_'+today },										
						'print'
					]
				}
			],
			columns: columns,
            order: [[1, 'desc']]
        });         
        
    }
	
	function GetDoDetail(project_id, id) {
		$('#do_form .table-do').empty();
		$("#do_form .do_no").html('No. : ');
		$('#view_file').show();
		
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },           
            url: APP_URL + '/admin/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;
						var do_status		= do_detail.status;
						
						switch(do_status) {
							case 1	: do_status = '<td>Pending</td>';
								break;
							case 2	: do_status = '<td style="color:blue;">Accepted</td>';
								break;
							case 3	: do_status = '<td style="color:orange;">Processing</td>';
								break;
							case 4	: do_status = '<td style="color:green;">Completed</td>';
								break;
							case 5	: do_status = '<td style="color:red;">Rejected</td>';
								break;
								
						}
						
						$("#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 += '<tr><td>Status :</td>'+ do_status +'</tr>';						
						row += '</table>';
						
						$('#do_form .request-info').append(row);
					}
					
					if(data.do_list.length > 0) { 
						var file_url	= APP_URL + '/document/' + company_info.company_id + '/do/' + do_detail.do_file;
						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>';
							}); 
						});
						
						if(do_detail.do_file == '' || do_detail.do_file == undefined) {
							$('#view_file').hide();
						} else {
							$('#iframe_doFile').attr('src', file_url);							
						}
						
						// $('#doFile span').css("background-image", "url('" + file_url + "')");
						$('#do_form button').data("do-id", do_detail.id);
						$('#do_form button').data("ref-no", do_detail.do_no);
						$('#do_form .table-do').append(row2);
						
						$('#do_form button').show(); 						
						
						if(do_detail.status == 5) {
							$('#do_form .btnAccept').hide(); 
							$('#do_form .btnReject').hide(); 
						} else if(do_detail.status == 2) {
							$('#do_form .btnAccept').hide(); 							
						}
					}
					
                } else{
                    printErrorMsg(data.status);
                }
                // window.location.href = window.location.href;
            },

        });
	}	
	

});