<section class="container" style="padding-bottom: 2rem;">
    <div class="row">
        <div class="col-12">
            <div class="card bg-light-transparent">
                <!--header-selection. type dropdown. new button-->
                <div class="card-header bg-light selection-container">
                    <div class="float-left form-inline">
                        <!--type-->
                        <div class="input-group">
                            <select class="form-control" id="select-type">
                                <option value="" selected>All leave types</option>
                                <?php foreach ($leave_types as $lt) { ?>
                                    <option value="<?php echo $lt['id']; ?>">
                                        <?php echo $lt['name']; ?>
                                    </option>
                                <?php } ?>                       
                            </select>
                        </div>
                    </div>
                    <div class="float-right form-inline">
                        <!--new btn--> 
                        <div class="input-group ml-2">
                            <button class="btn btn-primary" type="button" onclick="toggleCards(true)">
                                <i class="fas fa-plus mr-1"></i>
                                Add New
                            </button>                        
                        </div>                   
                    </div>
                </div>
                <!--header-new leave.-->
                <div class="card-header bg-light create-container">
                    <div class="float-left">
                        <!--title-->
                        <h5 style="margin: 0; padding: 0;">New Leave Type</h5>
                    </div>
                </div>
                <!--all card-->
                <div class="card-body selection-container" id="all-card">
                    <div class="card no-shadow">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table id="table_types" class="table nowrap table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th class="text-center">#</th>
                                            <th>Type</th>
                                            <th>Code</th>
                                            <th>Color</th>
                                            <th>Status</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if ($leave_types): ?>
                                            <?php $i = 1; ?>
                                            <?php foreach ($leave_types as $type): ?>
                                                <tr>
                                                    <td><?php echo $i++; ?></td>
                                                    <td><a href="javascript:leaveClicked(<?php echo $type['id']; ?>)"><?php echo $type['name']; ?></a></td>
                                                    <td><?php echo $type['code']; ?></td>
                                                    <!-- <td><?php echo $type['description']; ?></td> -->
                                                    <td style="border: 1px #aaa solid; background: <?php echo $type['colour']; ?>"></td>
                                                    <td>
                                                        <?php if($type['active'] == 1){ ?>
                                                        <span class="badge badge-pill badge-success">Active</span>
                                                        <?php }else{ ?>
                                                        <span class="badge badge-pill badge-warning">Inactive</span>
                                                        <?php } ?>
                                                    </td>
                                                    <td>
                                                        <?php if ($type['is_fixed'] != 1): ?>
                                                            <button type="button" class="btn btn-sm btn-danger" onclick="deleteType(<?php echo $type['id']; ?>);" data-trigger="hover" data-tooltip="tooltip" title="Delete Type"><i class="fas fa-trash"></i></button>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <!--new form/edit selection card-->
                <div class="card-body create-container" id="selection-card">
                    <div class="card no-shadow">
                        <form>
                            <div class="card-body"> 
                                <!--status, name-->
                                <div class="form-row">
                                    <div class="col-2">
                                        <div class="form-group">
                                            <label for="type-status">Status</label>
                                            <select class="form-control" id="type-status">
                                                <option value="0">Inactive</option>
                                                <option value="1">Active</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="form-group">
                                            <label for="type-name">Name</label>
                                            <input type="text"  class="form-control required-input" id="type-name" placeholder="e.g. Annual Leave" >
                                        </div>
                                    </div>
                                    <div class="col-1">
                                        <div class="form-group">
                                            <label for="type-code">Code</label>
                                            <input type="text"  class="form-control required-input"  id="type-code" placeholder="e.g. AL" >
                                        </div>
                                    </div>
                                    <div class="col-2">
                                        <div class="form-group">
                                            <label for="type-colour">Colour</label>
                                            <div class="input-group mb-3">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text" id="type-colour-lbl"></span>
                                                </div>
                                                <input type="color" class="form-control" style="height: 38px; width: 38px;" id="type-colour" aria-describedby="type-colour-lbl">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="col-12">	
                                        <div class="form-group">
                                            <label for="type-description">Description</label>
                                            <textarea class="form-control required-input" id="type-description" placeholder="More informations about the leave type"></textarea>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="col">
                                        <div class="form-group">
                                            <label for="type-cooling-period">Cooling Period (days)</label> 
                                            <input type="number" step="1" min="0" class="form-control required-input" id="type-cooling-period" placeholder="No of days between application and actual leave date">
                                        </div>
                                    </div>
                                </div>
                                <!--bf-->
                                <div class="form-row">
                                    <div class="col-3">	
                                        <div class="form-group form-check">
                                            <input type="checkbox" class="form-check-input" <?php if ($type['is_bring_forward'] == 1) echo 'checked'; ?> id="type-brought-forward-cb">
                                            <label for="is_bring_forward-<?php echo $type['id']; ?>">Can be brought forward</label> 
                                        </div>
                                    </div>
                                    <div class="col-5 brought-forward-container">
                                        <div class="form-group">
                                            <label for="bring_forward_percent-<?php echo $type['id']; ?>">Brought Forward Amount (%)</label> 
                                            <input type="number" step="1" min="0" class="form-control" name="bring_forward_percent-<?php echo $type['id']; ?>" id="type-brought-forward-percentage" placeholder="Will be converted to selected leave in the following year" value="<?php echo $type["bring_forward_percent"]; ?>">
                                        </div>
                                    </div>
                                    <div class="col-4 brought-forward-container">
                                        <div class="form-group"> 
                                            <label for="type-brought-forward-leave">Brought Forward Leave Type</label> 
                                            <select class="form-control" id="type-brought-forward-leave">
                                                <option value="0">Select Leave Type</option> 
                                                <?php foreach ($leave_types as $row): ?>
                                                    <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <!--increment per cycle-->
                                <div class="form-row">
                                    <div class="col-4">	
                                        <div class="form-group form-check">
                                            <input type="checkbox" class="form-check-input" id="type-increment-cb">
                                            <label for="type-increment-cb">Increment per cycle</label> 
                                        </div>
                                    </div>
                                    <div class="col-4 increment-container">	
                                        <div class="form-group">
                                            <label for="increment_period-<?php echo $type['id']; ?>">Cycle Period (months)</label> 
                                            <input type="number" step="1" min="0" class="form-control" name="increment_period-<?php echo $type['id']; ?>" id="type-increment-cycle" placeholder="No. of months per cycle" value="<?php echo $type["increment_period"]; ?>">
                                        </div>
                                    </div>
                                    <div class="col-4 increment-container">
                                        <div class="form-group">
                                            <label for="increment_value-<?php echo $type['id']; ?>">Increment Value (days)</label> 
                                            <input type="number" step="1" min="0" class="form-control" name="increment_value-<?php echo $type['id']; ?>" id="type-increment-value" placeholder="No. of days added per cycle" value="<?php echo $type["increment_value"]; ?>">
                                        </div>
                                    </div>
                                </div>
                                <!--module allocation-->
                                <div class="form-row">
                                    <div class="col-4">
                                        <div class="form-group form-check">
                                            <input type="checkbox" class="form-check-input" id="type-module-allocation-cb">
                                            <label class="form-check-label" for="type-module-allocation-cb">Allocation on own module</label>
                                        </div>
                                    </div>
                                    <div class="col-8 module-allocation-container">	
                                        <div class="form-group">
                                            <label for="type-module-allocation-url">Module Allocation URL</label>
                                            <div class="input-group mb-3">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text"><?php echo base_url(); ?></span>
                                                </div>
                                                <input type="text" class="form-control" id="type-module-allocation-url">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group form-check">
                                    <input type="checkbox" class="form-check-input" <?php if ($type['is_prorate'] == 1) echo 'checked'; ?> id="type-prorate-cb" name="is_prorate-<?php echo $type['id']; ?>">
                                    <label class="form-check-label" for="is_prorate-<?php echo $type['id']; ?>">Prorate leave</label>
                                </div>
                                <div class="form-group form-check">
                                    <input type="checkbox" class="form-check-input" <?php if ($type['include_holiday'] == 1) echo 'checked'; ?> id="type-include-holiday-cb">
                                    <label class="form-check-label <?php if ($type['include_holiday'] == 1) echo 'active'; ?>" for="typeIncHoliday-<?php echo $type['id']; ?>">Include holidays and rest day</label>
                                </div>	
                                <div class="form-group form-check">
                                    <input type="checkbox" class="form-check-input" id="type-attachment-cb">
                                    <label class="form-check-label" for="type-attachment-cb">Application require attachment</label>
                                </div>
                                <div class="form-group form-check">
                                    <input type="checkbox" class="form-check-input" id="type-allocation-value-cb">
                                    <label class="form-check-label" for="type-allocation-value-cb">Application require non-zero allocation</label>
                                </div>
                            </div>
                            <input type="hidden" id="type-id">
                        </form>
                        <div class="card-footer selection-container">
                            <div class="float-left mt-1">
                                <span class="text-danger" id="uerror-string"></span>
                            </div>
                            <div class="float-right">
                                <button type="button" class="btn btn-warning" onclick="toggleCards(false)" >Cancel</button>
                                <button type="button" class="btn btn-primary" onclick="updateType()">Update</button>
                            </div>
                        </div>
                        <div class="card-footer create-container">
                            <div class="float-left mt-1">
                                <span class="text-danger" id="error-string"></span>
                            </div>
                            <div class="float-right">
                                <button type="button" class="btn btn-warning " onclick="toggleCards(false)" >Cancel</button>
                                <button type="button" class="btn btn-primary " onclick="createLeaveType()" >Save</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</section>

<!--modals-->
<?php
// loader-modal
$this->load->view('hr/leave/modals/modal_loader'); 
?>

<script>
    var leaveTypes = <?php echo json_encode($leave_types); ?>;
    toggleCards(false);

    $('#tab a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });

    var hash = window.location.hash;

    $(document).ready(function () {
        $('#tab a[href="' + hash + '"]').tab('show');
        $('#select-type').val('').trigger('change');
        
        
    });

    $(".nav-pills > a").on("shown.bs.tab", function (e) {
        var id = $(e.target).attr("href").substr(1);
        window.location.hash = id;
    });

    $("#typeForm").on("submit", function (e) {
        e.preventDefault();
        createType();
    });

    $('#select-type').on('change', function () {
        if (id = $(this).val()) {
            $('#selection-card').show();
            $('#all-card').hide();
            loadType(id);
        } else {
            $('#all-card').show();
            $('#selection-card').hide();
        }
    });
    
    $('#type-colour').on('change', function(){
       $('#type-colour-lbl').html($(this).val().toUpperCase());
    });
    
    $('#type-brought-forward-cb').on('change', function(){
        $('.brought-forward-container input').prop('disabled', !($(this).prop('checked')));
        $('.brought-forward-container select').prop('disabled', !($(this).prop('checked')));
    });
    
    $('#type-increment-cb').on('change', function(){
        $('.increment-container input').prop('disabled', !($(this).prop('checked')));
    });
    
    $('#type-module-allocation-cb').on('change', function(){
        $('.module-allocation-container input').prop('disabled', !($(this).prop('checked')));
    });
    
    function leaveClicked(id){
        $('#select-type').val(id).trigger('change');
    }

    function toggleCards(isCreating){
        if(isCreating){
            $('.selection-container').hide();
            $('.create-container').show();
            $('.create-container :input').each(function(){
                $(this).val('');
                if($(this).prop('type') == 'select-one') $(this).val(0);
                if($(this).prop('type') == 'color') $(this).val('#ffffff').trigger('change');
            });
            $('.create-container :checkbox').each(function(){
                $(this).prop('checked', false).trigger('change');
            });
        }else{
            $('.selection-container').show();
            $('.create-container').hide();
            $('#select-type').val('').trigger('change');
        }
    }

    function loadType(typeId) {
        loadedType = leaveTypes.find(to => to.id == typeId);
//        console.log(JSON.stringify(loadedType));
        if (loadedType) {
            $('#type-id').val(loadedType.id);
            $('#type-status').val(loadedType.active);
            $('#type-name').val(loadedType.name);
            $('#type-code').val(loadedType.code);
            $('#type-colour').val(loadedType.colour);
            $('#type-colour-lbl').html(loadedType.colour);
            $('#type-description').val(loadedType.description);
            $('#type-cooling-period').val(loadedType.cooling_period);
            $('#type-increment-cb').prop('checked', (loadedType.has_increment_per_cycle == 1)).trigger('change');
            $('#type-increment-cycle').val(loadedType.increment_period);
            $('#type-increment-value').val(loadedType.increment_value);
            $('#type-brought-forward-cb').prop('checked', (loadedType.is_bring_forward == 1)).trigger('change');
            $('#type-brought-forward-percentage').val(loadedType.bring_forward_percent);
            $('#type-brought-forward-leave').val(loadedType.forward_leave_type_id);
            $('#type-include-holiday-cb').prop('checked', (loadedType.include_holiday == 1));
            $('#type-prorate-cb').prop('checked', (loadedType.is_prorate == 1));
            $('#type-attachment-cb').prop('checked', (loadedType.app_require_attachment == 1));
            $('#type-allocation-value-cb').prop('checked', (loadedType.require_allocation_value == 1));
            $('#type-module-allocation-cb').prop('checked', (loadedType.module_allocation == 1)).trigger('change');
            $('#type-module-allocation-url').val(loadedType.module_allocation_url);
        }
    }

    function openTypeModal() {
        clearForm("#typeForm");

        $("#typeModal").modal('show');
    }
    
    function checkForm() {
        console.log('checking form');
        empty = false;
        errorStr = '';
        $('.required-input').each(function () {
            if (this.id != null && this.id != undefined && this.value == '') {
                console.log('id: ' + this.id + ' val length: ' + this.value.length);
                console.log('found an empty input: ' + this.id);
                label = $("label[for=" + this.id + "]");
                console.log('label: ' + label.text());
                empty = true;
                errorStr += label.text();
                return false;
            }
        });
        return {
            error: empty,
            msg: errorStr
        };
    }

    function createLeaveType() {
        console.log('createLeaveType()');
        $('#error-string').html('');
        
        checkRes = checkForm();
        if (checkRes.error)
            return ($('#error-string').html(checkRes.msg + ' is required'));
        
        toastConfirm("Are you sure you want to create this leave type?!", function () {
//            $('#loader-modal').modal('show');
            
            $.ajax({
                type: "POST",
                url: "<?php echo base_url('hr/leave/createLeaveType'); ?>",
                data: {
                    active: $('#type-status').val(),
                    name: $("#type-name").val(),
                    code: $("#type-code").val(),
                    description: $("#type-description").val(),
                    colour: $("#type-colour").val(),
                    include_holiday: $('#type-include-holiday-cb').prop('checked') ? 1 : 0,
                    is_prorate: $('#type-prorate-cb').prop('checked') ? 1 : 0,
                    is_bring_forward: $('#type-brought-forward-cb').prop('checked') ? 1 : 0,
                    has_increment_per_cycle: $('#type-increment-cb').prop('checked') ? 1 : 0,
                    app_require_attachment: $('#type-attachment-cb').prop('checked') ? 1 : 0,
                    module_allocation: $('#type-module-allocation-cb').prop('checked') ? 1 : 0,
                    require_allocation_value: $('#type-allocation-value-cb').prop('checked') ? 1 : 0,
                    cooling_period: $('#type-cooling-period').val(),
                    bring_forward_percent: $('#type-brought-forward-percentage').val(),
                    forward_leave_type_id: $('#type-brought-forward-leave').val(),
                    increment_period: $('#type-increment-cycle').val(),
                    increment_value: $('#type-increment-value').val(),
                    module_allocation_url: $('#type-module-allocation-url').val()
                },
                dataType: "JSON",
                success: (data) => {
//                    $("#loader-modal").modal('hide');
                    if(data.status.toLowerCase() == 'success'){
                        localStorage.setItem("status", data.status);
                        localStorage.setItem("msg", data.msg);
                        window.location.replace(window.location.href);
                    }else{
                        $('#error-string').html(data.msg);
                    }
                    
                },
                error: (jqXHR, textStatus, errorThrown) => {
                    $("#loader-modal").modal('hide');
                    console.log('ajax error');
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });
        });
    }

    function updateType(id) {
        console.log('updateType()');
        $('#uerror-string').html('');
        
        checkRes = checkForm();
        if (checkRes.error)
            return ($('#uerror-string').html(checkRes.msg + ' is required'));
        
            toastConfirm("Are you sure you want to update this leave type?", () => {
                $.ajax({
                    type: "POST",
                    url: "<?php echo base_url('hr/leave/updateType'); ?>",
                    data: {
                        id: $('#type-id').val(),
                        active: $('#type-status').val(),
                        name: $("#type-name").val(),
                        code: $("#type-code").val(),
                        description: $("#type-description").val(),
                        colour: $("#type-colour").val(),
                        include_holiday: $('#type-include-holiday-cb').prop('checked') ? 1 : 0,
                        is_prorate: $('#type-prorate-cb').prop('checked') ? 1 : 0,
                        is_bring_forward: $('#type-brought-forward-cb').prop('checked') ? 1 : 0,
                        has_increment_per_cycle: $('#type-increment-cb').prop('checked') ? 1 : 0,
                        app_require_attachment: $('#type-attachment-cb').prop('checked') ? 1 : 0,
                        module_allocation: $('#type-module-allocation-cb').prop('checked') ? 1 : 0,
                        require_allocation_value: $('#type-allocation-value-cb').prop('checked') ? 1 : 0,
                        cooling_period: $('#type-cooling-period').val(),
                        bring_forward_percent: $('#type-brought-forward-percentage').val(),
                        forward_leave_type_id: $('#type-brought-forward-leave').val(),
                        increment_period: $('#type-increment-cycle').val(),
                        increment_value: $('#type-increment-value').val(),
                        module_allocation_url: $('#type-module-allocation-url').val()
                    },
                    dataType: "JSON",
                    success: (data) => {
                        if(data.status.toLowerCase() == 'success'){
                            localStorage.setItem("status", data.status);
                            localStorage.setItem("msg", data.msg);
                            window.location.replace(window.location.href);
                        }else{
                            $('#uerror-string').html(data.msg);
                        }
                    
                    },
                    error: (jqXHR, textStatus, errorThrown) => {
                        $("#loader-modal").modal('hide');
                        console.log('ajax error');
                        console.log(textStatus);
                        console.log(errorThrown);
                    }
                })
            })
    }

    function deleteType(id) {
        toastConfirm("Are you sure you want to delete this leave type?", function () {
            $.ajax({
                type: "POST",
                url: "<?php echo base_url('hr/leave/deleteType'); ?>",
                data: {id: id},
                dataType: "JSON",
                success: function (data) {
                    if (data.status == "Success")
                    {
                        localStorage.setItem("status", data.status);
                        localStorage.setItem("msg", data.msg);

                        location.reload();
                    }
                }
            })
        });
    }


    function clearForm(e) {
        $(e).parsley().reset();

        $(e).find("input, textarea").val("");
    }
</script>