$(function () {
	console.log('inventory-site.js');
	
	var arrInventory= [];
    var cur_url     = window.location.pathname;
    var arr_url     = cur_url.split('/');
    var project_id  = 0;
	var page 		= "";
	
	if(arr_url[3] == "inventory") {
        project_id = arr_url[4];

        if(arr_url[5] == undefined) {
            ListTable(project_id);			
        } 
		else if(arr_url[5] == "detail") {
			var id 	= getQueryVariable('ref');
			ListLogTable(project_id, id);
			
			$( ".datepicker" ).datepicker({
				format: 'dd/mm/yyyy',
				minDate: moment("12/01/2000"),				
			});
		}
		page	= arr_url[5];
    }
	
	$('.btnFilter').on('click', function() {		
		var start_date	= $('#kt_datepicker_5 input[name=start]').val();
		var end_date	= $('#kt_datepicker_5 input[name=end]').val();
		var id		 	= getQueryVariable('ref');
		
		console.log('[.btnFilter] [start_date: '+start_date+'] [end_date: '+end_date+']');
		
		ListLogTable(project_id, id)
	});
	
	function getQueryVariable(variable) {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i=0;i<vars.length;i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) {
				return pair[1];
			}
		} 
		// alert('Query Variable ' + variable + ' not found');
	}

	function ListTable(project_id) {
        console.log('ListTable() ');
        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	= "inventory_list";	

        var row = '';
		row += '<table id="'+tableName+'" class="table table-bordered mt-15 table_inventory_list table-hover" data-category="0">';
		row += '<thead>';
		row += '<tr>';
		row += '<th style="width:3%">#</th>';		
		row += '<th class="excelExport" style="width:20%">Item Name</th>';
		row += '<th class="excelExport" style="width:25%">Item Description</th>';
		row += '<th class="excelExport" style="width:15%">Last Transaction Date</th>';
		row += '<th class="excelExport" style="width:10%">Balance</th>';
		row += '<th class="excelExport" style="width:8%">Unit</th>';
		row += '<th class="excelExport" style="width:5%">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/inventory/list',);
        console.log('[tableName: '+tableName+'] formData ==>  ', formData);
		
		var	columns = [
			{ "data": null,"sortable": false, 
				render: function (data, type, row, meta) {
							return meta.row + meta.settings._iDisplayStart + 1;
				}
			},				
			{ data: 'item_name', name: 'item_name' },
			{ data: 'desc', name: 'desc' },
			{ data: 'tranx_date', name: 'tranx_date' },
			{ data: 'balance', name: 'balance' },			
			{ data: 'unit', name: 'unit' },			
			{ data: 'action', name: 'action'},
		];
		
        var po_table = $('#'+tableName).DataTable({
            processing  : true,
            serverSide  : true,
			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 + '/site/inventory/list',
				type: "post",  		
				data: formData,
				error: function(){  
					console.log("error");
				}
			}, 
            columnDefs: [				
				{
					"targets"	: [0,3,4,5,6],
					"className"	: "text-center",
				}
			],
			buttons: [
				{
					extend: 'collection',
					text: 'Export',
					buttons: [
						'copy',		
						{ extend: 'csv', filename: 'Inventory_List_'+today },
						{ extend: 'excel', filename: 'Inventory_List_'+today },						
						{ extend: 'pdf', filename: 'Inventory_List_'+today },										
						'print'
					]
				}
			],
			columns: columns,
            order: [[1, 'desc']]
        });         
        
    }
	
	function ListLogTable(project_id, id) {
        console.log('ListLogTable() ');
        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	= "inventory_log";	
		
		var start_date	= $('#kt_datepicker_5 input[name=start]').val();
		var end_date	= $('#kt_datepicker_5 input[name=end]').val();
		
		if(start_date == undefined) {
			start_date = "";
		}
		
		if(end_date == undefined) {
			end_date = "";
		}

        var row = '';
		row += '<table id="'+tableName+'" class="table table-bordered mt-15 table_inventory_log table-hover" data-category="0">';
		row += '<thead>';
		row += '<tr>';
		row += '<th style="width:3%">#</th>';		
		row += '<th class="excelExport" style="width:20%">Transaction Date</th>';
		row += '<th class="excelExport" style="width:25%">Source / Destination</th>';
		row += '<th class="excelExport" style="width:8%">Unit</th>';
		row += '<th class="excelExport" style="width:15%">Qty</th>';
		row += '<th class="excelExport" style="width:10%">Last Balance</th>';		
		// row += '<th class="excelExport" style="width:5%">Action</th>';
		row += '</tr>';
		row += '</thead>';
		row += '<tbody>';
		row += '</tbody>';
		row += '</table>';
		$('#ListLogTable').html(row);

        var formData = {
			// 'by_status'	    : by_status,
			'item_id'		: id,
			'project_id'	: project_id,
			'source'		: 'detail',
			'start_date'	: start_date,
			'end_date'		: end_date,
		};
        
        console.log('ajax_url ==>  ' + APP_URL + '/site/inventory/log',);
        console.log('[tableName: '+tableName+'] formData ==>  ', formData);
		
		var	columns = [
			{ "data": null,"sortable": false, 
				render: function (data, type, row, meta) {
							return meta.row + meta.settings._iDisplayStart + 1;
				}
			},
			{ data: 'create_at', name: 'create_at' },
			{ data: 'do_no', name: 'do_no' },			
			{ data: 'unit', name: 'unit' },
			{ data: 'qty', name: 'qty' },
			{ data: 'balance', name: 'balance' },			
			// { data: 'action', name: 'action'},
		];
		
        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 + '/site/inventory/log',
				type: "post",  		
				data: formData,
				error: function(){  
					console.log("error");
				}
			}, 
            columnDefs: [				
				{
					"targets"	: [0,1,2,3,4,5],
					"className"	: "text-center",
				}
			],
			buttons: [
				{
					extend: 'collection',
					text: 'Export',
					buttons: [
						'copy',		
						{ extend: 'csv', filename: 'Inventory_List_'+today },
						{ extend: 'excel', filename: 'Inventory_List_'+today },						
						{ extend: 'pdf', filename: 'Inventory_List_'+today },										
						'print'
					]
				}
			],
			columns: columns,
            order: [[1, 'desc']]
        });         
        
    }
	
});