$(function () {
    console.log('material.js');

    var cur_url = window.location.pathname;
    var arr_url = cur_url.split('/');

    // console.log('cur_url --> '+cur_url);
    // console.log('arr_url[1] --> '+arr_url[1]);
    // console.log('arr_url[2] --> '+arr_url[2]);

    if(arr_url[4] == "material") {
        if(arr_url[5] == "trade") {
            ListTradeTable();
        } else if(arr_url[5] == "item") {
            ListItemTable();
        } else {
            ListCategoryTable();
        }
    }  

    $(document).on("click", ".btnSaveCategory", function() {
        console.log('[.btnSaveCategory] Clicked!');

        var parent_cat  = $("input[name='parent_cat']").val();
        var cat_name    = $("input[name='category_name']").val();
        var cat_desc    = $("input[name='category_desc']").val();

        console.log('[cat_name: '+cat_name+'] ');

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            // url : "/admin/material/trade/create",
            URL : $(this).attr('action'),
            type: 'POST',           
            data: {
                'type'              : 'category',
                'parent_cat'        : parent_cat,
                'category_name'      : cat_name,
                'category_desc'      : cat_desc,
            },
            success: function(data) {                
                console.log('Create Category Success!');        
                console.log('Error: ', data.error);       

                if($.isEmptyObject(data.error)){
                    alert(data.success);
                }else{
                    printErrorMsg(data.error);
                    
                }
                // window.location = "/admin/material/category";
            },
        });
    });

   
    $(document).on("click", ".btnSaveTrade", function() {
        console.log('[.btnSaveTrade] Clicked!');

        var trade_parent= $("input[name='trade_parent']").val();
        var trade_name  = $("input[name='trade_name']").val();
        var trade_desc  = $("input[name='trade_desc']").val();

        console.log('[trade_name: '+trade_name+'] ');

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            // url : "/admin/material/trade/create",
            URL : $(this).attr('action'),
            type: 'POST',           
            data: {
                'type'          : 'trade',
                'trade_parent'  : trade_parent,
                'trade_name'    : trade_name,
                'trade_desc'    : trade_desc,
            },
            success: function(data) {                
                console.log('Create Trade Success!');        
                console.log('Error: ', data.error);       

                if($.isEmptyObject(data.error)){
                    alert(data.success);
                }else{
                    printErrorMsg(data.error);
                    
                }
                window.location = "/admin/material/trade";
            },
        });
    });

    $(document).on("click", ".action-btn", function() {
        console.log('[.action-btn] Clicked!');

        // var _token = $("input[name='_token']").val();
        // var trade_parent= $("input[name='trade_parent']").val();
        // var trade_name  = $("input[name='trade_name']").val();
        // var trade_desc  = $("input[name='trade_desc']").val();

        // console.log('[trade_name: '+trade_name+'] ');

        // $.ajax({
        //     headers: {
        //         'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        //     },
        //     // url : "/admin/material/trade/create",
        //     URL : $(this).attr('action'),
        //     type: 'POST',           
        //     data: {
        //         'type'          : 'trade',
        //         'trade_parent'  : trade_parent,
        //         'trade_name'    : trade_name,
        //         'trade_desc'    : trade_desc,
        //     },
        //     success: function(data) {                
        //         console.log('Create Trade Success!');        
        //         console.log('Error: ', data.error);        

        //         if($.isEmptyObject(data.error)){
        //             alert(data.success);
        //         }else{
        //             printErrorMsg(data.error);
                    
        //         }
        //         window.location = "/admin/material/trade";
        //     },
        // });
    });

    $(document).on("change", "#item_image", function() {
    // $("#item_image").change(function() {
        var id 		= $(this).attr("id");
		var files 	= document.getElementById('item_image').files[0];
		// var files 	= $('#'+id)[0].files;

        var formData = new FormData();	
		
		// data.append('user_ID', user_ID);
		// data.append('event_id', $("#event-id").val());
		formData.append('id', id);
		formData.append('image', files);

        // $.each(files, function (i, file) {
		// 	console.log('file-'+i+' ==> ', file);
		// 	data.append('file-' + i, file);
		// });

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

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

                    row += '<div class="img_item" data-file="'+data.path+'">';
                    row += '<a href="#img1"><div class="thumb_img" style="background-image: 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('+data.path+')"></span></a>';
                    row +=  '</div>';        

                    $(".img_preview").append(row);
                    // alert('Image Upload Successfully.');
                } else{
                    printErrorMsg(data.status);
                }
                // window.location.href = window.location.href;
            },

        });
    });

    $(document).on("click", ".delete_img", 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', 'material_item');

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

                } else{
                    printErrorMsg(data.status);
                }
                // window.location.href = window.location.href;
            },

        });
    });

    $(document).on("click", ".btnSaveItem", function() {
        var trade       = $("#trade").val();
        var item_id     = $(this).data('id');
        var item_unit   = $("#item_unit").val();
        var item_name   = $("input[name='item_name']").val();
        var item_desc   = $("textarea[name='item_desc']").val();        
        var filename    = $(".img_preview .img_item").data('file');      
        var ajax_url         = "";

        if(item_id == "" || item_id == undefined) {
            ajax_url    = $(this).attr('action');
        } else {
            ajax_url    = APP_URL + '/admin/material/item/update/' + item_id;
        }

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            // url : "/admin/material/trade/create",
            url : ajax_url,
            type: 'POST',           
            data: {
                'type'          : 'item',
                'trade'         : trade,
                'item_name'     : item_name,
                'item_desc'     : item_desc,
                'item_unit'     : item_unit,
                'filename'      : filename,
            },
            success: function(data) {                
                console.log('Create Item Success!');        
                console.log('Error: ', data.error);       

                if($.isEmptyObject(data.error)){
                    alert(data.success);
                }else{
                    printErrorMsg(data.error);
                    
                }
                // window.location = "/admin/material/item";
            },
        });
    });

    function printErrorMsg (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 ListTradeTable() {
        var date	= new Date();
		var month 	= date.getMonth() + 1;
			month 	= (month < 10) ? '0'+month : month;
		var today	= date.getFullYear() + month + date.getDay();
        var tableName = "hq_material_settings";
        var row = '';
		row += '<table id="'+tableName+'" class="table table-bordered mt-15 table_material_settings table-hover" data-category="0" style="width:100%;">';
		row += '<thead>';
		row += '<tr>';
		row += '<th style="width:5%">#</th>';
		row += '<th class="excelExport" style="width:30%">Item Description</th>';		
		row += '<th class="excelExport" style="width:6%">Status</th>';
		row += '<th style="width:6%">Action</th>';
		row += '</tr>';
		row += '</thead>';
		row += '<tbody>';
		row += '</tbody>';
		row += '</table>';
		$('#ListTable').html(row);

        var formData = {
			'action'	: "listing",
			// 'user_ID'	: user_ID
		};

        // $('#hq_material_settings').DataTable().destroy();
        var trade_table = $('#hq_material_settings').DataTable({
            processing  : true,
            serverSide  : true,
            dom		    : 'lBfrtip',
            ajax        : {
				headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: APP_URL + '/admin/material/trade/list',
				type: "post",  		
				data: formData,
				error: function(){  
					console.log("error");
				}
			}, 
            columnDefs: [				
				{
					"targets"	: [0,2,3],
					"className"	: "text-center",
				}
			],
            buttons: [
				{
					text: "<i class='fa fa-download' style='vertical-align:middle;'></i> <label style='margin:5px;'>Export</label>",
					extend: 'excelHtml5',
                    exportOptions: {
						columns: '.excelExport'
					},
					filename: 'Trade_List_'+today,
					title: '',
					className: 'btn-export',
					action: function (e, dt, button, config) {
						var that = this;
						if(confirm("Do you want to export trade listing to Excel file?")) {
							console.log('COnfirm == OK');
							that.processing(true);
							that.disable();
							setTimeout(function () {
								console.log('[excelHtml5]button',button);
								$.fn.dataTable.ext.buttons.excelHtml5.action.call(that, e, dt, button, config);
								
							}, 500);
							that.enable();
						} else {
							console.log('Confirm == Cancel');
						}
					}
				},
			],			
            // ajax        : "{{route('admin.getTradeList')}}",
            columns: [
                // { data: 'id', name: 'id' },
                { "data": null,"sortable": false, 
                    render: function (data, type, row, meta) {
                                return meta.row + meta.settings._iDisplayStart + 1;
                    }  
                },
                { data: 'name', name: 'name' },                  
                { data: 'status', name: 'status' },                  
                { data: 'action', name: 'action'},
            ],
            order: [[1, 'asc']]
        }); 
        
        // trade_table.on( 'order.dt search.dt', function () {
        //     trade_table.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
        //         cell.innerHTML = i+1;
        //     } );
        // } ).draw();
    }

    function ListItemTable() {
        var date	= new Date();
		var month 	= date.getMonth() + 1;
			month 	= (month < 10) ? '0'+month : month;
		var today	= date.getFullYear() + month + date.getDay();
        var tableName = "hq_material_settings";
        var row = '';
		row += '<table id="'+tableName+'" class="table table-bordered mt-15 table_material_settings table-hover" data-category="0" style="width:100%;">';
		row += '<thead>';
		row += '<tr>';
		row += '<th style="width:5%">#</th>';
		row += '<th class="excelExport" style="width:30%">Item Description</th>';		
		row += '<th class="excelExport" style="width:6%">Status</th>';
		row += '<th style="width:6%">Action</th>';
		row += '</tr>';
		row += '</thead>';
		row += '<tbody>';
		row += '</tbody>';
		row += '</table>';
		$('#ListTable').html(row);

        var formData = {
			'action'	: "listing",
			// 'user_ID'	: user_ID
		};

        // $('#hq_material_settings').DataTable().destroy();
        var trade_table = $('#hq_material_settings').DataTable({
            processing  : true,
            serverSide  : true,
            dom		    : 'lBfrtip',
            ajax        : {
				headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: APP_URL + '/admin/material/item/list',
				type: "post",  		
				data: formData,
				error: function(){  
					console.log("error");
				}
			}, 
            columnDefs: [				
				{
					"targets"	: [0,2,3],
					"className"	: "text-center",
				}
			],
            buttons: [
				{
					text: "<i class='fa fa-download' style='vertical-align:middle;'></i> <label style='margin:5px;'>Export</label>",
					extend: 'excelHtml5',
                    exportOptions: {
						columns: '.excelExport'
					},
					filename: 'Item_List_'+today,
					title: '',
					className: 'btn-export',
					action: function (e, dt, button, config) {
						var that = this;
						if(confirm("Do you want to export item listing to Excel file?")) {
							console.log('COnfirm == OK');
							that.processing(true);
							that.disable();
							setTimeout(function () {
								console.log('[excelHtml5]button',button);
								$.fn.dataTable.ext.buttons.excelHtml5.action.call(that, e, dt, button, config);
								
							}, 500);
							that.enable();
						} else {
							console.log('Confirm == Cancel');
						}
					}
				},
			],			
            // ajax        : "{{route('admin.getTradeList')}}",
            columns: [
                // { data: 'id', name: 'id' },
                { "data": null,"sortable": false, 
                    render: function (data, type, row, meta) {
                                return meta.row + meta.settings._iDisplayStart + 1;
                    }  
                },
                { data: 'name', name: 'name' },                  
                { data: 'status', name: 'status' },                  
                { data: 'action', name: 'action'},
            ],
            order: [[1, 'asc']]
        }); 
        
        // trade_table.on( 'order.dt search.dt', function () {
        //     trade_table.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
        //         cell.innerHTML = i+1;
        //     } );
        // } ).draw();
    }

    function ListCategoryTable() {
        var date	= new Date();
		var month 	= date.getMonth() + 1;
			month 	= (month < 10) ? '0'+month : month;
		var today	= date.getFullYear() + month + date.getDay();
        var tableName = "hq_material_settings";
        var row = '';
		row += '<table id="'+tableName+'" class="table table-bordered mt-15 table_material_settings table-hover" data-category="0" style="width:100%;">';
		row += '<thead>';
		row += '<tr>';
		row += '<th style="width:5%">#</th>';
		row += '<th class="excelExport" style="width:30%">Category Name</th>';		
		row += '<th class="excelExport" style="width:6%">Status</th>';
		row += '<th style="width:6%">Action</th>';
		row += '</tr>';
		row += '</thead>';
		row += '<tbody>';
		row += '</tbody>';
		row += '</table>';
		$('#ListTable').html(row);

        var formData = {
			'action'	: "listing",
			// 'user_ID'	: user_ID
		};

        // $('#hq_material_settings').DataTable().destroy();
        var trade_table = $('#hq_material_settings').DataTable({
            processing  : true,
            serverSide  : true,
            dom		    : 'lBfrtip',
            ajax        : {
				headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: APP_URL + '/admin/material/category/list',
				type: "post",  		
				data: formData,
				error: function(){  
					console.log("error");
				}
			}, 
            columnDefs: [				
				{
					"targets"	: [0,2,3],
					"className"	: "text-center",
				}
			],
            buttons: [
				{
					text: "<i class='fa fa-download' style='vertical-align:middle;'></i> <label style='margin:5px;'>Export</label>",
					extend: 'excelHtml5',
                    exportOptions: {
						columns: '.excelExport'
					},
					filename: 'Category_List_'+today,
					title: '',
					className: 'btn-export',
					action: function (e, dt, button, config) {
						var that = this;
						if(confirm("Do you want to export category listing to Excel file?")) {
							console.log('COnfirm == OK');
							that.processing(true);
							that.disable();
							setTimeout(function () {
								console.log('[excelHtml5]button',button);
								$.fn.dataTable.ext.buttons.excelHtml5.action.call(that, e, dt, button, config);
								
							}, 500);
							that.enable();
						} else {
							console.log('Confirm == Cancel');
						}
					}
				},
			],			
            // ajax        : "{{route('admin.getTradeList')}}",
            columns: [
                // { data: 'id', name: 'id' },
                { "data": null,"sortable": false, 
                    render: function (data, type, row, meta) {
                                return meta.row + meta.settings._iDisplayStart + 1;
                    }  
                },
                { data: 'name', name: 'name' },                  
                { data: 'status', name: 'status' },                  
                { data: 'action', name: 'action'},
            ],
            order: [[1, 'asc']]
        }); 
        
        // trade_table.on( 'order.dt search.dt', function () {
        //     trade_table.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
        //         cell.innerHTML = i+1;
        //     } );
        // } ).draw();
    }


   
});