<?php
if ($permissions->hasPermission('addJob')) {
    include("Views/HRM/addJob.php");
}
?>
<style>
    .table thead tr >th{
        background-color:#4c0870;
        color:#fff;
    }
    .table thead tr th[class*='sorting_'] {
        color: #fff;
    }
    .bg-master-lighter {
        border:none;
        background-color:#fff;
        border-top:1px solid #ddd;  
    }
    .btn-default{
        border: none;
        background-color: #eee;
    }
    .btn-default:hover{
        background-color:#4c0870!important;
        color:#fff;
        border: none;
    }
    #tableWithSearch tbody >tr>td >div.Arrow{
        cursor:pointer;   
    }
    #tableWithSearch tbody >tr>td >div.Arrow:before{
        content: "\f054";
        display: inline-block;
        margin-right: 8px;
        font-family: 'FontAwesome';
        -webkit-transition: all 0.12s linear;
        transition: all 0.12s linear;
    }
    #tableWithSearch tbody >tr.shown>td >div.Arrow:before {
        -webkit-transform: rotate(90deg);
        -ms-transform: rotate(90deg);
        transform: rotate(90deg);
    }
    .StatementTable{
        width: 80%;
        margin: 0 auto;
        border: 1px solid rgb(200, 200, 200);
    }
    .StatementTable th{
        border: 1px solid rgb(200, 200, 200) !important;
    }
    .StatementTable tbody tr:last-child > td{
        border-bottom: 1px solid rgb(200, 200, 200) !important;
    }
    .StatementTable td,.StatementTable th{
        font-size:11px !important;
    }
    .TableLoader{
        text-align:center;
        width: 50%;
        margin: 0 auto;
    }
    .ValSpan {
        opacity:0;
    }
    .NameCenter{
        margin-left: 290px;
    }
</style>
<script>
    function AddCommas(val) {
        val = parseFloat(val.toString()).toString();
        while (/(\d+)(\d{3})/.test(val.toString())) {
            val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
        }
        return val.replace(/\.0$|\.00$/, "") || "0";
    }
    function FixNumber(val) {
        return AddCommas(parseFloat(val + "").toFixed(2));
    }
//    // to remove many digits after the period
//    $(function () {
//        $(".ValSpan").each(function () {
//            $(this).html(AddCommas(parseFloat($.trim($(this).text())).toFixed(3)))})})
</script>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title"><?php print CommonLanguage::getMessage('jobs'); ?></div>
            <div class="clearfix"></div>
        </div>
        <div class="panel-body">
            <?php
            if ($permissions->hasPermission('addJob')) {
                echo Forms::FloatingAddButton('4c0870', '#add_job', CommonLanguage::getMessage('add'));
            }
            ?>
            <table class="table table-detailed" id="tableWithSearch">
                <thead>
                    <tr >

                        <th class="text-center" ><?php print CommonLanguage::getMessage('job_name'); ?></th>
                        <th class="text-center" ><?php print CommonLanguage::getMessage('description'); ?></th>
                        <th class="text-center" ><?php print CommonLanguage::getMessage('Action'); ?></th>
                    </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade bs-example-modal-md" id="DeleteJobFromList" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width:50%">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title"><?php print CommonLanguage::getMessage('Confirm_Delete'); ?></h4>
                <div id="DeleteJob_modalAlert" class="alert alert-success"></div>
            </div>
            <div class="modal-body">
                <form>
                    <div class="row">
                        <div class="col-md-12 ">
                            <div class="col-md-12" style="margin-top: 20px;">
                                <p><?php print CommonLanguage::getMessage('delete_job'); ?> <strong class="Name"></strong></p>
                                <p><?php print CommonLanguage::getMessage('Proceed_Delete'); ?></p>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close'); ?></button>
                <button type="button" class="btn btn-danger" id="Job_Delete" style="width:auto"><?php print CommonLanguage::getMessage('delete'); ?></button>
            </div>
        </div>
    </div>
</div>
<div class="col-md-12 PayGradeItem form-group hidden"  >
    <div class="col-sm-3">
        <input type="text" name="Paygrade_Name" id="Paygrade_Name" class="form-control Paygrade_Name"	placeholder="<?php print CommonLanguage::getMessage('paygrade'); ?>">	
    </div>
    <div class="col-sm-3">
        <input type="number"  step="any" name="Paygrade_Value"  id="Paygrade_Value" class="form-control Paygrade_Value"	placeholder="<?php print CommonLanguage::getMessage('paygrade_value'); ?>"/>
    </div>  
    <div class="col-sm-4" >
        <!--<span onclick="addinput()" class="fa fa-plus-circle" style="margin-top: 10px; color: #40d9ca;float: right;margin-right: -14px;" ></span>-->
        <div class="input-group-btn DropDownForForms Closable" id="CurrencyDropDown">
            <button type="button" class="btn btn-success btn-block dropdown-toggle" name="Paygrade_Currency" data-toggle="dropdown" aria-expanded="false">
                <span class="currency-title"><strong ><?php print CommonLanguage::getMessage('Select_Currency'); ?></strong></span>
                <input type="hidden" value="" class="form-control ignore Paygrade_Currency" onkeyup="return false" onkeydown="return false" required/>
            </button>
            <ul class="dropdown-menu">
                <?php echo($currency->GetLIListCurrency()); ?>
                <li class="divider"></li>
                <li><a class="LoadMore"><?php print CommonLanguage::getMessage('More'); ?>..</a></li>
            </ul>
        </div>
    </div>
    <div class="col-md-2 AddButtons">
        <span class="fa fa-plus-circle" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
        <span class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;"></span>
    </div>
</div>
<script>
    var NameLang = <?php echo json_encode(CommonLanguage::getMessage('Name')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            title = <?php echo json_encode(CommonLanguage::getMessage('jobs')); ?>,
            PaygradeValLang = <?php echo json_encode(CommonLanguage::getMessage('paygrade_value')); ?>;
    var IsEdit = false, IDToEdit = 0;
    $(function () {
        $(".floatingContainer").on("click", function () {
            IsEdit = false;
            IDToEdit = 0;
            build_job_absences()

        })

        RebuildDataTable(title, [0, 1], 'HRMAjax/viewJobsRequest', '')

        var table = $('#tableWithSearch');

        table.dataTable();

        var StatementTableTemplate = '<table class="table table-hover StatementTable">' +
                '<thead>' +
                '    <tr>' +
                '        <th>' + NameLang + '</th>' +
                '        <th>' + PaygradeValLang + '</th>' +
                '    </tr>' +
                '</thead>' +
                '<tbody>' +
                '</tbody>' +
                '</table>';
        var LoadingTableTemplate = '<div class="TableLoader"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress"/></div>';
        $('tbody', table).on('click', 'td:lt(2)', function () {
            if ($(this).hasClass('shown') && $(this).next().hasClass('row-details')) {
                $(this).removeClass('shown');
                $(this).next().remove();
                return;
            }
            var tr = $(this).closest('tr');

            var row = table.DataTable().row(tr);
            $(this).parent('tr').find('.shown').removeClass('shown');
            $(this).parent('tr').find('.row-details').remove();
            row.child(LoadingTableTemplate).show();
            tr.addClass('shown');
            tr.next().addClass('row-details');
            var code = {
                code_id: $(this).find('.Delete').attr('data-id')
            }

            $.ajax({
                url: 'HRMAjax/viewJobsRequest',
                data: code,
                method: 'GET',
                dataType: 'json',
                complete: function (data, vv) {
                    if (vv == "success") {
                        var TheTable = $(StatementTableTemplate), results = (data.responseJSON);
                        //TheTable.css("display",(results.length > 0 ? '' :'none'))
                        for (var i = 0; i < (results.length); i++) {
                            var locations = "<tr data-id=" + results[i]["Paygrade_ID"] + ">" +
                                    "<td class='Name'>" + results[i]["Paygrade_Name"] + "</td>" +
                                    "<td>" + ' ' + results[i]["Currency_Symbol"] + " " + FixNumber(results[i]["Paygrade_Value"]) + "</td></tr>";
                            $("tbody", TheTable).append(locations);
                        }
                        $(".TableLoader", tr.next()).replaceWith(TheTable);
                    } else {
                        alert('error')
                    }
                }
            })
        });

        $("#tableWithSearch").on("click", ".edit_job", function (e) {
            IsEdit = true;
            IDToEdit = $(this).parents('.Action').attr('data-id');
            $(".PayGradeClass").remove()

            var data = {
                Job_Id: $(this).parents('.Action').attr("data-id")
            }

            $.ajax({
                url: "HRMAjax/ManagePaygradeRequest",
                data: data,
                dataType: "json",
                complete: function (v, vv) {
                    if (vv = "success") {
                        //full the info 
                        var results = (v.responseJSON);
                        $("#Job_Name").val(results['Job_Name']),
                                $("#Job_Description").val(results['Job_Description'])

                        // re-bulid the table
                        $(".PayGradeClass").empty().remove()
                        if (results['paygrade'].length > 0) {
                            for (var i = 0; i < (results['paygrade'].length); i++) {
//                                console.log(i + '===')
                                var item = $(".PayGradeItem").clone();
                                item.removeClass("PayGradeItem hidden").addClass("PayGradeClass")
                                item.find(".Paygrade_Name").val(results['paygrade'][i]['Paygrade_Name'])
                                item.find(".Paygrade_Value").val(results['paygrade'][i]['Paygrade_Value'])
                                item.attr("data-id", results['paygrade'][i]['Paygrade_ID'])
                                item.find(".Paygrade_Currency").val(results['paygrade'][i]['Currency_ID'])
                                item.find(".currency-title").html(results['paygrade'][i]['Currency_Name'] + ' - ' + results['paygrade'][i]['Currency_Name'])
                                $("#PayGrade").append(item)
                            }
                        } else {
                            var item = $(".PayGradeItem").clone()
                            item.removeClass("PayGradeItem hidden").addClass("PayGradeClass")
                            $("#PayGrade").append(item)
//                            console.log(item)

                        }
                        build_job_absences(IDToEdit)
                        $("#add_job").modal("show")

                    }
                }
            })
        })


    })
    var CurrentDeparmtent_ToDelete;
    $("#tableWithSearch").on("click", ".Delete", function () {
        var JobName = $(this).parents("tr").find("td:eq(0)").text()//parent tr keep searching till it reach tr 
        $("#DeleteJobFromList").find(".Name").text(JobName).end().modal("show") // to set the name of employee in modal to delete 
        CurrentDeparmtent_ToDelete = $(this).parents('.Action').attr('data-id')  // current id to delete
    })
    $("#DeleteJob_modalAlert").hide(); // hide the alert when submit if true or false
    //on click the delete button in modal get the id of the selected employee to delete it 
    $("#Job_Delete").on("click", function () {
//        var del_id = $(this).attr('data-id');
        var oTable = $('#tableWithSearch').dataTable();
        var me = this;
        $.ajax({
            type: 'POST',
            url: 'HRMAjax/viewJobsRequest',
            dataType: 'json',
            data: {GetID: CurrentDeparmtent_ToDelete},
            complete: function (data, vv) {
                if (vv == "success" && data.responseJSON == "OK") {

                    $("#DeleteJob_modalAlert").attr("class", "alert alert-success").html(Submitted_Successfully).show();
                    setTimeout(function () {
                        $("#DeleteJobFromList").modal("hide")
                        $("#DeleteJob_modalAlert").modal("hide")
                    }, 1000)
                    $('#tableWithSearch').DataTable().destroy();
                    RebuildDataTable(title, [0, 1], 'HRMAjax/viewJobsRequest', '')

                } else {
                    $("#DeleteJob_modalAlert").attr("class", "alert alert-danger").html(data.responseJSON[0]).show();

                }
            }});
    })

    function build_job_absences(job_id) {
        job_id = job_id == undefined ? 0 : job_id;
        $(".abs-row:eq(0) input").val("").attr("data-id",0)
        $(".abs-row:gt(0)").remove()
        $.ajax({
            url: 'HRMAjax/get_absence_by_type',
            data: {type_id: job_id,type:3},
            dataType: 'json',
            complete: function (v1, v2) {
                if (v2 == 'success') {
                    var data = v1.responseJSON;
                    $.each(data, function (indx, row) {
                        if (indx == 0) {
                            $(".abs-row:eq(0)").attr("data-id", row['Absence_Reason_ID'])
                            $("input.reason_name").val(row['Absence_Reason_Name'])
                            $("input.nb_days").val(row['nb_days'])
                        } else {
                            var cloned_row = $(".abs-row:eq(0)").clone();
                            $("input.reason_name", cloned_row).val(row['Absence_Reason_Name'])
                            $("input.nb_days", cloned_row).val(row['nb_days'])
                            cloned_row.attr("data-id", row['Absence_Reason_ID'])
                            cloned_row.appendTo($("#absences"))
                        }
                    })
                }
            }
        })
    }
</script>
