<section class="container" style="padding-bottom: 2rem;">
	<div class="row">
		<div class="col-sm-12">
			<div class="card bg-light-transparent">
				<div class="card-header bg-light">
					<h4 class="card-title float-left">Approval</h4>
				</div>
				<div class="card-body">
					<div class="card no-shadow">
						<div class="card-header-action d-print-none d-none d-sm-block">
							<div class="form-row float-right" style="padding-top: 1rem; padding-right: 1rem;">
								<a href="" data-toggle="modal" class="btn btn-primary" data-target="#approval_modal" data-tblname="<?php echo $tblname; ?>" data-tblid="<?php echo $ID; ?>" data-link="<?php echo $link; ?>" data-frmname="<?php echo $form_name; ?>" onclick="open_approval_modal(this)">Add New</a>
							</div>
						</div>
						<div class="card-body">
							<div class="row">
						        <table id="table_approval" class="table table-bordered table-hover mx-1">
						            <thead class="text-center">
						                <th width="5%">#</th>
						                <th width="40%">Status</th>
						                <th width="30%">By</th>
						                <th width="20%">Date</th>
						                <th width="5%">Action</th>
						            </thead>
						            <tbody class="text-center">
						                <?php foreach($rsApproval as $key => $row): ?>
						                    <tr <?php echo ($row['is_delete'] == 1)?'style="background-color: rgba(0,0,0,0.05);"':''; ?>>
						                        <td><?php echo $key+1; ?></td>
						                        <td>
						                        	<?php 
						                        		if($row['status'] == 'Pending')
						                        		{
						                        			$icon = '<i class="fa fa-exclamation-circle" style="color: #FFC107;"></i>';
						                        		}
						                        		if($row['status'] == 'In_progress')
						                        		{
						                        			$row['status'] = str_replace('_', ' ', $row['status']);
						                        			$icon = '<i class="fa fa-hourglass-start" style="color: grey;"></i>';
						                        		}
						                        		if($row['status'] == 'Verified')
						                        		{
						                        			$icon = '<i class="fa fa-check-circle" style="color: green;"></i><p style="font-style: italic; font-size: 13px;">'.$row['reason'].'</p>';
						                        		}
						                        		if($row['status'] == 'Approved' || $row['status'] == 'Completed')
						                        		{
						                        			$icon = '<i class="fa fa-check-circle" style="color: green;"></i>';
						                        		}
						                        		if($row['status'] == 'Rejected')
						                        		{
						                        			$icon = '<i class="fa fa-times-circle" style="color: red;"></i>';
						                        		}
						                        		if($row['status'] == 'Cancel')
						                        		{
						                        			$icon = '<i class="fa fa-times-circle" style="color: red;"></i>';
						                        		}
						                        		echo $row['status'].' '.$icon; 
						                        	?>	
						                        </td>
						                        <td><?php echo ($key == 0)?'<i>New Request</i>':$row['approvedByName']; ?></td>
						                        <td><?php echo date('d M Y',strtotime($row['approvedTS'])); ?></td>
						                        <td><?php 
						                        		$approvedDate 	= date('d-m-Y',strtotime($row['approvedTS'])); 
						                        		$currentDate 	= date('d-m-Y');

						                        		if($approvedDate == $currentDate)
						                        		{			
						                        			if($_SESSION['user']['id'] == $row['approved_by'])
						                        			{
						                        				$btn_color = ($row['is_delete'] == 0)?'btn-warning':'btn-secondary';
						                        				$disabled = ($row['is_delete'] == 0)?'':'disabled style="cursor: not-allowed;"';
						                        			}
						                        			else
						                        			{
						                        				$btn_color = 'btn-secondary';
						                        				$disabled = 'disabled style="cursor: not-allowed;"';
						                        			}
						                        		} else
						                        		{
						                        			$btn_color = 'btn-secondary';
						                        			$disabled = 'disabled style="cursor: not-allowed;"';
						                        		}
						                        	?>
						                        	<button class="btn <?php echo $btn_color; ?> btn-sm" data-toggle="modal" data-target="#editStatus" data-trigger="hover" data-tooltip="tooltip" title="Edit Status" data-status="<?php echo $row['status']; ?>" data-statusid="<?php echo $row['ID']; ?>" data-username="<?php echo $row['approvedByName']; ?>" data-date="<?php echo date('d M Y',strtotime($row['approvedTS'])); ?>" data-tblname="<?php echo $tblname; ?>" data-tblid="<?php echo $ID; ?>" data-reason="<?php echo $row['reason'] ?>" data-link="<?php echo $link; ?>" data-frmname="<?php echo $form_name; ?>" <?php echo ($row['is_delete'] == 0)?'onclick="edit_status(this)"':''; ?> <?php echo $disabled; ?>><i class="fa fa-edit"></i></button>
						                        </td>
						                    </tr>
						                <?php endforeach; ?>
						            </tbody>
						        </table>
						    </div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</section>

<!-- add status -->
<div class="modal fade" id="approval_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-md" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h4>Add New</h4>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>

			<div class="modal-body">
				<form class="form" id="approvalForm">
				<!-- <form action="<?php //echo base_url('hr/Serviceform/approval_save' ) ?>" method="post"> -->
					<input type="text" name="table_name" id="table_name" hidden>
					<input type="text" name="table_id" id="table_id" hidden>	
					<input type="text" name="link" id="link" hidden>
					<input type="text" name="form_name" id="form_name" hidden>

					<div class="row">
						<div class="col-12 mb-6">
							<label>By</label>
							<input type="text" class="form-control" name="approved_by" id="approved_by" value="<?php echo $_SESSION['user']['name']; ?>" disabled>
						</div>
					</div><br>

					<div class="row">
						<div class="col-12 mb-6">
							<label>Date</label>
							<input class="form-control" id="date_submission" name="date_submission" value="<?php echo date('d M Y'); ?>" disabled>
						</div>
					</div><br>

					<div class="row">
						<div class="col-12 mb-6">
							<label>Status</label>
							<select class="form-control" id="status" name="status" required onchange="display_reason_input(false)">
								<option value="Pending">Pending</option>
								<option value="In_progress">In Progress</option>
								<option value="Verified">Verified</option>
								<option value="Approved">Approved</option>
								<option value="Cancel">Cancel</option>
								<option value="Rejected">Rejected</option>
							</select>
						</div>
					</div><br>

					<div class="row d-none" id="verified_reason">
						<div class="col-12 mb-6">
							<label>Reason</label>
							<input type="text" class="form-control" name="reason" id="reason">
						</div><br>
					</div>

					<?php if(isset($form_detail)){ ?>
						<?php if($tblname == 'sv__job_request'){ ?>	
							<div class="row d-none" id="job_deadline">
								<div class="col-12 mb-6">
									<label>Deadline</label>
									<input type="text" class="form-control datepicker" name="deadlines" id="deadlines">
								</div>
							</div><br>
						<?php } ?>
					<?php } ?>

					<div class="float-right">
						<button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
						<button type="button" class="btn btn-primary" onclick="submitApproval()">Submit</button>
					</div> 
				</form>
			</div>
		</div>
	</div>
</div>
<!-- add status -->

<!-- edit status -->
<div class="modal fade" id="editStatus" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-md" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h4>Edit Status</h4>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>

			<div class="modal-body">
				<form class="form" id="editapprovalForm">
				<!-- <form action="<?php //echo base_url('hr/Serviceform/approval_save' ) ?>" method="post"> -->
					<input type="text" name="edit_table_name" id="edit_table_name" hidden>
					<input type="text" name="edit_table_id" id="edit_table_id" hidden>	
					<input type="text" name="edit_link" id="edit_link" hidden>
					<input type="text" name="edit_status_id" id="edit_status_id" hidden>
					<input type="text" name="edit_form_name" id="edit_form_name" hidden>

					<div class="row">
						<div class="col-12 mb-6">
							<label>By</label>
							<input type="text" class="form-control" name="edit_approved_by" id="edit_approved_by" disabled>
						</div>
					</div><br>

					<div class="row">
						<div class="col-12 mb-6">
							<label>Date</label>
							<input class="form-control" id="edit_date_submission" name="edit_date_submission" disabled>
						</div>
					</div><br>

					<div class="row">
						<div class="col-12 mb-6">
							<label>Status</label>
							<select class="form-control" id="edit_status" name="edit_status" required onchange="display_reason_input(true)">
								<option value="Pending">Pending</option>
								<option value="In_progress">In Progress</option>
								<option value="Verified">Verified</option>
								<option value="Approved">Approved</option>
								<option value="Cancel">Cancel</option>
								<option value="Rejected">Rejected</option>
							</select>
						</div>
					</div><br>

					<div class="row d-none" id="edit_verified_reason">
						<div class="col-12 mb-6">
							<label>Reason</label>
							<input type="text" class="form-control" name="edit_reason" id="edit_reason">
						</div>
					</div><br>

					<div class="float-right">
						<button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
						<button type="button" class="btn btn-primary" onclick="edit_submitApproval()">Submit</button>
					</div> 
				</form>
			</div>
		</div>
	</div>
</div>
<!-- edit status -->

<script type="text/javascript">
	function open_approval_modal(elem) 
    {
        let tblname   	= $(elem).data('tblname');
        let tblid     	= $(elem).data('tblid');
        let link     	= $(elem).data('link');
        let form_name	= $(elem).data('frmname');

        // if(tblname == 'sv__training_request')
        if(tblname == 'sv__training_request' || tblname == 'sv__delivery' || tblname == 'sv__car_booking' || tblname == 'sv__booking__room' || tblname == 'sv__stationery' || tblname == 'sv__maintenance' || tblname == 'sv__zoom_booking' || tblname == 'sv__capex')
        {
        	var select_option = `<option value="Pending">Pending</option>
			<option value="In_progress">In Progress</option>
			<option value="Verified">Verified</option>
			<option value="Completed">Completed</option>
			<option value="Cancel">Cancel</option>
			<option value="Rejected">Rejected</option>`;
        }else{
        	var select_option = `<option value="Pending">Pending</option>
			<option value="In_progress">In Progress</option>
			<option value="Verified">Verified</option>
			<option value="Approved">Approved</option>
			<option value="Cancel">Cancel</option>
			<option value="Rejected">Rejected</option>`;
        }
        $('#status').html('')
        $('#status').append(select_option)
        
        /* view modal */

        $('#table_name').val(tblname);
        $('#table_id').val(tblid);
        $('#link').val(link);
        $('#form_name').val(form_name);
    }

    function edit_status(elem) 
    {
    	let tblname   	= $(elem).data('tblname');
        let tblid     	= $(elem).data('tblid');
        let link     	= $(elem).data('link');
        let status     	= $(elem).data('status');
        let reason     	= $(elem).data('reason');
        let status_id  	= $(elem).data('statusid');
        let username    = $(elem).data('username');
        let date     	= $(elem).data('date');
        let form_name	= $(elem).data('frmname');

        // if(tblname == 'sv__training_request')
        if(tblname == 'sv__training_request' || tblname == 'sv__delivery' || tblname == 'sv__car_booking' || tblname == 'sv__booking__room' || tblname == 'sv__stationery' || tblname == 'sv__maintenance' || tblname == 'sv__zoom_booking' || tblname == 'sv__capex')
        {
        	var select_option = `<option value="Pending">Pending</option>
			<option value="In_progress">In Progress</option>
			<option value="Verified">Verified</option>
			<option value="Completed">Completed</option>
			<option value="Cancel">Cancel</option>
			<option value="Rejected">Rejected</option>`;
        }else{
        	var select_option = `<option value="Pending">Pending</option>
			<option value="In_progress">In Progress</option>
			<option value="Verified">Verified</option>
			<option value="Approved">Approved</option>
			<option value="Cancel">Cancel</option>
			<option value="Rejected">Rejected</option>`;
        }
        $('#edit_status').html('')
        $('#edit_status').append(select_option)

        /* view modal */
        $('#edit_table_name').val(tblname);
        $('#edit_table_id').val(tblid);
        $('#edit_link').val(link);
        $('#edit_status').val(status);
        $('#edit_reason').val(reason);
        $('#edit_status_id').val(status_id);
        $('#edit_approved_by').val(username);
        $('#form_name').val(form_name);
        $('#edit_form_name').val(form_name);
        $('#edit_date_submission').val(date);
    }

    function submitApproval() {
	    validateForm("#approvalForm", "Confirm to update status?", function() {
	    	var input_key 	= {};
	    	var input_value = [];

	    	if($('#deadlines').val() != null && $('#deadlines').val() != '' && $('#deadlines').val() != undefined){
	    		input_key["deadline"] = moment($('#deadlines').val(),'DD-MM-YYYY').format('YYYY-MM-DD');
	    	}

			input_value.push(input_key);
			console.log(input_value[0]);

	        $.ajax({
	            url:'<?php echo base_url('hr/serviceform/approval_save') ?>',
	            data: {
	                table_name 		: $('#table_name').val(),
	                table_id 		: $('#table_id').val(),
	                status 			: $('#status').val(),
	                reason 			: $('#reason').val(),
	                link 			: $('#link').val(),
	                form_name 		: $('#form_name').val(),
	                input_value 	: input_value[0],
	            },
	            type: 'post',
	            dataType: 'json',
	            success: (data) => {
	            	// console.log(data);
	            	if(data.status == "Success") {

	            		localStorage.setItem("status", data.status);
	            		localStorage.setItem("msg", data.msg);
	            		if(data.redirect == null || data.redirect == undefined || data.redirect == '')
	            		{
	            			window.location.reload();
	            		} else {
	            			window.location.href = data.redirect;
	            		}
	            	}

	            	if(data.status == "Error") {

	            		localStorage.setItem("status", data.status);
	            		localStorage.setItem("msg", data.msg);
	            		if(data.redirect == null || data.redirect == undefined || data.redirect == '')
	            		{
	            			window.location.reload();
	            		} else {
	            			window.location.href = data.redirect;
	            		}
	            	}
	            }
	        });
	    });
	}

	function edit_submitApproval() {
	    validateForm("#approvalForm", "Confirm to edit current status?", function() {
			var input_key 	= {};
	    	var input_value = [];

	    	if($('#deadlines').val() != null && $('#deadlines').val() != '' && $('#deadlines').val() != undefined){
	    		input_key["deadline"] = moment($('#deadlines').val(),'DD-MM-YYYY').format('YYYY-MM-DD');
	    	}

			input_value.push(input_key);

	        $.ajax({
	            url:'<?php echo base_url('hr/serviceform/approval_edit') ?>',
	            data: {
	                table_name 	: $('#edit_table_name').val(),
	                table_id 	: $('#edit_table_id').val(),
	                link 		: $('#edit_link').val(),
	                status 		: $('#edit_status').val(),
	                reason 		: $('#edit_reason').val(),
	                status_id	: $('#edit_status_id').val(),
	                form_name 	: $('#edit_form_name').val(),
	                input_value : input_value[0],
	            },
	            type: 'post',
	            dataType: 'json',
	            success: (data) => {
	            	// console.log(data);
	            	if(data.status == "Success") {

	            		localStorage.setItem("status", data.status);
	            		localStorage.setItem("msg", data.msg);
	            		if(data.redirect == null || data.redirect == undefined || data.redirect == '')
	            		{
	            			window.location.reload();
	            		} else {
	            			window.location.href = data.redirect;
	            		}
	            	}

	            	if(data.status == "Error") {

	            		localStorage.setItem("status", data.status);
	            		localStorage.setItem("msg", data.msg);
	            		if(data.redirect == null || data.redirect == undefined || data.redirect == '')
	            		{
	            			window.location.reload();
	            		} else {
	            			window.location.href = data.redirect;
	            		}
	            	}
	            }
	        });
	    });
	}

	function display_reason_input(edit_mode)
	{
		if(edit_mode == true) 
		{
			var status = $('#edit_status').val();
			if(status == 'Verified')
			{
				$('#edit_verified_reason').removeClass('d-none');
				$('#edit_reason').attr('required','required');
			}else{
				$('#edit_verified_reason').addClass('d-none','d-none');
				$('#edit_reason').removeAttr('required');
				$('#edit_reason').val('');
			}
		}else{
			var status = $('#status').val();
			if(status == 'Verified')
			{
				$('#job_deadline').addClass('d-none','d-none');
				$('#verified_reason').removeClass('d-none');
				$('#reason').attr('required','required');
			}else{
				$('#verified_reason').addClass('d-none','d-none');
				$('#reason').removeAttr('required');
				$('#reason').val('');

				if($('#table_name').val() == 'sv__job_request')
				{
					if(status != 'Approved') $('#job_deadline').addClass('d-none','d-none');
					else $('#job_deadline').removeClass('d-none');
				}
			}
		}
	}
</script>