var baseURL=$('meta[name="base_url"]').attr('content');
var token_key = $('#token_key').val();

$(function () {
	getCategory();
	getBrands();
});

function getCategory() {
	//var parameter = '&csrf_secure_name=' + token_key;
	$.ajax({
		url: baseURL + "dataHandling/getCategoryJsonData",
		type: 'GET',
		/* data: parameter,*/
		dataType: 'json',
		success: function (response) {
			items = "";
			items += "<option value=''>-select a category-</option>";
			$.each(response, function (index, item) {
				items += "<option value=" + item.category_id + ">" + item.category_name + "</option>";
			});
			$(".category").html(items);
			$(".modal_category").html(items);
		}
	})
}


$('.category').on('change', function () {
	var category_id = $('.category').val();
	getSubCategory(category_id);
});

$('.modal_category').on('change', function () {
	var category_id = $('.modal_category').val();
	getModalSubCategory(category_id);
});
function getModalSubCategory(category_id, sub_category_id) {
	$.ajax({
		url: baseURL + "dataHandling/getSubCategoryJsonData",
		type: 'POST',
		data: { "category_id": category_id, "csrf_medisave_secured": token_key },
		dataType: 'json',
		success: function (response) {
			items = "";
			if ($.isEmptyObject(response)) {
				items += "<option value=''>-select a sub-category-</option>";
			}
			$.each(response, function (index, item) {
				items += "<option value=" + item.sub_category_id + ">" + item.sub_category_name + "</option>";
			});
			$(".modal_sub_category").html(items);
			$(".modal_sub_category").val(sub_category_id);
		}
	})
}
function getSubCategory(category_id) {
	$.ajax({
		url: baseURL + "dataHandling/getSubCategoryJsonData",
		type: 'POST',
		data: { "category_id": category_id, "csrf_medisave_secured": token_key },
		dataType: 'json',
		success: function (response) {
			items = "";
			if ($.isEmptyObject(response)) {
				items += "<option value=''>-select a sub-category-</option>";
			}
			$.each(response, function (index, item) {
				items += "<option value=" + item.sub_category_id + ">" + item.sub_category_name + "</option>";
			});
			$(".sub_category").html(items);
		}
	})
}

function getBrands() {
	//var parameter = '&csrf_secure_name=' + token_key;
	$.ajax({
		url: baseURL + "dataHandling/getBrandJsonData",
		type: 'GET',
		/* data: parameter,*/
		dataType: 'json',
		success: function (response) {
			items = "";
			items += "<option value=''>-select a brand-</option>";
			$.each(response, function (index, item) {
				items += "<option value=" + item.brand_id + ">" + item.brand_name + "</option>";
			});
			$("#brand").html(items);
			$("#modal_brand").html(items);
		}
	})
}

var $ckfield = CKEDITOR.replace( 'ckfield' );
var $modal_ckfield = CKEDITOR.replace( 'modal-ckfield' );

$ckfield.on('change', function() {
	$ckfield.updateElement();
});

$modal_ckfield.on('change', function() {
	$modal_ckfield.updateElement();
});

$("#addForm").validate({
	rules:
	{
		product_name:
		{
			required: true,
		},
		product_size:
		{
			required: true,
		},
		product_model:
		{
			required: true,
		},
		brand_id:
		{
			required: true,
		},
		category_id:
		{
			required: true,
		},
		sub_category_id:
		{
			required: true,
		},
		description:{
			required: true,
		}
	},

	messages:
	{
		product_name:
		{
			required: "Please type product name",
		},
		product_size:
		{
			required: "Please type product size",
		},
		product_model:
		{
			required: "Please type product model",
		},
		brand_id:
		{
			required: "Please select a brand",
		},
		category_id:
		{
			required: "Please select a category",
		},
		sub_category_id:
		{
			required: "Please select a sub-category",
		},
		description:{
			required:"Please type product description",
		}
	},

	submitHandler: function (form) {
		console.log($('#addForm').serialize())
		$('.submit_button').css('cursor', 'wait');
		$('.submit_button').attr('disabled', true);

		$.ajax({
			url: baseURL + "newProductEntryProcess",
			type: 'POST',
			data: $('#addForm').serialize(),
			dataType: 'json',
			success: function (res) {
				swal({
					title: res.response,
					type: res.type,
					timer: 1500,
					showConfirmButton: false,
					customClass: 'swal-height'
				});

				if (res.type=='success')
				{
					$('.open').trigger('click');
					$("#addForm").trigger("reset");
					CKEDITOR.instances['ckfield'].setData("");
					$(".tag").tagsinput("removeAll");
					getCategory();
					getBrands();
					$('.sub_category').html("<option value=''>-select a sub-category-</option>");
					productTable.ajax.reload();
				}


				$('.submit_button').css('cursor', 'pointer');
				$('.submit_button').removeAttr('disabled');

			}
		});
	},                                                // Do not change code below
	errorPlacement: function (error, element) {
		error.insertAfter(element.parent());
	}

});

var productTable = $('#productTable').DataTable({
	"processing": true,
	"serverSide": true,
	"deferRender": true,
	"ajax": {
		"url": baseURL + "dataHandling/getProductData",
		"type": "POST",
		data: function (d) {
			d.csrf_medisave_secured = token_key;
		}
	},

	"columns": [
		null,
		{ "className": "" },
		{ "className": "" },
		{ "className": "" },
		{ "className": "" },
		{ "className": "" },
		{ "className": "" },
		{ "className": "" },
		{ "className": "" },
		{ "className": "center", searchable: false, orderable: false },
	],
	"autoWidth": false,


	"columnDefs": [{
		"targets": -1,
		"data": null,
		"defaultContent": "<td align='center'><a href='#full_width_modal_parent' role='button' id='details' class='btn btn-primary btn-xs small_btn' title='Details' data-toggle='modal'><i class='fa fa-bars'></i> View</a>   <a href='javascript:void(0)' role='button' id='delete' class='btn btn-danger btn-xs small_btn' title='Delete'><i class='fa fa-times'></i> Delete</a> </td></td> "
	},
	{
		targets: 8,
		render: function (data, type, row) {
			var color = 'black';
			if (data == 'Not Publish') {
				color = 'red';
			}
			if (data == 'Published') {
				color = 'green';
			}
			return '<span style="color:' + color + '">' + data + '</span>';
		}
	}
	],

	"aLengthMenu": [
		[10, 25, 50, -1],
		[10, 25, 50, "All"]
	],
	// set the initial value
	"iDisplayLength": 10,
	"bFilter": true,
	"bLengthChange": true,
	"bInfo": true,
	"bPaginate": true,
	"aaSorting": [[0, "asc"]],

});

$uploadCrop = $('#upload-demo').croppie({
	enableExif: true,
	viewport: {
		width: 550,
		height: 360,
		type: 'rectangle'
	},
	boundary: {
		width: 560,
		height: 370,
	}
});

$('#upload').on('change', function () {
	var reader = new FileReader();
	reader.onload = function (e) {
		$uploadCrop.croppie('bind', {
			url: e.target.result
		}).then(function () {
			console.log('jQuery bind complete');
		});
	}
	reader.readAsDataURL(this.files[0]);
});

$('.upload-result').on('click', function (ev) {

	$('.upload-result').css('cursor', 'wait');
	$('.upload-result').attr('disabled');

	$uploadCrop.croppie('result', {
		type: 'canvas',
		size: 'viewport'
	}).then(function (resp) {
		var product_id = $('#modal_product_id_picture').val();
		$.ajax({
			url: baseURL + "dataHandling/addProductPicture",
			type: "POST",
			data: { "image": resp, "product_id": product_id, "csrf_medisave_secured": token_key },
			dataType: 'json',
			success: function (data) {
				var response_brought = data.response.indexOf('Picture Added successfully');
				if (response_brought != -1) {
					swal({
						title: "Picture Added Successfully",
						type: "success",
						timer: 1500,
						showConfirmButton: false,
						customClass: 'swal-height'
					});
					$("#updateLogo").trigger("reset");
					$('#full_width_modal_parent').modal('hide');
					productTable.ajax.reload();
				}

				$('.upload-result').css('cursor', 'pointer');
				$('.upload-result').removeAttr('disabled');
			}
		});
	});
});

$('#productTable tbody').on('click', '#details', function () {
	var data = productTable.row($(this).parents('tr')).data();
	// console.log(data);
	$('#modal_product_id_picture').val(data[9]);
	$('#modal_product_id').val(data[9]);
	getModalSubCategory(data[11], data[12]);
	$('.modal_category').val(data[11]);
	$('#product_name').val(data[1]);
	$('#product_size').val(data[5]);
	$('#product_model').val(data[2]);
	$('#modal_brand').val(data[14]);
	CKEDITOR.instances['modal-ckfield'].setData(htmlspecialchars(data[13]));
	$('#modal_status').val(data[7]);
	if (data[10] != null) {
		var imageData = data[10];
	}
	else {
		var imageData = 'image.png';
	}
	var image = "<img src='" + baseURL + "/assets/img/products/" + imageData + "' width='120px'/>";
	$('#modal_image').html(image);
	$('#n_tag').tagsinput('refresh');
	$("#n_tag").tagsinput("add",htmlspecialchars(data[16]));
	$("#modal_meta_desc").val(data[17]);
});

function htmlspecialchars(str) {
	return str.replace('&amp;', '&').replace('&quot;', '"').replace("&#039;", "'").replace('&lt;', '<').replace('&gt;', '>');
}

$("#updateForm").validate({

	rules:
	{
		product_name:
		{
			required: true,
		},
		product_size:
		{
			required: true,
		},
		product_model:
		{
			required: true,
		},
		brand_id:
		{
			required: true,
		},
		category_id:
		{
			required: true,
		},
		sub_category_id:
		{
			required: true,
		},
		description:
		{
			required: true,
		},
	},

	messages:
	{
		product_name:
		{
			required: "Please type product name",
		},
		product_size:
		{
			required: "Please type product size",
		},
		product_model:
		{
			required: "Please type product model",
		},
		brand_id:
		{
			required: "Please select a brand",
		},
		category_id:
		{
			required: "Please select a category",
		},
		sub_category_id:
		{
			required: "Please select a sub-category",
		},
		description:
		{
			required: "Please type product description",
		},
	},

	submitHandler: function (form,event) {

		$('.update_button_2').css('cursor', 'wait');
		$('.update_button_2').attr('disabled', true);
		$.ajax({
			url: baseURL + "productEditProcess",
			type: 'POST',
			data: $('#updateForm').serialize(),
			dataType: 'json',
			success: function (res) {
				swal({
					title: res.response,
					type: res.type,
					timer: 1500,
					showConfirmButton: false,
					customClass: 'swal-height'
				});

				if (res.type=='success')
				{
					CKEDITOR.instances['modal-ckfield'].setData("");
					$("#updateForm").trigger("reset");
					$('#full_width_modal_parent').modal('hide');
					productTable.ajax.reload();
				}


				$('.update_button_2').css('cursor', 'pointer');
				$('.update_button_2').removeAttr('disabled');

			}
		});
	},                                                // Do not change code below
	errorPlacement: function (error, element) {
		error.insertAfter(element.parent());
	}

});

$('#productTable tbody').on('click', '#delete', function () {
	var data = productTable.row($(this).parents('tr')).data();
	swal(
		{
			title: "Are you sure?",
			type: "warning",
			showCancelButton: true,
			confirmButtonColor: "#DD6B55",
			confirmButtonText: "Yes, delete it!",
			closeOnConfirm: false,
		},
		function () {
			$.ajax({
				type: "POST",
				url: baseURL + "deleteProduct",
				data: {
					product_id: data[9],
					product_picture: data[10],
					csrf_medisave_secured: token_key,
				},
				dataType: "json",
				success: function (res) {
					swal({
						title: res.response,
						type: res.type,
						timer: 1500,
						showConfirmButton: false,
						customClass: "swal-height",
					});
					productTable.ajax.reload();
				},
			});
		}
	);
});

