<style>
    .hl-row{
        /* background-color: grey;
        color: white; */
    }
    .chart-container {
        position: relative;
    }

    .chart-center {
        position:absolute;
        top: 55%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

    .text-center{
        text-align: center;
    }
</style>

<section class="container-fluid" style="padding-bottom: 2rem;">
    <div class="row">
        <div class="col-8" id="h-info">
            <div class="card bg-light-transparent">
                <div class="card-header bg-white">
                    <div class="float-left" style="margin-top: 4px;">
                        <h5>Holiday List</h5>
                    </div>
                    <div class="float-right" style="margin-top: 4px;">
                        <div class="btn-group btn-group-sm">
                            <a href="<?php echo base_url('hr/holiday/print')?>" target="_blank" class="btn btn-light btn-sm" title="Print holiday list">
                                <i class="fas fa-print"></i> 
                            </a>
                            <!-- <a href="<?php echo base_url('hr/holiday/print')?>" target="_blank" class="btn btn-light btn-sm" title="Show filter">
                                <i class="fas fa-filter"></i> 
                            </a> -->
                            <!-- <button class="btn btn-light" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-expanded="false">
                                <i class="fas fa-ellipsis-v"></i>
                            </button>
                            <div class="dropdown-menu" aria-labelledby="dropdownMenu2">
                                <button class="dropdown-item" type="button" id="clone-menui">Clone</button>
                                <button class="dropdown-item" type="button" id="activate-menui">Activate/Deactivate</button>
                            </div> -->
                        </div>
                    </div>
                    <div class="float-right" style="margin-right: 5px;">
                        <select class="form-control" id="year-select">
                            <?php
                                if($year_list){
                                    foreach($year_list as $yl){
                                        echo '<option value="' . $yl['year'] . '">' . $yl['year'] . '</option>';
                                    }
                                }else{
                                    echo '<option value="' . date('Y') . '">' . date('Y') . '</option>';
                                }
                            ?>
                        </select>
                    </div>
                </div>

                <div class="card-body">
                    <!-- selection bar -->
                    <div class="card no-shadow mb-2" id="select-bar" style="display: none;">
                        <div class="card-body">
                            <!-- <div class="form-check float-left" style="margin-top: 5px;">
                                <input class="form-check-input" type="checkbox" value="" id="selectall-cb">
                                <label class="form-check-label" for="selectall-cb">
                                    Select all
                                </label>
                                <span id="select-text"></span>
                            </div> -->
                            <div class="float-right">
                                <button type="button" class="btn btn-secondary" id="batch-cancel-btn">Cancel</button>
                                <button type="button" class="btn btn-primary" id="batch-btn"></button>
                            </div>
                        </div>
                    </div>
                    <!-- main -->
                    <div class="card no-shadow">
                        <div class="card-body">
                            <!-- table -->
                            <div class="table-responsive">
                            <table class="table display responsive table-striped" id="h-table">
                                <thead>
                                    <tr>
                                        <!-- <th style="width: 5%;">
                                            <input type="checkbox" id="selectall-cb">
                                        </th> -->
                                        <th style="width: 5%;">No.</th>
                                        <th style="width: 15%;">Date & Day</th>
                                        <th>Name</th>
                                        <th style="width: 10%;">Type</th>
                                        <th style="width: 10%;">Status</th>
                                        <th style="width: 10%;"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $i=1; if($holiday_list){ foreach ($holiday_list as $holiday) { ?>
                                        <tr class="table-row" id="tr-<?php echo $i; ?>" data-id="<?php echo $holiday['id']; ?>">
                                            <!-- <td><input type="checkbox"></td> -->
                                            <td><?php echo $i; ?></td>
                                            <!-- <td><?php echo date_format(date_create(($holiday['is_moved'] == 1 ? $holiday['moved_start_date'] : $holiday['original_start_date'])), 'd-m-Y'); ?></td>
                                            <td><?php echo date_format(date_create(($holiday['is_moved'] == 1 ? $holiday['moved_start_date'] : $holiday['original_start_date'])), 'D'); ?></td> -->
                                            <td>
                                                <?php if($holiday['is_moved'] == 1) echo '<s>'; ?>
                                                <p style="margin: 0; padding: 0;">
                                                    <?php echo date_format(date_create($holiday['original_start_date']), 'd-m-Y'); ?><span style="color: grey;"> <?php echo date_format(date_create(($holiday['original_start_date'])), 'D'); ?></span>
                                                </p>
                                                <?php echo '</s>'; ?>
                                                <?php if($holiday['is_moved'] == 1){ ?>
                                                <p style="margin: 0; padding: 0;">
                                                    <?php echo date_format(date_create($holiday['moved_start_date']), 'd-m-Y'); ?><span style="color: grey;"> <?php echo date_format(date_create(($holiday['moved_start_date'])), 'D'); ?></span>
                                                </p>
                                                <?php } ?>
                                            </td>
                                            <td><?php echo $holiday['name']; ?></td>
                                            <td><?php echo ucfirst($holiday['type']); ?></td>
                                            <td style="text-align: center;">
                                                <p style="margin: 0; padding: 0;">
                                                    <?php echo ($holiday['active'] == 1 ? '<span class="badge badge-pill badge-success">Active</span>' : '<span class="badge badge-pill badge-warning">Inactive</span>'); ?>
                                                </p>
                                                <?php
                                                    if($holiday['is_moved'] == 1) echo '<p style="color: grey; margin: 0; padding: 0;"><span class="badge badge-pill badge-info">Moved</span></p>';
                                                ?>
                                            </td>
                                            <td style="text-align: center;" class="h-action"></td>
                                        </tr>
                                    <?php $i++; } }else{ ?>
                                        <tr>
                                            <td colspan="6" style="text-align: center;">
                                                No holiday data found for this year. You can clone holidays from previous year of import from API
                                            </td>
                                        </tr>
                                        <tr>
                                            <td colspan="6" style="text-align: center;">
                                                <button class="btn btn-primary" type="button" id="import-btn">Import from API</button>
                                            </td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-4" id="h-details">
            <!-- summary. upcoming holiday, pie-chart national vs regional, upcoming count, past count -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-7">
                                    <h3>
                                        UPCOMING HOLIDAY
                                    </h3>
                                    <?php if($summary->next_name){ ?>
                                    <h5>
                                        <?php echo date_format(date_create($summary->next_date), 'j F') ?>
                                    </h5>
                                    <p style="padding: 0; margin: 0;">
                                        <a href="javascript:loadHoliday(<?php echo $summary->next_id; ?>)">
                                        <?php echo $summary->next_name ?>
                                        </a>
                                    </p>
                                    <?php }else{ ?>
                                    <h5>
                                    No holiday found
                                    </h5>
                                    <?php } ?>
                                </div>
                                <div class="col-5">
                                    <?php if($summary->count_national != 0 || $summary->count_regional != 0){ ?>
                                    <div class="chart-container">
                                        <canvas id="h-chart" width="400" height="400"></canvas>
                                        <div class="chart-center text-center">
                                            <p style="padding: 0; margin:0; font-size: larger;"><?php echo (intval($summary->count_national) + intval($summary->count_regional)) ?></p>
                                            <p style="padding: 0; margin:0;">Holidays</p>
                                        </div>
                                    </div>
                                    <?php } ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- hoilday details -->
            <div class="row mt-4" id="detail-container" style="display: none;">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header bg-white">
                            <div class="float-left" style="margin-top: 4px;">
                                <h5 id="h-name"></h5>
                                <p class="text-muted" style="padding: 0; margin: 0; font-style: italic; font-size: smaller;" id="h-updated"></p>
                            </div>
                            <!-- <div class="float-right">
                                <a href="#"><i class="fas fa-info-circle"></i></a>
                            </div> -->
                        </div>
                        <div class="card-body">
                            <!-- states -->
                            <div class="row mb-3">
                                <div class="col" id="h-states">
                                </div>
                            </div>
                            <!-- date -->
                            <div class="row mb-2">
                                <div class="col">
                                    <div class="float-left mr-2"><i class="far fa-calendar-alt"></i></div>
                                    <div class="float-left" id="h-date"></div>
                                </div>
                            </div>
                            <!-- active -->
                            <div class="row mv-2">
                                <div class="col">
                                    <input type="checkbox" id="h-active" aria-label="Active"> Active 
                                </div>
                            </div>
                            <!-- move -->
                            <div class="row mb-2">
                                <div class="col-3">
                                    <div class="form-group">
                                        <input type="checkbox" id="h-move" aria-label="Move"> Move holiday 
                                    </div>
                                </div>
                                <div id="h-move-container" style="display: none;" class="col-9">
                                    <div class="row">
                                        <div class="col">
                                            <div class="form-group">
                                                <input type="text" id="h-move-startdate" class="form-control datepicker" placeholder="Start date">
                                            </div>
                                        </div>
                                        <span> to </span>
                                        <div class="col">
                                            <div class="form-group">
                                                <input type="text" id="h-move-enddate" value="23-02-2022" class="form-control datepicker" placeholder="End date">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col">
                                            <div class="form-group">
                                                <textarea class="form-control" id="h-move-remarks" placeholder="Remarks"></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <hr>
                            <!-- broadcast option -->
                            <div class="row">
                                <div class="col">
                                    <div class="form-group">
                                        <label for="bc-select">How do you like any change to be broadcasted?</label>
                                        <select id="bc-select" class="form-control" name="bc-select">
                                            <option selected value="0">No broadcast</option>
                                            <!-- <option value="1">Via e-mail</option>
                                            <option value="2">Via e-mail and Salihin mobile app (push notification)</option> -->
                                            <option value="3">As announcement</option>
                                        </select>
                                        <p class="text-muted" style="padding: 0; margin: 0; font-style: italic; font-size: smaller;" id="bc-last"></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer bg-white">
                            <!-- <div class="float-left" style="margin-right: auto;">
                                <span class="text-danger" id="application-error"></span>
                            </div> -->
                            <div class="form-group float-left mb-0">
                                <button class="btn btn-danger" id="delete-btn" type="button">Delete</button>
                            </div>
                            <div class="form-group float-right mb-0">
                                <!-- <button class="btn btn-secondary" id="clone-btn" type="button">Clone</button> -->
                                <button class="btn btn-secondary" id="cancel-btn" type="button">Cancel</button>
                                <button class="btn btn-primary" id="update-btn" type="button">Update</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- MODALS -->
<div class="modal fade" id="loader-modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-body text-center">
                <div class="spinner-border" role="status" style="text-align: center;">
                </div>
                <div class="h5">
                    Processing...
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="clone-modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
        <div class="modal-header">
                <!-- <h5 class="modal-title">Clone a Holiday</h5> -->
                <div class="float-left">
                    <p style="padding: 0; margin:0; font-size: larger;">Clone a Holiday</p>
                    <p style="padding: 0; margin:0; color: grey;" id="clone-holiday-name"></p>
                </div>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="clone-form" class="form">
                <div class="modal-body">
                    <!-- year selection -->
                    <div class="row">
                        <div class="col">
                            <div class="form-group">
                                <label for="dateFrom">Select one or more year to clone to</label>
                                <input type="text" id="year-picker" class="form-control datepicker-yyyy">
                            </div>
                        </div>
                    </div>
                    <!-- year badge -->
                    <div class="row">
                        <div class="col">
                            <div class="form-group" id="year-badges">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <div class="form-group float-right">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" id="faqModalSubmitBtn"  class="btn btn-primary">Save</button>
                    </div>
            </div>
            </form>
        </div>
    </div>
</div>
<div class="modal fade" id="confirm-modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                    <!-- <h5 class="modal-title">Clone a Holiday</h5> -->
                    <div class="float-left">
                        <p style="padding: 0; margin:0; font-size: larger;">Commit action?</p>
                    </div>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="clone-form" class="form">
                    <div class="modal-body">
                        <!-- broadcast selection -->
                        <div class="row">
                            <div class="col">
                                <div class="form-group">
                                    <label for="bc-select">How do you like this changes to be broadcasted?</label>
                                    <select id="bc-select" class="form-control" name="bc-select">
                                        <option selected value="0">No broadcast</option>
                                        <option value="1">Via e-mail</option>
                                        <option value="2">Via e-mail and Salihin mobile app (push notification)</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <div class="form-group float-right">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary" id="confirm-btn">Confirm</button>
                        </div>
                </div>
                </form>
            </div>
    </div>
</div>

<script type="text/javascript">
    var holidayList = <?php echo json_encode($holiday_list) ?>;
    var stateList = <?php echo json_encode($state_list) ?>;
    var summary = <?php echo json_encode($summary) ?>;
    var currentRowSelected = 0;
    var loadedHoliday = null;
    var isSelecting = false;

    console.log('states: ' + JSON.stringify(stateList));

    data = {
        datasets: [{
            data: [summary.count_national, summary.count_regional],
            backgroundColor: [
                '#FF6384',
                '#36A2EB'
            ],
        }],
        labels: [
            'National',
            'Regional',
        ]
    };
    var myDoughnutChart = new Chart($('#h-chart'), {
        type: 'doughnut',
        data: data,
        // options: options 
    });

    $('.h-action').append(`<i class="fas fa-chevron-right"></i>`);
    $('#bc-select').val(0).trigger('change');

    $('.datepicker').datepicker({
        daysOfWeekDisabled: [0,6],
        format: 'dd-mm-yyyy'
    });

    $('#import-btn').on('click', function(){
        console.log('importing for ' + $('#year-select').val());
        $('#loader-modal').modal('show');
        var fd = new FormData();
        fd.append("year", $('#year-select').val());
        $.ajax({
            url: "<?php echo base_url('hr/holiday/import/'); ?>",
            type: "POST",
            data: fd,
            dataType: "JSON",
            processData: false,
            contentType: false,
            success: (data) => {
                localStorage.setItem("status", data.status);
                localStorage.setItem("msg", data.msg);
                $("#loader-modal").modal('hide');
                location.reload();
            },
            error: (jqXHR, textStatus, errorThrown) => {
                localStorage.setItem("status", 'Error');
                localStorage.setItem("msg", 'Failed to retrieve holiday data. Please contact support');
                console.log(textStatus);
                console.log(errorThrown);
            },
            complete: (xhr,status) => {
                $("#loader-modal").modal('hide');
            }
        });
    });

    $('.table-row').on('click', function(){
        console.log('clicked: ' + this.id + ' with value: ' + $(this).attr('data-id'));
        console.log('current row: ' + currentRowSelected);
        $('#h-move').prop('checked', false);
        $('#h-move-container input').val('');
        $('#h-move-container textarea').val('');
        loadedHoliday = null;
        $('#h-move-container').hide();
        if(!isSelecting){
            // single selection
            if(currentRowSelected == (this.id).replace('tr-', '')){
                // un-highlight old row
                $('#tr-' + currentRowSelected).removeClass('hl-row');
                currentRowSelected = 0;
                unloadHoliday();
            }else{
                // un-highlight old row
                $('#tr-' + currentRowSelected).removeClass('hl-row');

                // highlight new row
                $('#' + this.id).addClass('hl-row');
                currentRowSelected = (this.id).replace('tr-', '');

                // redraw table - pending. disabled row highliting for now

                // load details
                loadHoliday($(this).attr('data-id'))
            }
        }else{
            // mass selection

            // check the checkbox
        }
    });

    $('#update-btn').on('click', () => {
        updateHoliday();
    });

    $('#delete-btn').on('click', () => {
        deleteHoliday();
    });

    $('#cancel-btn').on('click', () => {
        currentRowSelected = 0;
        unloadHoliday();
    });

    $('#clone-btn').on('click', () => {
        cloneHolidays();
    });

    $('#clone-menui').on('click', () => {
        massSelect('Clone');
    });

    $('#confirm-btn').on('click', () => {
        updateHoliday();
        $('#confirm-modal').modal('hide');
    });

    $('#selectall-cb').on('click', () => {
        if($('#selectall-cb').is(':checked')){
            // deselect
            $('.table input:checkbox').prop('checked', true);
        }else{
            // select
            $('.table input:checkbox').prop('checked', false);
        }
    });

    $('#h-move').on('click', () => {
        console.log('checked');
        if($('#h-move').is(":checked")){
            console.log('true');
            $('#h-move-container').show();
        }else{
            console.log('false');
            $('#h-move-container input').val('');
            $('#h-move-container textarea').val('');
            $('#h-move-container').hide();
        }
    })

    $('#batch-cancel-btn').on('click', () => {
        isSelecting = false;
        $('#select-bar').hide();
        $('.h-action').empty();
        $('.h-action').append(`<i class="fas fa-chevron-right"></i>`);
    });

    function massSelect(action){
        isSelecting = true;
        unloadHoliday();
        $('#select-bar').show();
        $('#batch-btn').html(action);
        $('.h-action').empty();
        $('.h-action').append(`<input type="checkbox">`);
    }

    function cloneHolidays(){
        $('#clone-holiday-name').html(loadedHoliday.name);
        $('#clone-modal').modal('show');
    }

    function updateHoliday(){
        console.log('updateHoliday()');
        let fd = new FormData();

        // check if broadcast, only applicable to active holiday
        if(!($('#h-active').is(":checked")) && ($('#bc-select').val() > 0)) return alert('Only broadcasting of changes in active holiday is currently supported'); // temp alert.

        // check date
        if($('#h-move').is(':checked') && ($('#h-move-startdate').val() == '' || $('#h-move-enddate').val() == '')) return alert('Invalid date selection'); // temp alert.
        if($('#h-move').is(':checked') && $('#h-move-startdate').val() > $('#h-move-enddate').val()) return alert('Invalid date selection'); // temp alert.

        toastConfirm("Are you sure you want to update this holiday?", function(){
            // check if move
            if($('#h-move').is(':checked')){
                console.log('dates: ' + $('#h-move-startdate').val() + ' - ' + $('#h-move-enddate').val());
                console.log('remarks: ' + $('#h-move-remarks').val());

                // // check date
                // if($('#h-move-startdate').val() == '' || $('#h-move-enddate').val() == '') return alert('Invalid date selection'); // temp alert.
                // if($('#h-move-startdate').val() > $('#h-move-enddate').val()) return alert('Invalid date selection'); // temp alert.

                // check duration

                // set var
                fd.append('is_moved', 1);
                fd.append('moved_start_date', moment($('#h-move-startdate').datepicker('getDate')).format('YYYY-MM-DD'));
                fd.append('moved_end_date', moment($('#h-move-enddate').datepicker('getDate')).format('YYYY-MM-DD'));
                fd.append('moved_remarks', $('#h-move-remarks').val());
                
            }else{
                fd.append('is_moved', 0);
                fd.append('moved_start_date', null);
                fd.append('moved_end_date', null);
                fd.append('moved_remarks', null);
            }

            // // check if broadcast, only applicable to active holiday
            // if(!($('#h-active').is(":checked")) && ($('#bc-select').val() > 0)) return alert('Only broadcasting of changes in active holiday is currently supported');

            fd.append('id', loadedHoliday.id);
            fd.append("active", ($('#h-active').is(":checked") ? 1 : 0));
            fd.append('broadcast_option', $('#bc-select').val());
            sendAjax('<?php echo base_url('hr/holiday/update'); ?>', 'POST', fd);
        });

    }

    function deleteHoliday(){
        console.log('deleteHoliday()');

        toastConfirm("Are you sure you want to delete this holiday?", function(){
            fd = new FormData();
            fd.append('id', loadedHoliday.id);
            sendAjax('<?php echo base_url('hr/holiday/delete'); ?>', 'POST', fd);
        });
    }

    function loadHoliday(id){
        console.log('loadHoliday()');
        $('#h-states').empty();

        loadedHoliday = holidayList.find(h => h.id == id);
        console.log('laoded holiday: ' + JSON.stringify(loadedHoliday));
        try {  
            loadedHoliday.states = JSON.parse(loadedHoliday.states);
        } catch (e) {  
            console.log('parse not needed');  
        }
        loadedHoliday.active == 1 ? ($('#h-active').prop('checked', true)) : ($('#h-active').prop('checked', false));
        // check if moved
        if(loadedHoliday.is_moved == 1){
            $('#h-move').prop('checked', true);
            // load date
            $("#h-move-startdate").datepicker("update", new Date(loadedHoliday.moved_start_date));
            $("#h-move-enddate").datepicker("update", new Date(loadedHoliday.moved_end_date));
            $('#h-move-remarks').val(loadedHoliday.moved_remarks);
            $('#h-move-container').show();
        }
        $('#h-name').html(loadedHoliday.name);
        updatedStr = `Last updated: ${moment(loadedHoliday.updated_ts).format('D-M-YYYY')}`;
        if(loadedHoliday.is_moved == 1) updatedStr += `, Moved on: ${moment(loadedHoliday.moved_ts).format('D-M-YYYY')}`;
        $('#h-updated').html(updatedStr);
        $('#bc-last').html(`Last broadcasted: ${loadedHoliday.last_broadcasted ? (moment(loadedHoliday.last_broadcasted).format('DD-MM-YYYY')) : 'NA'}`);
        // $('#h-date').html((moment(loadedHoliday.original_start_date).format('MMM Do YYYY')) + ' - ' + (moment(loadedHoliday.original_end_date).format('MMM Do YYYY')));
        $('#h-date').html((moment(loadedHoliday.original_start_date).format('dddd, MMMM Do YYYY')));
        if(!Array.isArray(loadedHoliday.states)) loadedHoliday.states = [loadedHoliday.states]; // to fix for one-item parsed to str
        (loadedHoliday.states).forEach(s => {
            foundS = stateList.find(o => o.id == s);
            if(foundS) $('#h-states').append(`<span class="badge badge-pill badge-info" style="margin: 0px 3px;">${foundS.state}</span>`);
        });
        $('#detail-container').show();
    }

    function unloadHoliday(){
        $('#h-states').empty();
        loadedHoliday = null;
        $('#detail-container h6').html('');
        $('#detail-container').hide();
    }

    function sendAjax(url, method, fd){
        $('#loader-modal').modal('show');
        $.ajax({
            url: url,
            type: method,
            data: fd,
            dataType: "JSON",
            processData: false,
            contentType: false,
            success: (data) => {
                localStorage.setItem("status", data.status);
                localStorage.setItem("msg", data.msg);
                $("#loader-modal").modal('hide');
                location.reload();
            },
            error: (jqXHR, textStatus, errorThrown) => {
                localStorage.setItem("status", 'Error');
                localStorage.setItem("msg", 'Failed to update holiday. Please contact support');
                console.log(textStatus);
                console.log(errorThrown);
            },
            complete: (xhr,status) => {
                $("#loader-modal").modal('hide');
            }
        });
    }
</script>