<div class="container-fluid">
	<div class="card card-body">
		<h4 class="card-title">Client Information</h4>
		<hr>
		<div class="row">
			<div class="col">
				<div class="form-check form-check-inline">
					<input class="form-check-input" type="radio" name="complaint_client_type" id="complaint_client_type_internal" value="0" onchange="changeClientList(this)">
					<label class="form-check-label" for="complaint_client_type">Internal Client</label>
				</div>
				<div class="form-check form-check-inline">
					<input class="form-check-input" type="radio" name="complaint_client_type" id="complaint_client_type_external" value="1" onchange="changeClientList(this)" checked>
					<label class="form-check-label" for="complaint_client_type">External Client</label>
				</div>
			</div>
			<div class="col-1">
				<label for="" class="col-form-label-sm">Reference No.</label>
			</div>
			<div class="col-2">
				<input type="text" name="complaint_ref_no" id="complaint_ref_no" class="form-control form-control-sm" disabled placeholder="Auto-generated" value="<?php if($data_ref_no){ echo str_pad($data_ref_no[0]['nextSerialNo'], 4,'0', STR_PAD_LEFT); }else{ echo "Auto-generated"; } ?>">
			</div>
			<div class="col-2">
				<label for="" class="col-form-label-sm">Register by / Receiver of Complaint</label>
			</div>
			<div class="col-4">
				<input type="text" name="complaint_recev" id="complaint_recev" class="form-control form-control-sm" disabled value="<?php echo $_SESSION['user']['name']; ?>">
			</div>
		</div>
		<div class="row">
			
			<div class="col-3">
				<label for="complaint_dept_id" class="col-form-label-sm">Department</label>
				<select id="complaint_dept_id" type="text" class="form-control form-control-sm">
					<option value="" selected="selected">Please Select</option>
					<?php if($department){ foreach($department as $key => $value) { ?>
						<option 
						<?php if($value['id']) { 
							//echo 'selected';
						}?>
						value="<?php echo $value['id']; ?>"><?php echo $value['name']; ?> | <?php echo $value['branch_name']; ?></option>
					<?php }} ?>
				</select>
			</div>
			<div class="col-3">
				<label for="" class="col-form-label-sm">Services</label>
				<select id="services" type="text" class="form-control form-control-sm" onchange="changeJobList(this)">
					<option value="" selected="selected">Please Select</option>
					<?php if($data_services){ foreach($data_services as $key => $value) { ?>
						<option 
						<?php if($value['id']) { 
							//echo 'selected';
						}?>
						value="<?php echo $value['id']; ?>"><?php echo $value['service']; ?></option>
					<?php }} ?>
				</select>
			</div>
			<div class="col-3">
				<label for="" class="col-form-label-sm">Type of Job</label>
				<select id="job" type="text" class="form-control form-control-sm">
					<option value="" selected="selected">Please Select</option>
					<?php if($data_job){ foreach($data_job as $key => $value) { ?>
						<option 
						<?php if($value['id']) { 
							//echo 'selected';
						}?>
						value="<?php echo $value['id']; ?>"><?php echo $value['job']; ?></option>
					<?php }} ?>
				</select>
			</div>
			<div class="col-3">
				<label for="complaint_client" class="col-form-label-sm">Client Name</label>
				<select id="complaint_client" type="text" class="form-control form-control-sm" onchange="changeClientDetails(this)">
					<option value="" selected="selected">Please Select</option>
					<?php if($data_client){ foreach($data_client as $key => $value) { ?>
						<option 
						<?php if($value['id']) { 
							//echo 'selected';
						}?>
						value="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></option>
					<?php }} ?>
				</select>
			</div>
		</div>
		<div class="row">
			<div class="col-3">
				<label for="complaint_client_address" class="col-form-label-sm">Client Address</label>
				<input type="text" name="complaint_client_address" id="complaint_client_address" class="form-control form-control-sm">
			</div>
			<div class="col-3">
				<label for="complaint_contact_name" class="col-form-label-sm">Contact Name</label>
				<select id="complaint_contact_name" type="text" class="form-control form-control-sm" onchange="changeContactNo(this)">
				</select>
				<input type="text" name="complaint_contact_name_oth" id="complaint_contact_name_oth" class="form-control form-control-sm" style="display: none;">
				<select name="complaint_contact_name_int" id="complaint_contact_name_int" class="form-control form-control-sm" style="display: none;" onchange="changeStaffContactNo(this)">
				</select>
			</div>
			<div class="col-3">
				<label for="complaint_contact_no" class="col-form-label-sm">Phone No.</label>
				<input type="text" name="complaint_contact_no" id="complaint_contact_no" class="form-control form-control-sm">
			</div>
			<div class="col-3">
				<label for="complaint_contact_email" class="col-form-label-sm">Email</label>
				<input type="text" name="complaint_contact_email" id="complaint_contact_email" class="form-control form-control-sm">
			</div>
		</div>
		<div class="row">
			<div class="col">
				<label for="" class="col-form-label-sm">Business Impact</label>
				<textarea class="form-control form-control-sm" rows="4" id="complaint_business_impact"></textarea>
			</div>
		</div>
		<br>
		<h4 class="card-title">Complaint Information</h4>
		<hr>
		<div class="row">
			<div class="col">
				<label for="complaint_addressee" class="col-form-label-sm"><b>Addressee of the Complaint</b></label>
				<br>
				<select id="complaint_addressee" type="text" class="form-control form-control-sm">
					<option value="0" selected="selected">Please Select</option>
					<option value="1">CRM</option>
					<option value="2">Person In Charge</option>
					<option value="3">Department</option>
					<option value="4">Management</option>
				</select>
			</div>
		</div>
		<div class="row">
			<div class="col">
				<label for="" class="col-form-label-sm"><b>Complaint Date / Date of Problem Occurrence</b></label>
				<input id="complaint_date" type="text" class="form-control form-control-sm" value="">
			</div>
			<div class="col">
				<label for="" class="col-form-label-sm"><b>Complaint Type</b></label>
				<br>
				<div class="form-check form-check-inline">
					<input class="form-check-input" type="radio" name="complaint_type" id="complaint_type_initial" value="0" checked>
					<label class="form-check-label" for="complaint_type" value="0">Initial Complaint</label>
				</div>
				<div class="form-check form-check-inline">
					<input class="form-check-input" type="radio" name="complaint_type" id="complaint_type_follow" value="1">
					<label class="form-check-label" for="complaint_type" value="1">Follow-up Complaint</label>
				</div>
			</div>
		</div>
		<div class="row">
			<div class="col">
				<label for="" class="col-form-label-sm"><b>Method of Complaint</b></label>
				<br>
				<?php if($data_method){ foreach($data_method as $key => $value) { ?>
					<div class="form-check form-check-inline">
						<input class="form-check-input" type="checkbox" name="complaint_method" id="complaint_method" value="<?php echo $value['id']; ?>" onchange="openOthers_method(this)">
						<label class="form-check-label" for="inlineCheckbox1"> <?php echo $value['method']; ?> </label>
					</div>
				<?php }}?>
				<div class="form-check form-check-inline">
					<input id="complaint_method_others" name="complaint_method_others" type="text" value="" placeholder="Others.." class="form-control form-control-sm" size="100%" style="display: none;">
				</div>
			</div>
			<div class="col">
				<label for="" class="col-form-label-sm"><b>Complaint About</b></label>
				<br>
				<?php if($data_about){ foreach($data_about as $key => $value) { ?>
					<div class="form-check form-check-inline" >
						<input class="form-check-input" type="checkbox" name="complaint_about" id="complaint_about" value="<?php echo $value['id']; ?>" onchange="openOthers_about(this)">
						<label class="form-check-label" for="inlineCheckbox1"> <?php echo $value['about']; ?> </label>
					</div>
				<?php }}?>
				<div class="form-check form-check-inline">
					<input id="complaint_about_others" name="complaint_about_others" type="text" value="" placeholder="Others.." class="form-control form-control-sm" size="50%" style="display: none;">
				</div>
			</div>
		</div>
		<div class="row">
			<div class="col">
				<label for="" class="col-form-label-sm"><b>Case / Complaint Details</b></label>
				<textarea class="form-control form-control-sm" rows="4" id="complaint_details"></textarea>
			</div>
		</div>
		<div class="row">
			<div class="col">
				<label for="" class="col-form-label-sm"><b>Case Resolution Desired by Client</b></label>
				<textarea class="form-control form-control-sm" rows="4" id="complaint_reso"></textarea>
			</div>
		</div>
		<div class="row">
			<div class="col">
				<label for="" class="col-form-label-sm"><b>Reaction Urgency</b></label>
				<br>
				<div class="form-check form-check-inline">
					<input class="form-check-input" type="radio" name="complaint_urgency" id="complaint_urgency_yes" value="1">
					<label class="form-check-label" for="complaint_urgency">
					Yes
					</label>
				</div>
				<div class="form-check form-check-inline">
					<input class="form-check-input" type="radio" name="complaint_urgency" id="complaint_urgency_no" value="0" checked>
					<label class="form-check-label" for="complaint_urgency">
					No
					</label>
				</div>
			</div>
		</div>
		<br>
		<div class="row">
			<div class="col">
				<div class="row">
					<div class="col">
						<label for="" class="col-form-label-sm"><b>Complaint Attachment</b></label>
					</div>
					<div class="col text-right">
	                    <button class="btn btn-info btn-sm" data-toggle="modal" data-target="#attachmentModal" type="button"> <i class="fas fa-plus"></i> Add Attachment</button>
	                </div>
				</div>
				<div class="table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th class="text-center">#</th>
                                <th class="text-center">Description</th>
                                <th class="text-center">File Name</th>
                                <th class="text-center">Action</th>
                            </tr>
                        </thead>
                    </table>
                </div>
			</div>
		</div>
		<br>
		<button onclick="saveComplaint();" class="btn btn-success">Save Complaint</button>
	</div>
</div>
<br>

<div class="modal fade" id="attachmentModal">
	<div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Add Attachment</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" id="attachment_form" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="row">
                        <div class="col">
                            <label for="item"><b>Description</b></label>
                        </div>
                    </div>

                    <div class="row form-group">
                        <div class="col">
                           <textarea class="form-control" rows="5" id="attachment_description" placeholder="Attachment's Descriptive Information "></textarea>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-8">
                            <input type="file" class="form-control form-control-sm" id="upload-attachment" placeholder="Uploads file">
                        </div>
                        <div class="col">
                            <button type="submit" class="btn btn-primary text-white btn-block"><i class="fas fa-save text-white" ></i> Save</button>
                        </div>
                    </div>  
                </div>
            </form>
        </div>
    </div>
</div>

<script>
	$(function(){
		$('#complaint_date').datepicker({
			uiLibrary: 'bootstrap4',
			format: 'dd-mm-yyyy'
		});

	});

	var attachments = [];

	$('#attachment_form').submit(function(event){
        event.preventDefault();

        var $form = $(this);
        url = $form.attr('action');

        formData = new FormData();
        formData.append('files',$('#upload-attachment').prop('files')[0]);
        formData.append('description',$('#attachment_description').val());

        $.ajax({
            url: '<?php echo base_url('hr/serviceform/addComplaintAttachment'); ?>',
            type: "POST",             
            data: formData, 
            contentType:false,       
            cache: false,             
            processData:false,
            dataType: 'JSON',
            success: function(data){
                $('#attachmentModal').modal('hide');

                if(data.status == true){
                    attachments.push(data);
                    populatetable();
                }else{
                    iziToast.error({
                        position: 'bottomRight',
                        title: 'Uploading failed',
                        message: data[0].error
                    });
                }
                
            }
        });

    });

    function populatetable() {
        // console.log(attachments);  
        var table   = $('.table').DataTable();
            table.clear().draw();

        $.each(attachments,function(index,value){
            console.log(value);
            
            var rowCount = table.data().count();
            table.row.add({
                0   : ++rowCount,
                1   : value.description,
                2   : '<a href="<?php echo base_url(); ?>assets/upload/hr/Form/complaintForm/'+value.file_name+'" target="_blank">'+value.orig_name+'<a>',
                3   : '<td class="text-center">\
                        <a href="javascript:removeAttachment('+rowCount+')" data-toggle="tooltip" data-placement="top" title="Delete" class="btn btn-danger btn-sm"><i class="fas fa-trash" ></i>\
                        </a>\
                    </td>',
            }).draw();
        });  
    }

    function removeAttachment(index){
        toastConfirm('Are you sure you want to remove this item from your attachments',function(){
            attachments.splice(index-1,1);
            populatetable();
        });
    }

	function changeClientList(obj)
	{
		var id = obj.value;

		$.ajax({
			type: "POST",
            url: "<?php echo base_url() ?>hr/ServiceForm/getClientList",
            data: "client_type=" + id,
            dataType: "json",
            success: function(content) {
            	if (content.status == "success") {
            		if(id == 1){

            			jQuery("#complaint_client").attr("onchange", "changeClientDetails(this)");
            			jQuery("#complaint_client").empty();
            			jQuery("#complaint_contact_name").show();
            			jQuery("#complaint_contact_name").empty();
            			jQuery("#complaint_contact_name_int").hide();
	                    jQuery("#complaint_client_address").val('');
	                    jQuery("#complaint_contact_no").val('');

            			var items = [];
	                    items.push('<option>Please Select</option>');
	                    for (var i = 0; i < content.message.length; i++) {
	                        items.push('<option value="' + content.message[i].id + '">'
	                                + content.message[i].name + '</option>');
	                    }
	                    
	                    jQuery("#complaint_client").append(items.join('</br>'));
	                    
            		}else{

            			jQuery("#complaint_client").empty();
            			jQuery("#complaint_contact_name").hide();
            			jQuery("#complaint_contact_name_int").show();
	                    jQuery("#complaint_client_address").val('');
	                    jQuery("#complaint_contact_no").val('');

            			var items = [];
	                    items.push('<option>Please Select</option>');
	                    for (var i = 0; i < content.message.length; i++) {
	                        items.push('<option value="' + content.message[i].id + '">'
	                                + content.message[i].name + ' | ' + content.message[i].branch_name + '</option>');
	                    }
	                    
	                    jQuery("#complaint_client").append(items.join('</br>'));
	                    // jQuery("#complaint_client").removeAttr('onchange');
	                    jQuery("#complaint_client").attr("onchange", "changeStaffDetails(this)");
	                    
            		}
            	}else{
            		$("#error").html('<p>' + content.message + '</p>');
            	}
            }
		});
		return false;
	}

	function changeClientDetails(obj) 
    {
        var id = obj.value;

        $.ajax({
            type: "POST",
            url: "<?php echo base_url() ?>hr/ServiceForm/getClientDetails",
            data: "client_id=" + id,
            dataType: "json",
            success: function(content) {
                if (content.status == "success") {

                	jQuery("#complaint_client_address").val('');
                	jQuery("#complaint_client_address").val(content.message.client_address[0].address1 + ', ' + content.message.client_address[0].address2 );

                	if(content.message.client_contact != null){

                		jQuery("#complaint_contact_name").empty();

		                var items = [];
		                items.push('<option>Please Select</option>');
		                for (var i = 0; i < content.message.client_contact.length; i++) {
		                    items.push('<option value="' + content.message.client_contact[i].id + '">'
		                            + content.message.client_contact[i].name + '</option>');
		                }
		                items.push('<option value="9999">Others</option>');
		                jQuery("#complaint_contact_name").append(items.join('</br>'));
		                jQuery("#complaint_contact_no").val('');

		            }else{

		            	jQuery("#complaint_contact_name").empty();

		            	var items2 = [];
		                items2.push('<option>Please Select</option>');
		                items2.push('<option value="9999">Others</option>');

		                jQuery("#complaint_contact_name").append(items2.join('</br>'));
		                jQuery("#complaint_contact_no").val('');
		               
		            }

                } else {
                    $("#error").html('<p>' + content.message + '</p>');
                }
            }
        });
        return false;
    }

    function changeStaffDetails(obj) 
    {
        var id = obj.value;

        $.ajax({
            type: "POST",
            url: "<?php echo base_url() ?>hr/ServiceForm/getStaffDetails",
            data: "dept_id=" + id,
            dataType: "json",
            success: function(content) {
                if (content.status == "success") {

                	jQuery("#complaint_client_address").val('');
                	jQuery("#complaint_client_address").val(content.message.dept_branch.branch_name);

                	if(content.message.staff_list != null){

                		jQuery("#complaint_contact_name").hide();
                		jQuery("#complaint_contact_name_int").empty();

		                var items = [];
		                items.push('<option>Please Select</option>');
		                for (var i = 0; i < content.message.staff_list.length; i++) {
		                    items.push('<option value="' + content.message.staff_list[i].id + '">'
		                            + content.message.staff_list[i].name + '</option>');
		                }
		                jQuery("#complaint_contact_name_int").append(items.join('</br>'));
		                jQuery("#complaint_contact_no").val('');

		            }else{

		            	jQuery("#complaint_contact_name_int").empty();

		            	var items2 = [];
		                items2.push('<option>Please Select</option>');

		                jQuery("#complaint_contact_name_int").append(items2.join('</br>'));
		                jQuery("#complaint_contact_no").val('');
		               
		            }

                } else {
                    $("#error").html('<p>' + content.message + '</p>');
                }
            }
        });
        return false;
    }

    function changeContactNo(obj)
    {
    	var id = obj.value;

    	if(id == 9999){
    		jQuery("#complaint_contact_name_oth").show();
    		jQuery("#complaint_contact_no").val('');
    		jQuery("#complaint_contact_email").val('');
    	}else{
    		jQuery("#complaint_contact_name_oth").hide();
    		$.ajax({
	            type: "POST",
	            url: "<?php echo base_url() ?>hr/ServiceForm/getContactNo",
	            data: "contact_id=" + id,
	            dataType: "json",
	            success: function(content) {
	                if (content.status == "success") {

	                	jQuery("#complaint_contact_no").empty();
	                	jQuery("#complaint_contact_no").val(content.message[0].phone_mobile + '/ ' + content.message[0].phone_home);

	                	jQuery("#complaint_contact_email").empty();
	                	jQuery("#complaint_contact_email").val(content.message[0].email);

	                } else {
	                    $("#error").html('<p>' + content.message + '</p>');
	                }
	            }
	        });
	        return false;
    	}	
    }

    function changeStaffContactNo(obj)
    {
    	var id = obj.value;

		$.ajax({
            type: "POST",
            url: "<?php echo base_url() ?>hr/ServiceForm/getStaffContactNo",
            data: "staff_id=" + id,
            dataType: "json",
            success: function(content) {
                if (content.status == "success") {

                	jQuery("#complaint_contact_no").empty();
                	jQuery("#complaint_contact_no").val(content.message.phone);

                } else {
                    $("#error").html('<p>' + content.message + '</p>');
                }
            }
        });
        return false;
    }

	function changeJobList(obj) 
    {
        var id = obj.value;

        $.ajax({
            type: "POST",
            url: "<?php echo base_url() ?>crm/customer/getJob",
            data: "service_id=" + id,
            dataType: "json",
            success: function(content) {

                if (content.status == "success") {

                    var items = [];
                    items.push('<option>Please Select</option>');
                    for (var i = 0; i < content.message.length; i++) {
                        items.push('<option value="' + content.message[i].id + '">'
                                + content.message[i].job + '</option>');
                    }
                    jQuery("#job").empty();
                    jQuery("#job").append(items.join('</br>'));
                } else {
                    $("#error").html('<p>' + content.message + '</p>');
                }
            }
        });
        return false;
    }

    function openOthers_method(obj)
    {
    	var id = obj.value;

		if(id == 7){ //others
    		jQuery("#complaint_method_others").show();
    	}else{
    		jQuery("#complaint_method_others").hide();
    	}
    }

    function openOthers_about(obj)
    {
    	var id = obj.value;

		if(id == 8){ //others
    		jQuery("#complaint_about_others").show();
    	}else{
    		jQuery("#complaint_about_others").hide();
    	}
    }

    function saveComplaint()
	{
		if($('#complaint_client_type_internal').is(':checked')) {
			var complaint_for 	= 0; 
			var contact_id 		= $('#complaint_contact_name_int').val();
		} else if($('#complaint_client_type_external').is(':checked')) {
			var complaint_for 	= 1; 
			var contact_id 		= $('#complaint_contact_name').val();
		} else{
			return;
		}

		if($('#complaint_type_initial').is(':checked')) {
			var complaint_type = 0; 
		} else if($('#complaint_type_follow').is(':checked')) {
			var complaint_type = 1; 
		} else{
			return;
		}

		if($('#complaint_urgency_yes').is(':checked')) {
			var urgency = 1; 
		} else if($('#complaint_urgency_no').is(':checked')) {
			var urgency = 0; 
		} else{
			return;
		}

		var complaint_method = []
		$("input:checkbox[name=complaint_method]:checked").each(function(){
		    complaint_method.push($(this).val());
		}); 

		var complaint_about = []
		$("input:checkbox[name=complaint_about]:checked").each(function(){
		    complaint_about.push($(this).val());
		}); 

		if($('#complaint_contact_name').val() == 9999){
			var contact_name = $('#complaint_contact_name_oth').val();
		}else{
			var contact_name = 0;
		}

		var postData = {
			'complaint_for' 	: complaint_for,
			'ref_no'			: $('#complaint_ref_no').val(),
			'dept_id'			: $('#complaint_dept_id').val(),
			'services_id'		: $('#services').val(),
			'job_id'			: $('#job').val(),
			'client_id'			: $('#complaint_client').val(),
			'client_address'	: $('#complaint_client_address').val(),
			'contact_id'		: contact_id,
			'contact_name'		: contact_name,
			'phone_no' 			: $('#complaint_contact_no').val(),
			'email' 			: $('#complaint_contact_email').val(),
			'business_impact'	: $('#complaint_business_impact').val(),
			'addressee_id'		: $('#complaint_addressee').val(),
			'date'				: $('#complaint_date').val(),
			'complaint_type'	: complaint_type,
			'complaint_details'	: $('#complaint_details').val(),
			'reso_desired'		: $('#complaint_reso').val(),
			'urgency'			: urgency,
			'complaint_method'	: complaint_method,
			'complaint_about'	: complaint_about,
			'complaint_method_others'	: $('#complaint_method_others').val(),
			'complaint_about_others'	: $('#complaint_about_others').val(),
			'attachments'		: attachments

		};

		$.ajax({
			type: 'POST',
			dataType: 'json',
			url: '<?php echo base_url(); ?>hr/ServiceForm/saveComplaint',
			data: postData,
			success: function(data) {
				window.location.href = "<?php echo base_url().'hr/serviceform/complaint_list'?>";
			}
		});
	}

</script>