<div class="container-fluid" style="padding-bottom: 2rem;">
    <div class="row">
        <div class="col-md-6">
            <div class="card bg-light-transparent" style="margin-bottom: 2rem;">
                <div class="card-header bg-white">
                    <div class="float-left">
                        <h5 class="card-title">Calendar</h5>
                    </div>
                </div>
                <div class="card-body">
                    <div class="card bg-white no-shadow" style="height: 58rem;">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-12">
                                    <div id="calendar"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card bg-light-transparent" style="margin-bottom: 2rem;">
                <div class="card-header bg-white">
                    <h5 class="card-title">Flight Request Summary</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-12">
                            <a class="btn btn-block btn-dark add-shadow" href="<?php echo base_url('hr/serviceform/flight_form'); ?>" style="padding-top: 1rem; padding-bottom: 1rem;">New Request</a>
                        </div>
                    </div>
                    <br>
                    <div class="card bg-white no-shadow">
                        <div class="card-body">
                            <h6>Total Flight Request (<?php echo date('Y') ?>)</h6>
                            <br>
                            <div class="row">
                                <table id="table_flight" class="table table-bordered table-striped table-hover mx-1">
                                    <thead>
                                        <th class="text-center">Department</th>
                                        <th class="text-center">Total Request</th>
                                    </thead>
                                    <tbody>
                                        <?php if($total_request) foreach($total_request as $total){ ?>
                                            <tr>
                                                <td><?php echo $total['dept_name'].'/'.$total['branchName']; ?></td>
                                                <td class="text-center"><?php echo $total['total_request']; ?></td>
                                            </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container-fluid">
        <div class="card bg-light-transparent">
            <div class="card-header bg-white">
                <div class="float-left">
                    <h4>Flight Booking List</h4>

                    <a href="<?php echo base_url('hr/serviceform/flight_form'); ?>" target="_blank" class="btn btn-outline-dark btn-sm" title="Add New Flight"><i class="fa fa-plus"></i> Add New Flight Booking</a>

                    <a href="<?php echo base_url('hr/Serviceform_report/flight_print')?>" target="_blank" class="btn btn-outline-dark btn-sm" title="Print"><i class="fa fa-print"></i>Print</a>

                    <a id="btnShowFilters" type="button" class="btn btn-outline-dark btn-sm collapsed" data-trigger="hover" title="Show Filters Box" data-toggle="collapse" data-target="#collapseFilter" aria-expanded="false"><i class="fas fa-filter"></i>Show Filters</a>
                </div>
            </div>
            <div class="collapse" id="collapseFilter">
                <div class="card-header">
                    <div class="row">
                        <div class="col">
                            <div class="card no-shadow">
                                <div class="card-body">
                                    <input type="hidden" name="user_id" id="user_id" value="<?php echo $_SESSION['user']['id']; ?>">
                                    <?php if($_SESSION['module_data']['role'] == 'admin'){ ?>  
                                        <div class="form-group row">
                                            <label for="sv_flight_filter_dept" class="col-lg-3">
                                                Department
                                            </label>                           
                                            <div class="col-lg-4" >
                                                <select class="custom-select" name="sv_flight_filter_dept" id="sv_flight_filter_dept">
                                                    <option value="-1">[All]</option>
                                                    <?php if($department) foreach($department as $row){ //debug($row);?>
                                                        <option value="<?php echo $row['id']; ?>"><?php echo $row['name'].' ['.$row['branch_name'].']'; ?></option> 
                                                    <?php } ?>
                                                </select>
                                            </div>
                                        </div>
                                    <?php }?>

                                    <div class="form-group row">
                                        <label for="sv_flight_filter_status" class="col-lg-3">
                                            Status
                                        </label>                           
                                        <div class="col-lg-4" >
                                            <select class="custom-select" id="sv_flight_filter_status" name="sv_flight_filter_status">
                                                <option value="-1">[All]</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="Rejected">Rejected</option>
                                                <option value="Cancel">Cancel</option>
                                            </select>
                                        </div>
                                    </div>
                                    <!-- <div class="form-group row">
                                        <label for="filterName" class="col-lg-3">
                                            Guest Name
                                        </label>
                                        <div class="col-lg-4">    
                                            <select class='custom-select' id="sv_flight_filter_gname" name="sv_flight_filter_gname">
                                                <option value="-1">[All]</option>
                                                <?php if($listName) foreach($listName as $type){ ?>
                                                    <option value="<?php echo $type['id'];?>"><?php echo $type['name'];?></option>
                                                <?php } ?>
                                            </select>
                                        </div>                                         
                                    </div> -->
                                    <div class="form-group row">
                                        <label for="sv_flight_filter_year" class="col-lg-3">
                                            Year
                                        </label>                           
                                        <div class="col-lg-4" >
                                            <input type="text" name="sv_flight_filter_year" id="sv_flight_filter_year" class="form-control datepicker-yyyy">
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <label for="sv_flight_filter_month" class="col-lg-3">
                                            Requested Month
                                        </label>                           
                                        <div class="col-lg-4" >
                                            <input type="text" name="sv_flight_filter_month" id="sv_flight_filter_month" class="form-control datepicker-mm">
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col d-print-none">
                                            <button class="btn btn-info" id="searchBtn">Search</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-content">
                <div class="tab-pane fade active show" id="tableView" role="tabpanel" aria-labelledby="nav-table-tab">
                    <div class="card-body">
                        <div class="card no-shadow">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table id="filter_table_flight" class="table table-bordered p-0 m-0" width="100%">
                                        <thead>
                                            <th class="text-center" width="5%">#</th>
                                            <th class="text-center" width="15%">Requestor</th>
                                            <th class="text-center" width="10%">Flight Name</th>
                                            <th class="text-center" width="5%">No. of Passengers</th>
                                            <th class="text-center" width="15%">Origin</th>
                                            <th class="text-center" width="15%">Destination</th>
                                            <th class="text-center" width="10%">Departure Date and Time</th>
                                            <th class="text-center" width="10%">Return Date and Time</th>
                                            <th class="text-center" width="10%">Status</th>
                                            <th class="text-center" width="5%">Action</th>
                                        </thead>

                                        <tbody>
                                            <?php if(!empty($listFlightBooking)) { ?>
                                                <?php foreach ($listFlightBooking as $key => $row) {  ?>
                                                    <tr>
                                                        <td class="text-center"><?php echo $key+1 ?></td>
                                                        <td>
                                                            <b>Requested By : </b><br><?php echo $row['requestor'].' ['.$row['requestor_email'].']'; ?>
                                                            <br><br>
                                                            <b>Created By : </b><br><?php echo $row['created_name'].' ['.$row['created_email'].']' ?>
                                                        </td>
                                                        <td><?php echo strtoupper($row['flight_name']); ?></td>
                                                        <td class="text-center"><?php echo $row['no_of_passengers'] ?></td>
                                                        <td><?php echo strtoupper($row['origin']); ?></td>
                                                        <td><?php echo strtoupper($row['destination']); ?></td>
                                                        <td class="text-center"><?php echo date('d-m-Y', strtotime($row['departure_date'])) . ' / ' . $row['departure_time']; ?></td>
                                                        <td class="text-center"><?php echo (strtotime($row['return_date']) > 0)?date('d-m-Y', strtotime($row['return_date'])) . ' / ' . $row['return_time']:'N/A'; ?></td>
                                                        <td class="text-center">
                                                            <?php 
                                                                if(($row['status_app']==null || $row['status_app']=='Pending'))
                                                                {
                                                                    $status = 'Pending <i class="fa fa-exclamation-circle" style="color: #FFC107;"></i>';
                                                                    $disabled = '';
                                                                }
                                                                if($row['status_app'] == 'In_progress')
                                                                {
                                                                    $status = str_replace('_', ' ', $row['status_app']).' <i class="fa fa-hourglass-start" style="color: grey;"></i>';
                                                                    $disabled = 'disabled style="cursor: not-allowed;"';
                                                                }
                                                                if($row['status_app'] == 'Verified')
                                                                {
                                                                    $status = $row['status_app'].' <i class="fa fa-check-circle" style="color: green;"></i><p style="font-style: italic; font-size: 13px;">'.$row['status_reason'].'</p>';
                                                                    $disabled = '';
                                                                }
                                                                if($row['status_app'] == 'Approved')
                                                                {
                                                                    $status = $row['status_app'].' <i class="fa fa-check-circle" style="color: green;"></i>';
                                                                    $disabled = 'disabled style="cursor: not-allowed;"';
                                                                }
                                                                if($row['status_app'] == 'Rejected')
                                                                {
                                                                    $status = $row['status_app'].' <i class="fa fa-times-circle" style="color: red;"></i>';
                                                                    $disabled = 'disabled style="cursor: not-allowed;"';
                                                                }
                                                                if($row['status_app'] == 'Cancel')
                                                                {
                                                                    $status = $row['status_app'].' <i class="fa fa-times-circle" style="color: red;"></i>';
                                                                    $disabled = 'disabled style="cursor: not-allowed;"';
                                                                }

                                                                echo $status;
                                                            ?> 
                                                        </td>
                                                        <td class="text-center">
                                                            <div class="btn-group btn-group-sm" role="group">
                                                                <a href="<?php echo base_url('hr/serviceform/flight_form/'.$row['ID'].'/view'); ?>" class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="View Detail" target="_blank"><i class="fas fa-eye"></i></a>

                                                                <?php if(($_SESSION['user']['id'] == $row['requester_id']) || ($_SESSION['user']['id'] == $row['createdBY'])){ ?>
                                                                    <?php if($disabled == ''){ ?>
                                                                        <a href="<?php echo base_url('hr/serviceform/flight_form/'.$row['ID']); ?>" target="_blank" class="btn btn-outline-dark" onclick="" data-trigger="hover" data-tooltip="tooltip" title="Edit"><i class="far fa-edit"></i></a>
                                                                    <?php }else{ ?>
                                                                        <button class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="Edit" disabled style="cursor: not-allowed;"><i class="far fa-edit"></i></button>
                                                                    <?php } ?>
                                                                <?php } ?>

                                                                <a type="button" class="btn btn-outline-dark" href="<?php echo base_url('hr/serviceform_report/flight_print/').$row['ID']; ?>" target="_blank" data-trigger="hover" data-tooltip="tooltip" title="Print Detail"><i class="fa fa-print"></i></a>
                                                                
                                                                <?php if(($_SESSION['user']['id'] == $row['requester_id']) || ($_SESSION['user']['id'] == $row['createdBY'])){ ?>
                                                                    <button id="deleteButton" type="button" class="btn btn-outline-dark" onclick="deleteData(<?php echo $row['ID']; ?>);" data-trigger="hover" data-tooltip="tooltip" title="Delete" <?php echo ($disabled == '')?'':'disabled style="cursor: not-allowed;"'; ?>><i class="far fa-trash-alt"></i></button>
                                                                <?php } ?>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php } ?>
                                            <?php } ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style type="text/css">
    .tooltipevent
    {
        width:auto;
        height:auto;
        background:rgba(0,0,0,0.75);
        position:absolute;
        color: #fff;
        z-index:10001;
        padding:10px 10px 10px 10px ;  
        line-height: 200%;
    }
</style>

<script>
    $(document).ready(function()
    {
        <?php $this->session->unset_userdata('sv_flight_filter_dept'); ?>
        <?php $this->session->unset_userdata('sv_flight_filter_status'); ?>
        <?php $this->session->unset_userdata('sv_flight_filter_year'); ?>
        <?php $this->session->unset_userdata('sv_flight_filter_month'); ?>
        <?php $this->session->unset_userdata('sv__flight__booking'); ?>

        $('#searchBtn').click(function(){
            getData();
        });
        
        $('#table_flight').DataTable().destroy();

        var fc_event= '';
        var resource = <?php echo $resource;?>;

        var fullcalendar = $('#calendar').fullCalendar({ 
            height: 860,
            themeSystem: 'bootstrap4',
            header: 
            {
                left: 'prev,next today',
                center: 'title',
                right: 'month,listMonth'
            },
            buttonText: {
                today: 'Today',
                month: 'Calendar',
                listMonth: 'List'
            },

            navLinks: true, // can click day/week names to navigate views
            editable: true,
            eventLimit: true, // allow "more" link when too many events
            events: <?php echo $fc_event; ?>,

            eventMouseover: function (data, event, param, resource = <?php echo $resource;?>) {
                var js_res = JSON.parse(JSON.stringify(resource));
                var hover_item = js_res[data.id];
                var title = JSON.stringify(data.title);
                var depart_date = moment(hover_item.departure_date).format('DD-MM-YYYY');
                var return_dates = moment(hover_item.return_date).format('DD-MM-YYYY');

                if(hover_item.departure_type == 1)
                {
                    var return_date = 'N/A';
                    var return_time = 'N/A';
                }else{
                    var return_date = return_dates;
                    var return_time = hover_item.return_time;
                }

                tooltip = '<div class="tooltipevent"> Staff name : '+hover_item.requestor+'<br>Flight name : '+hover_item.flight_name+' <br/> Origin : '+hover_item.origin+'<br/> Destination : '+hover_item.destination+'<br/> Departure Date : '+depart_date+'<br/> Return Date : '+return_date+'<br/>Departure Time : '+hover_item.departure_time+' <br/> Return Time : '+return_time+' </div>';

                $("body").append(tooltip);
                $(this).mouseover(function (e) {
                    $(this).css('z-index', 10000);
                    $('.tooltipevent').fadeIn('500');
                    $('.tooltipevent').fadeTo('10', 1.9);
                }).mousemove(function (e) {
                    $('.tooltipevent').css('top', e.pageY + 10);
                    $('.tooltipevent').css('left', e.pageX + 20);
                });
            },

            eventMouseout: function(data, event) {
                $(this).css('z-index', 8);
                $('.tooltipevent').remove();
            },
        });

        fullcalendar.fullCalendar();
    });

	function deleteData(ID)
	{
		validateForm("#deleteButton", "Delete this flight booking list?", function() {
			$.ajax({
				url:'<?php echo base_url('hr/serviceform/deleteFlightList') ?>',
				data: {
					flightID : ID,
				},
				type: 'post',
				dataType: 'json',
				success: (data) => {
					if(data.status == "Success") {

                       localStorage.setItem("status", data.status);
                       localStorage.setItem("msg", data.msg);

                       location.reload();

					// redirect(base_url('hr/serviceform/hotel_list'));
               }
           }
       });
		});
	}

    function open_view_modal(elem) 
    {
        let name            = $(elem).data('name');
        let dept            = $(elem).data('dept');
        let datereq         = $(elem).data('datereq');
        let guest_name      = $(elem).data('guest_name');
        let guest_ic        = $(elem).data('guest_ic');
        let guest_passport  = $(elem).data('guest_passport');
        let guest_phone     = $(elem).data('guest_phone');
        let origin          = $(elem).data('origin');
        let destination     = $(elem).data('destination');
        let depart_date     = $(elem).data('depart_date');
        let depart_time     = $(elem).data('depart_time');
        let return_date     = $(elem).data('return_date');
        let return_time     = $(elem).data('return_time');
        let passenger       = $(elem).data('passenger');
        let flight_class    = $(elem).data('flight_class');
        let meal            = $(elem).data('meal');
        let baggage         = $(elem).data('baggage');
        let flight          = $(elem).data('flight');
        // console.log(dept);
        
        /* view modal */
        $('#modal_view_name').val(name);
        $('#modal_view_dept').val(dept);
        $('#modal_view_date_req').val(datereq);
        $('#modal_view_guest_name').val(guest_name);
        $('#modal_view_guest_ic').val(guest_ic);
        $('#modal_view_passport').val(guest_passport);
        $('#modal_view_phone').val(guest_phone);
        $('#modal_view_origin').val(origin);
        $('#modal_view_destination').val(destination);
        $('#modal_view_depart_date').val(depart_date);
        $('#modal_view_depart_time').val(depart_time);
        $('#modal_view_return_date').val(return_date);
        $('#modal_view_return_time').val(return_time);
        $('#modal_view_passenger').val(passenger);
        $('#modal_view_flight_class').val(flight_class);

        if (meal == 1)
        {
            $('#modal_view_meal').val('Yes');
        } else
        {
            $('#modal_view_meal').val('No');
        }

        $('#modal_view_baggage').val(baggage);
        $('#modal_view_flight_name').val(flight);
        
    }

    function getData() 
    {
        var table = $('#filter_table_flight').DataTable();
        table.clear().draw();
        var frmData = new FormData();

        frmData.append('sv_flight_filter_dept',$('#sv_flight_filter_dept').val());
        // frmData.append('sv_flight_filter_gname',$('#sv_flight_filter_gname').val());
        frmData.append('sv_flight_filter_status', $('#sv_flight_filter_status').val());
        frmData.append('sv_flight_filter_year',$('#sv_flight_filter_year').val());
        frmData.append('sv_flight_filter_month',$('#sv_flight_filter_month').val());
        frmData.append('user_id',$('#user_id').val());

        $.ajax({
            url:"<?php echo base_url('/hr/api/serviceform/get_flight_filter'); ?>",
            type:'post',
            dataType:'json',
            data:frmData,
            processData: false,
            contentType: false,
            success:function(data)
            {

                iziToast.success({
                    position: 'bottomRight',
                    message: 'filtering data',
                });

                let flight = data.table;

                if(flight != null){
                    $.each(flight,function(key,content)
                    {
                        var i = key + 1;

                        var requestor_name = '<b>Requestor : </b><br>'+content.requestor+' ['+content.requestor_email+']';
                        var creator_name = '<b>Creator : </b><br>'+content.created_name+' ['+content.created_email+']';

                        if(content.departure_date != '0000-00-00')
                        {
                            var departure_date = moment(content.departure_date).format('DD-MM-YYYY');
                        } 

                        if(content.return_date != '0000-00-00'){
                            var return_date = moment(content.return_date).format('DD-MM-YYYY')+' / '+content.return_time;
                        }else{
                            var return_date = 'N/A';
                        }

                        if(content.status_app == null || content.status_app == 'Pending')
                        {
                            var status      = 'Pending <i class="fa fa-exclamation-circle" style="color: #FFC107;"></i>';
                            var disabled    = '';
                        }
                        if(content.status_app == 'In_progress')
                        {
                            var status      = ((content.status_app).replace('_',' '))+' <i class="fa fa-hourglass-start" style="color: grey;"></i>';
                            var disabled    = 'disabled style="cursor: not-allowed;"';
                        }
                        if(content.status_app == 'Verified')
                        {
                            var status      = content.status_app+' <i class="fa fa-check-circle" style="color: green;"></i><p style="font-style: italic; font-size: 13px;">'+content.status_reason+'</p>';
                            var disabled    = '';
                        }
                        if(content.status_app == 'Approved')
                        {
                            var status      = content.status_app+' <i class="fa fa-check-circle" style="color: green;"></i>';
                            var disabled    = 'disabled style="cursor: not-allowed;"';
                        }
                        if(content.status_app == 'Rejected')
                        {
                            var status      = content.status_app+' <i class="fa fa-times-circle" style="color: red;"></i>';
                            var disabled    = 'disabled style="cursor: not-allowed;"';
                        }
                        if(content.status_app == 'Cancel')
                        {
                            var status      = content.status_app+' <i class="fa fa-times-circle" style="color: red;"></i>';
                            var disabled    = 'disabled style="cursor: not-allowed;"';
                        }

                        var btn_view = '<a href="<?php echo base_url(); ?>hr/serviceform/flight_form/'+content.ID+'/view" class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="View Detail" target="_blank"><i class="fas fa-eye"></i></a>';
                        
                        var btn_print = '<a type="button" class="btn btn-outline-dark" href="<?php echo base_url();?>hr/serviceform_report/flight_print/'+content.ID+'" target="_blank" data-trigger="hover" data-tooltip="tooltip" title="Print Detail"><i class="fa fa-print"></i></a>';

                        if(disabled == '')
                        {
                            var btn_edit = '<a type="button" class="btn btn-outline-dark" href="<?php echo base_url();?>hr/serviceform/flight_form/'+content.ID+'" data-trigger="hover" data-tooltip="tooltip" title="Edit"><i class="far fa-edit"></i></a>';
                        }else{
                            var btn_edit = '<button class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="Edit" '+disabled+'><i class="far fa-edit"></i></button>';
                        }

                        var btn_delete = '<button type="button" class="btn btn-outline-dark" onclick="deleteData('+content.ID+')" data-trigger="hover" data-tooltip="tooltip" title="Delete"'+disabled+'><i class="far fa-trash-alt"></i></button>';

                        if(('<?php echo $_SESSION['user']['id']; ?>' == content.requester_id) || ('<?php echo $_SESSION['user']['id']; ?>' == content.createdBY))
                        {
                            var btn = btn_view+btn_edit+btn_print+btn_delete;
                        }else{
                            var btn = btn_view+btn_print;
                        }


                        table.row.add({
                            0   : '<div class="text-center">'+i+'</div>',
                            1   : requestor_name+'<br><br>'+creator_name,
                            2   : '<div class="text-center">'+content.no_of_passengers+'</div>',
                            3   : '<div class="text-center">'+(content.flight_name).toUpperCase()+'</div>',
                            4   : '<div class="text-center">'+(content.origin).toUpperCase()+'</div>',
                            5   : '<div class="text-center">'+(content.destination).toUpperCase()+'</div>',
                            6   : '<div class="text-center">'+departure_date+' / '+content.departure_time+'</div>',
                            7   : '<div class="text-center">'+return_date+'</div>',
                            8   : '<div class="text-center">'+status+'</div>',
                            9	: '<div class="text-center"><div class="btn-group btn-group-sm" role="group">'+btn+'</div></div>',
                        }).draw();
                        console.log(data);
                    });
                }
            },
            error:function(){
                iziToast.warning({
                    position: 'bottomRight',
                    message: '500 Internal Server Error.'
                });
            }
        });
    }
</script>