<div class="container-fluid container-fixed-lg bg-white" >
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <?php echo Forms::ModalLoader('Loader') ?>
            <div class="modal-header clearfix text-left" >
                <h5><span class="semi-bold"><?php echo CommonLanguage::getMessage("piece_price"); ?>  </span></h5>
            </div>
            <div class="modal-body" >
                <form id="PiecePricePostForm" method="POST" onsubmit="return false">
                    <div class="row"><?php echo Forms::AlertDiv('ValidationAlert');?></div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="col-md-3 form-group">
                                <label><?php print CommonLanguage::getMessage('Date'); ?></label><span class="red-star">*</span>
                                <input type="text" placeholder="<?php print CommonLanguage::getMessage('Date'); ?>" id="piece_price_date" name="piece_price_date" class="form-control" required autocomplete="off">
                            </div>
                            <div class="col-md-3 form-group">
                                <label><?php echo CommonLanguage::getMessage('branch');?></label><span class="red-star">*</span>
                                <input class=" full-width common_dis_piece_price" id="branch_id" name="branch_id" type="hidden"  value="<?= empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_id'] : smc_session()['user_accounts']['branch_id']; ?>" data-select-name='<?= json_encode(empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_name'] : smc_session()['user_accounts']['branch_name']); ?>' required/>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12 ">
                            <div class="col-md-2 form-group">
                                <label><?php echo CommonLanguage::getMessage('employee') ?></label>
                            </div>
                            <div class="col-md-2 form-group">
                                <label><?php echo CommonLanguage::getMessage('piece_service') ?></label>
                            </div>
                            <div class="col-md-2 form-group">
                                <label><?php echo CommonLanguage::getMessage('piece_price') ?></label>
                            </div>
                            <div class="col-md-2 form-group">
                                <label><?php echo CommonLanguage::getMessage('quantity') ?></label>
                            </div>
                            <div class="col-md-2 form-group">
                                <label><?php echo CommonLanguage::getMessage('total_price') ?></label>
                            </div>
                        </div>
                    </div>
                    <div id="main_div">
                        <div class="row add-row">
                            <div class="col-md-12  m-b-10">
                                <div class="col-md-2">
                                    <input name="employee_id" class="full-width common_dis_piece_price" type="hidden"/>
                                </div>
                                <div class="col-md-2">
                                    <select name="piece_service_id" class="full-width common_dis_piece_price" data-init-plugin="select2">
                                        <option value=""><?php print CommonLanguage::getMessage('choose_piece_service'); ?></option>
                                        <?php foreach ($piece_service as $service): ?>
                                        <option value="<?php echo $service['piece_service_id']; ?>" data-currency="<?php echo $service['currency_id']; ?>" data-piece-price="<?php echo $service['piece_service_price']; ?>"><?php echo $service['piece_service_name']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <input class="nb_hrs form-control empty" name="piece_price" type="number" step="any" readonly/>
                                </div>
                                <div class="col-md-2">
                                    <input class="nb_hrs form-control empty" name="piece_quantity" onkeyup="changeEmployeeQuantity(this)" type="number" onchange="changeEmployeeQuantity(this)" step="any" />
                                </div>
                                <div class="col-md-2">
                                    <input class="nb_hrs form-control empty" name="total_price" type="number" step="any" readonly/>
                                </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;display:none;"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <br><br>
                    <div class="col-md-12 m-t-10 ">
                        <div class="col-md-4 pull-right">
                            <button class="btn btn-success " id="SubmitAddPiecePrice"  > <?php print CommonLanguage::getMessage('Save'); ?>   </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<script>
    var Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
        Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
                choose_piece_service = <?php echo json_encode(CommonLanguage::getMessage('choose_piece_service')); ?>,
                    assign_employee_quantity = <?php echo json_encode(CommonLanguage::getMessage('assign_employee_quantity')); ?>,
                        assign_quantity_selected_emp = <?php echo json_encode(CommonLanguage::getMessage('assign_quantity_selected_emp')); ?>,
                            is_actual = <?php echo json_encode($is_actual);?>;
                            $(function () {
                                build_select2($("input[name=employee_id]"), "xhr/employeeSearch?is_actual="+is_actual);
                                build_select2($("#branch_id"), "xhr/CommonSearch?col_id=branch_id&col_name=branch_name&table=tbl_organization_branches")
                                $("#piece_price_date").datepicker({autoclose: true}).on('changeDate',function(){
                                    getDataDate()
                                });
                                $("#main_div").on("click", " .fa-plus-circle", function (e) {
                                    $("#main_div  .fa-minus-circle").css("display", "inline-block")
                                    var Parent = $(this).parents(".add-row"),
                                        NewItem = Parent.clone().insertAfter(Parent);
                                    NewItem.find(".select2-container").remove();
                                    NewItem.find("input[name=piece_quantity],input[name=piece_price],input[name=total_price]").val('');
                                    NewItem.find("input[name=employee_id]").val('');
                                    NewItem.find("input[name=employee_id]").attr("data-select-name", "");
                                    build_select2(NewItem.find("input[name=employee_id]"), "xhr/employeeSearch?is_actual="+is_actual);
                                    $("select[name=piece_service_id]", NewItem).select2()
                                    $(".select2-container", NewItem).show();
                                });
                                $("#main_div").on("click", ".fa-minus-circle", function (e) {
                                    $(this).closest(".add-row").empty().remove();
                                    $(".add-row").each(function () {
                                        $(" .fa-minus-circle", $(this).parents('#main_div')).css({"display": $(".add-row", $(this).parents('#main_div')).length <= 1 ? "none" : "inline-block"})
                                    });
                                });
                                $('#main_div').on("change","select[name=piece_service_id]",function(){
                                    var parent = $(this).parents('.row.add-row'),
                                        current_quantity = parseFloat($('input[name=piece_quantity]',parent).val()),
                                        piece_price = parseFloat($('option:selected', this).attr('data-piece-price'));
                                    $('input[name=piece_price]',parent).val(piece_price);
                                    current_quantity ?
                                        $('input[name=total_price]',parent).val(current_quantity * piece_price) : '';
                                });
                                $("#SubmitAddPiecePrice").on("click", function () {
                                    if ($("#piece_price_date").val() == '' || !$("#branch_id").val()) {
                                        AddAlert('#ValidationAlert',Required_Fields,'danger');
                                        return false;
                                    }
                                    var Data = new FormData(document.getElementById("PiecePricePostForm")),
                                        piece_price_arr = [],
                                        qauntity_valid=true,piece_service_valid = true;
                                    $(".row.add-row").each(function () {
                                        var employee_id = $(this).find("input[name=employee_id]").val(),
                                            piece_service_id = $(this).find("select[name=piece_service_id]").val(),
                                            piece_quantity = $(this).find("input[name=piece_quantity]").val(),
                                            piece_price = $(this).find("input[name=piece_price]").val(),
                                            total_price = $(this).find("input[name=total_price]").val(),
                                            currency_id = $(this).find("select[name=piece_service_id] option:selected").attr('data-currency');
                                        if(employee_id){
                                            if(piece_service_id == ""){
                                                piece_service_valid = false;
                                            }
                                            if(piece_quantity == ''){
                                                qauntity_valid = false;
                                            }
                                            piece_price_arr.push({
                                                employee_id: employee_id,
                                                piece_service_id: piece_service_id,
                                                piece_quantity: piece_quantity,
                                                piece_price: piece_price,
                                                total_price: total_price,
                                                currency_id: currency_id
                                            });
                                        }
                                    });
                                    Data.append("piece_price_arr", JSON.stringify(piece_price_arr));
                                    Data.append("is_actual",is_actual);
                                    if(piece_price_arr.length == 0){
                                        AddAlert('#ValidationAlert',assign_employee_quantity,'danger');
                                        return false;
                                    }
                                    if(!piece_service_valid){
                                        AddAlert('#ValidationAlert',choose_piece_service,'danger');
                                        return false;
                                    } 
                                    if(!qauntity_valid){
                                        AddAlert('#ValidationAlert',assign_quantity_selected_emp,'danger');
                                        return false;
                                    }
                                    $("#Loader").removeClass('hidden');
                                    $.ajax({
                                        url: "HRMAjax/submitEmployeePiecePrice",
                                        method: "POST",
                                        data: Data,
                                        processData: false,
                                        contentType: false,
                                        dataType:"json",
                                        complete: function (v1, v2) {
                                            if (v2 == 'success') {
                                                if (v1.responseJSON == 'OK') {
                                                    AddAlert('#ValidationAlert',Submitted_Successfully,'success');
                                                    $('.row.add-row:gt(0)').remove();
                                                    $('input.empty,#piece_price_date').val('');
                                                    $("input[name=employee_id]").val('');
                                                    $("input[name=employee_id]").attr("data-select-name", "");
                                                    $("select[name=piece_service_id]").val('')
                                                    $("select[name=piece_service_id]").select2()
                                                    build_select2($("input[name=employee_id]"), "xhr/employeeSearch?is_actual="+is_actual);
                                                    $('.AddButtons .fa-minus-circle').css({"display":"none"});
                                                } else {
                                                    AddAlert('#ValidationAlert',v1.responseJSON,'danger');
                                                }
                                            } else {
                                                AddAlert('#ValidationAlert',v1.responseJSON,'danger');
                                            }
                                            $("#Loader").addClass('hidden');
                                        }
                                    });
                                });
                            });
    function changeEmployeeQuantity(input){
        var parent = $(input).parents(".row.add-row"),
            current_quantity = parseFloat($(input).val()),
            piece_price = parseFloat($('input[name=piece_price]',parent).val());
        current_quantity ? parent.find('input[name=total_price]').val(current_quantity*piece_price) : '';
    }
    function getDataDate(){
        $('#Loader').removeClass('hidden')
        $.ajax({
            url: 'HRMAjax/getEmployeePieceData',
            method: 'GET',
            data: {piece_price_date:$("#piece_price_date").val(),is_actual:is_actual,branch_id:$('#branch_id').val()},
            dataType:"json",
            complete: function (data, vv) {
                if(vv == 'success'){
                    var response = data.responseJSON;
                    if(!$.isEmptyObject(response)){
                        if(response .hasOwnProperty('payment_piece')){
                            $('select.common_dis_piece_price,input.common_dis_piece_price,#SubmitAddPiecePrice').attr('disabled',true);
                            $('input[name=piece_quantity]').attr('readonly',true);
                            toastr.warning('<?php echo CommonLanguage::getMessage('payment_date_done');?>');
                        }else{
                            var main_data = response.main;
                            $("input[name=branch_id]").val(main_data.branch_id);
                            $("input[name=branch_id]").attr("data-select-name", main_data.branch_name);
                            build_select2($("#branch_id"), "xhr/CommonSearch?col_id=branch_id&col_name=branch_name&table=tbl_organization_branches");
                            var details = response.details,
                                current_row = $("#main_div .add-row:eq(0)").clone()
                            $("#main_div").empty();
                            $.each(details,function(index,value){
                                current_row = current_row == null ? $("#main_div .add-row:eq(0)").clone() : current_row;
                                $('input[name=piece_quantity]',current_row).val(details[index].piece_quantity);
                                $('input[name=total_price]',current_row).val(details[index].total_price);
                                $("#main_div").append(current_row);
                                $(".select2-container",current_row).remove();
                                $("input[name=employee_id]",current_row).val(details[index].employee_id);
                                $("input[name=employee_id]",current_row).attr("data-select-name", details[index].employee_name);
                                build_select2($("input[name=employee_id]"), "xhr/employeeSearch?is_actual="+is_actual);
                                $("select[name=piece_service_id]", current_row).val(details[index].piece_service_id);
                                $("select[name=piece_service_id]", current_row).select2();
                                $("input[name=piece_price]", current_row).val(details[index].piece_price);
                                $(".select2-container",current_row).show();
                                current_row = null
                                $(".add-row").each(function () {
                                    $(" .fa-minus-circle", $(this).parents('#main_div')).css({"display": $(".add-row", $(this).parents('#main_div')).length <= 1 ? "none" : "inline-block"})
                                });
                            }); 
                            $('select.common_dis_piece_price,input.common_dis_piece_price,#SubmitAddPiecePrice').attr('disabled',false);
                            $('input[name=piece_quantity]').attr('readonly',false);
                        }
                    }else{
                        $('select.common_dis_piece_price,input.common_dis_piece_price,#SubmitAddPiecePrice').attr('disabled',false)
                        $('input[name=piece_quantity]').attr('readonly',false)
                        $('.row.add-row:gt(0)').remove();
                        $('input.empty').val('');
                        $("input[name=employee_id]").val('');
                        $("input[name=employee_id]").attr("data-select-name", "");
                        $("select[name=piece_service_id]").val('')
                        $("select[name=piece_service_id]").select2()
                        build_select2($("input[name=employee_id]"), "xhr/employeeSearch?is_actual="+is_actual);
                        $('.AddButtons .fa-minus-circle').css({"display":"none"});
                    }
                    $('#Loader').addClass('hidden');
                }
            }
        });
    }
</script>