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

$("#addForm").validate({

	rules:
	{
		brand_name:
		{
			required: true,
		},
		serial:
			{
				required: true,
				number: true,
			},
	},

	messages:
	{
		brand_name:
		{
			required: "Please type brand name",
		},
		serial:
			{
				required: "Type a serial number",
				number: "Write in number format",
			},
	},

	submitHandler: function (form) {

		$('.submit_button').css('cursor', 'wait');
		$('.submit_button').attr('disabled', true);

		$.ajax({
			url: baseURL + "newBrandEntryProcess",
			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");
					brandTable.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 brandTable = $('#brandTable').DataTable({
	"processing": true,
	"serverSide": true,
	"deferRender": true,
	"ajax": {
		"url": baseURL + "dataHandling/getBrandData",
		"type": "POST",
		data: function (d) {
			d.csrf_medisave_secured = token_key;
		}
	},

	"columns": [
		null,
		{ "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_logo' 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: 4,
		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"]],

});


$('#brandTable tbody').on('click', '#details_logo', function () {
	var data = brandTable.row($(this).parents('tr')).data();
	console.log(data);
	$('#modal_brand_id_logo').val(data[5]);
	$('#modal_brand_id').val(data[5]);
	$('#modal_brand').val(data[1]);
	$('#modal_serial').val(data[2]);
	$('#modal_status').val(data[3]);
	if (data[6] != null) {
		var imageData = data[6];
	}
	else {
		var imageData = 'image.png';
	}
	var image = "<img src='" + baseURL + "/assets/img/brand/" + imageData + "' width='120px'/>";
	$('#modal_image').html(image);
});



$('#brandTable tbody').on('click', '#delete', function () {
	var data = brandTable.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 + "deleteBrand",
				data: {
					brand_id: data[5],
					brand_picture: data[6],
					csrf_medisave_secured: token_key,
				},
				dataType: "json",
				success: function (res) {
					swal({
						title: res.response,
						type: res.type,
						timer: 1500,
						showConfirmButton: false,
						customClass: "swal-height",
					});
					brandTable.ajax.reload();
				},
			});
		}
	);
});

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

$('#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 brand_id = $('#modal_brand_id_logo').val();
		$.ajax({
			url: baseURL + "dataHandling/addBrandLogo",
			type: "POST",
			data: { "image": resp, "brand_id": brand_id, "csrf_medisave_secured": token_key },
			dataType: 'json',
			success: function (data) {
				var response_brought = data.response.indexOf('Logo Add successfully');
				if (response_brought != -1) {
					swal({
						title: "Logo Added Successfully",
						type: "success",
						timer: 1500,
						showConfirmButton: false,
						customClass: 'swal-height'
					});
					$("#updateLogo").trigger("reset");
					$('#full_width_modal_parent').modal('hide');
					brandTable.ajax.reload();
				}

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

$("#updateForm").validate({

	rules:
	{
		mbrand_name:
		{
			required: true,
		},
		serial:
			{
				required: true,
				number: true,
			},
		status: {
			required: true,
		}
	},

	messages:
	{
		manufacturer_name:
		{
			required: "Please type brand name",
		},
		serial:
			{
				required: "Type a serial number",
				number: "Write in number format",
			},
		status: {
			required: "Please select a status"
		}
	},

	submitHandler: function (form) {

		$('.update_button_2').css('cursor', 'wait');
		$('.update_button_2').attr('disabled', true);

		$.ajax({
			url: baseURL + "brandEditProcess",
			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')
				{
					$("#updateForm").trigger("reset");
					$('#full_width_modal_parent').modal('hide');
					brandTable.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());
	}

});
