@extends('adminlte::page') @section('content')
<style>
  td.details-control {
      background: url(' {{ asset('images/details_open.png') }} ') no-repeat center center !important;
      cursor: pointer;
  }
  tr.shown td.details-control {
      background: url(' {{ asset('images/details_close.png') }} ') no-repeat center center !important;
  }
  .jconfirm .jconfirm-box div.jconfirm-content-pane .jconfirm-content div {
    color: rgb(0, 49, 79);
    font-weight: 500;
    padding-left: 5px;
    text-align: left;
}
.text-left{
    text-align: left !important;
}
.form-control:disabled, .form-control[readonly] {
    background-color: transparent !important;
    opacity: 1 !important;
}
.table-inv-head td {
    border: none;
}

.table th {
    vertical-align: middle !important;
}

table tr:nth-child(even), table tr:hover {
    background: none;
}

.table > thead > tr > th {
    border: 1px solid white;
    text-align: center;
}
.btn_disable{
    background-color:rgb(218, 136, 60);
}
</style>
<?php Fun::lang()?>
<div class="title-page">
    <div class="page-bar">
        <ul class="page-breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i> Dashboard</a></li>
            <li><a href="#">Construction</a></li>
            <li><a href="#">Constructor Payment</a></li>
            <li><a href="#">Constructor Payment List</a></li>
        </ul>
    </div>
</div>
    <div class="page">
        <div class="top-content">
            <div class="row">
                <div class="col-sm-12 col-xs-12">
                    <div class="title-page">
                        <div class="pull-left">
                            <h3>Constructor Payment List</h3>
                        </div>
                    </div>
                    <div class="pull-right">
                        <a class="button_sm button_info" href="javascript:void(0)" id="filter-toggle-search"><span class="fa fa-plus"></span>  Filter Toggle</a>
                    </div>
                </div>
            </div>
        </div>
        <div class="box-body table-responsive">
            <div class="row" id="toggle-seaching">
                <div class="col-md-6">
                    <div class="form-group">
                        <strong >Project :</strong>
                        {!! Form::select('project',$projects,null, array('class' => 'form-control select2')) !!}
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <strong >Contractor Name :</strong>
                        {!! Form::text('contractor_name',null, array('class' => 'form-control')) !!}
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <strong >Zone :</strong>
                        {!! Form::select('zone_id',\Globals::get_zone(),null, array('class' => 'form-control select2')) !!}
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <strong >Work Group Type :</strong>
                        {!! Form::select('work_group_type_id',\Globals::get_work_group_type(),null, array('class' => 'form-control select2')) !!}
                    </div>
                </div>
                <div class="col-md-12" style="text-align:right;margin-bottom:40px !important;">
                    <a class="button_sm button_success" href="javascript:void(0)" id="search-submit" onclick="searching()"><span class="fa fa-search"></span> Search</a>
                </div>
            </div>  
            <table id="datatable_constructor_payment" width="100%" class="table">
                <thead>
                    <tr>
                        <th></th>
                        <th>NO</th>
                        <th>Date</th>
                        <th>Start Work Date</th>
                        <th>Duration(Day)</th>
                        <th>DeadLine</th>
                        <th>Project</th>
                        <th>Work Group Type</th>
                        <th>Zone</th>
                        <th>Building Type</th>
                        <th>Contractor</th>
                        <th>Amount</th>
                        <th>Paid Amount</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>

        </div>
    </div>
    @endsection
    @section('js')
        <script>
            function searching(){
                $("#datatable_constructor_payment").DataTable().draw(true);
            }
            function check_request_cash_advance_amount(obj)
            {
                var amount_request = $(obj).val();
                var fee_amount = Number($(obj).closest('tr').find('td:eq(3)').data('fee_amount'));
                var paid_amount = Number($(obj).closest('tr').find('td:eq(4)').data('paid_amount'));
                var balance = fee_amount - paid_amount;
                if(amount_request>balance){
                    $.alert({
                            title: 'Your request is more than balance amount !',
                            type: 'red',
                            useBootstrap: false,
                            boxWidth: '30%',    
                            content:'',
                            theme: 'modern',
                            buttons: {
                                close: {
                                    text: 'close',
                                    btnClass: 'button_warning',
                                    action: function(){
                                            $(obj).val('');
                                    }
                                }
                            }
                        });
                }
            }
            function display_frm_cash_advance(construction_id){
                
                var status = 0;
                var row_select_id = [];
                $("table.tb-list-payment-"+construction_id).find('tbody').find("tr.work-tr").each(function(){
                    status =1;
                    if($(this).find("td:eq(9)").find('input').is(":checked" )==true){
                        row_select_id.push($(this).attr("id"));
                    }
                });
                $.ajax({
                    url:"{{ route('construction.check_payment_cash_advance') }}",
                    type:"POST",
                    dataType:"JSON",
                    data:{
                        "_token":"{{ csrf_token() }}",
                        status:status,
                        construction_id:construction_id,
                        row_select_id:row_select_id
                    },
                    success:function(data)
                    {
                        var tr = ``;
                        $.each(data,function(index,value){
                            tr +=`
                                <tr>
                                    <td>${index+1}<input type='hidden' name='task_id' value='${value.id}'></td>
                                    <td>${value.title}</td>
                                    <td>${value.name}</td>
                                    <td data-fee_amount = '${value.amount}'>${value.amount}$</td>
                                    <td data-paid_amount = '${value.paid_amount}'>${value.paid_amount}$</td>
                                    <td width='200px'><input type='text' class='number-only form-control' placeholder = '$' onkeyup="check_request_cash_advance_amount(this)"></td>
                                </tr>`;
                        });
                        var content = `
                            <div class='table-responsive'>
                                <div class='col-md-4'>
                                    <span style='font-weight:bold;'>Date :</span> <input type='text' value='{{ date('d-m-Y') }}' class='date_picker form-control' placeholder = 'Date' name='date' id='date-request'>
                                    <br/>
                                </div>
                                <div class="form-group col-md-8">
                                    <span>Cash Type:</span>
                                    <select name="cash_type" class="form-control" id="cash-type">
                                        <option value="11001" selected>Cash On Hand</option>
                                        <option value="11002">Cash In Bank</option>
                                    </select>
                                </div>
                                <table width="100%" id='table-cash-request-advance'>
                                    <thead>
                                        <tr>
                                            <th>No</th>
                                            <th>Group Task</th>
                                            <th>Task</th>
                                            <th>Fee Amount</th>
                                            <th>Paid Amount</th>
                                            <th>Request Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        
                                            ${tr}
                                            
                                    </tbody>
                                </table>
                            </div>
                        `;
                        $.alert({
                            title: 'List of Task Request Cash Advance',
                            type: 'green ',
                            useBootstrap: false,
                            boxWidth: '50%',    
                            content:content,
                            theme: 'modern',
                            buttons: {
                                close: {
                                    text: 'close',
                                    btnClass: 'button_warning',
                                },
                                save: {
                                        text: 'submit',
                                        btnClass: 'button_primary btn-print',
                                        action: function(){
                                            var data_task_id = [];
                                            var data_amount = [];
                                            var row = $("#table-cash-request-advance").find("tbody").find('tr');
                                            var error_status = 0;
                                            $(row).each(function(index,value){
                                                if(!$(value).find('td:eq(5)').find('input').val()){
                                                    error_status=1;
                                                    $(value).find('td:eq(5)').find('input').val(0)
                                                }
                                                data_task_id.push($(value).find('td:eq(0)').find('input').val());
                                                data_amount.push($(value).find('td:eq(5)').find('input').val());
                                            });
                                            $("#main-spinner").show();
                                            $.ajax({
                                                url:'{{ route("construction.check_payment_cash_advance_store") }}',
                                                type:"POST",
                                                dataType:"JSON",
                                                data:{
                                                    "_token":"{{ csrf_token() }}",
                                                    data_task_id:data_task_id,
                                                    data_amount:data_amount,
                                                    construction_id:construction_id,
                                                    date:$('#date-request').val(),
                                                    cash_type:$("#cash-type").val(),
                                                },
                                                success:function(data){
                                                    $("#main-spinner").hide();
                                                    $("#datatable_constructor_payment").DataTable().draw(true);
                                                    window.location.reload();
                                                },
                                                complete:function(){
                                                    $("#main-spinner").hide();
                                                    $("#datatable_constructor_payment").DataTable().draw(true);
                                                }
                                            });
                                        }
                                    }
                            }
                        });
                    },
                    complete:function()
                    {

                    }
                });
            }
            $(document).on("change",".check_all",function(){
                let status = $(this).prop('checked');
                var row = $(this).closest('table').find('tbody').find('tr'); 
                $(row).each(function(index,value){
                    var variable_amount = Number($(value).find('td:eq(6)').find('input').val());
                    if(variable_amount>0){
                        $(value).find('td:eq(9)').find("input").prop("checked",status);
                    }
                });
            });
            function check_box_select(obj)
            {
                var row = $(obj).closest('tr');
                var available_amount = Number($(row).find('td:eq(6)').find('input').val());
                if(available_amount>0){

                }
                else{
                    $.alert({
                        title: 'Request is fail',
                        useBootstrap: false,
                        type: 'red',
                        boxWidth: '20%',
                        content:'Amount available less than or equal zero.',
                        theme: 'modern',
                        buttons: {
                            close: {
                                text: 'close',
                                btnClass: 'button_warning',
                                action: function(){
                                    $(obj).prop('checked',false);
                                }
                            }
                        }
                    });
                }
            }
            function format (construction_id) {
                var table_detail="";
                var total_amount = 0;
                var total_amount_paid = 0;
                var total_amount_available = 0;
                var route="{{ route('construction_constructor_payment.get_index_detail') }}";
                $.ajax({
                url:route,
                type:"POST",
                async: false,
                dataType:"JSON",
                data:{
                    "_token":"{{ csrf_token() }}",
                    "construction_id":construction_id
                },
                success:function(data){
                    var tr =`
                            <tr><th colspan="9" style = 'text-align:center;'><u><h5 style='font-size:120%'>Task Detail</h5></u></th></tr>
                            <tr>
                                <th>No</th>
                                <th>Task</th>
                                <th>Group Task</th>
                                <th>Percentage Completed</th>
                                <th>Amount</th>
                                <th>Paid Amount</th>
                                <th>Available Amount</th>
                                <th>Cash Advance Paid</th>
                                <th>Action</th>
                                <th>Check All <input type="checkbox" class="check_all" checked></th>
                            </tr>
                        <tbody>`;
                    $.each(data,function(index,val){
                        total_amount += Number(val.amount);
                        total_amount_paid += Number(val.paid_amount);
                        total_amount_available += Number(Number(val.amount)*Number(val.percentage_completed)/100 - Number(val.paid_amount));
                        var check_status = "";
                        var variable_amount = (Number(val.amount)*Number(val.percentage_completed)/100 - Number(val.paid_amount));
                        if(variable_amount>0){
                            check_status ="checked";
                        }
                        else{
                            check_status = "";
                        }
                        let available_amount = (Number(val.amount)*Number(val.percentage_completed)/100 - Number(val.paid_amount));
                        let button_pay = '';
                        if(available_amount>0){
                            button_pay = `<button type="button" class="btn btn-sm btn-info" title='Make Payment' data-task_id = "${val.id}" onclick="make_each_payment(this)"><i class="fa fa-dollar"></i></button></td>`;
                        }else{
                            button_pay = `<button type="button" class="btn btn-sm button_success btn_disable" title='Make Payment' disabled><i class="fa fa-dollar"></i></button></td>`;
                        }
                        tr += `
                            <tr id="${val.id}" class="work-tr-${val.id} work-tr">
                                <td>${index+1}</td>
                                <td>${val.name}</td>
                                <td>${val.title}</td>
                                <td>${val.percentage_completed	} %</td>
                                <td>$${val.amount}</td>
                                <td>$${val.paid_amount}</td>
                                <td>$${(Number(val.amount)*Number(val.percentage_completed)/100 - Number(val.paid_amount))}
                                    <input type="hidden"​ style="display:none;" value="${(Number(val.amount)*Number(val.percentage_completed)/100 - Number(val.paid_amount))}">
                                </td>
                                <td>$${val.cash_advance_amount}</td>
                                <td>
                                    ${button_pay}
                                <td>
                                    <input type="checkbox"  name="checkbox[]" ${check_status} onchange = "check_box_select(this)">
                                </td>
                            </tr>
                            `;
                    });
                    tr+=`</tbody>
                        <tfoot>
                            <tr>
                                <td colspan='4' style='text-align:right;'>Total</td>
                                <td>$${total_amount}</td>
                                <td>$${total_amount_paid}</td>
                                <td>$${total_amount_available}</td>
                                <td></td>
                                <td colspan='2'></td>
                            </tr>
                        </tfoot>`;
                    table_detail= `<table id="${construction_id}" width="100%" class="table tb-list-payment-${construction_id}">${tr}</table>`;
                }
                });
                return table_detail;
            }
            function make_each_payment(obj){
                let task_id = $(obj).data('task_id');
                let amount = $(obj).closest('tr').find('td:eq(6)').find("input").val();

                var date = "{{ date('d-m-Y') }}";     
                        var content = `
                        <div class='col-md-12'>
                            <form action="" class="formName">
                                <div class='row'>
                                    <div class="form-group col-md-6">
                                        <label>Date:</label><input type="text"  placeholder="Date" value="${date}" class="date-work-each form-control date_picker" required />
                                    </div>
                                    <div class="form-group col-md-6">
                                        <label>Amount($):</label><input type="text" placeholder="$" value="${amount}" class="amount-available-work-each number-only form-control" required readonly />
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="form-group col-md-12">
                                        <label>Extra Amount Type:</label>
                                        <select name="extra_amount_type_each" class="form-control">
                                            <option value="0" selected>N/A</option>
                                            <option value="1">Bonus</option>
                                            <option value="2">Penalty</option>
                                        </select>
                                    </div>
                                    
                                </div>
                                <div class="row bonus-container-each" style="display:none;">
                                    <div class="form-group col-md-6">
                                        <label>Bonus Amount:</label><input type="text"  placeholder="Bonus Amount" class="bonus-amount-each form-control" />
                                    </div>
                                    <div class="form-group col-md-6">
                                        <label>Bonus Description:</label><textarea class='form-control' name="bonus_description" id='bonus_description_each'></textarea>
                                    </div>
                                </div>
                                <div class="row penalty-container-each" style="display:none;">
                                    <div class="form-group col-md-6">
                                        <label>Penalty Amount:</label><input type="text"  placeholder="Penalty Amount" class="penalty-amount-each form-control" />
                                    </div>
                                    <div class="form-group col-md-6">
                                        <label>Penalty Description:</label><textarea class='form-control' name="penalty_description" id='penalty_description_each'></textarea>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="form-group col-md-12">
                                        <label>Cash Type:</label>
                                        <select name="cash_type" class="form-control" id="cash-type-each">
                                            <option value="11001" selected>Cash On Hand</option>
                                            <option value="11002">Cash In Bank</option>
                                        </select>
                                    </div>
                                    
                                </div>
                            </form>
                        </div>
                            `;

                        $.confirm({
                            title:'<H3>Payment</H3>',
                            content:content,
                            theme:'modern',
                            useBootstrap: false,
                            boxWidth: '40%',
                            buttons: {
                                formSubmit: {
                                    text: 'Submit',
                                    btnClass: 'btn-blue',
                                    action: function () {
                                        var date = this.$content.find('.date-work-each').val();
                                        var bonus = this.$content.find('.bonus-amount-each').val();
                                        var penalty = this.$content.find('.penalty-amount-each').val();
                                        var bonus_description = this.$content.find("#bonus_description_each").val();
                                        var penalty_description = this.$content.find("#penalty_description_each").val();
                                        var cash_type = this.$content.find("#cash-type-each").val();
                                        var amount_val = this.$content.find(".amount-available-work-each").val();
                                        if(!date){
                                            $.alert('Please input value');
                                            return false;
                                        }
                                        if(Number(amount_val)<=0){
                                            $.alert("Amount invalid !");
                                            $("#main-spinner").hide();
                                            return flase;
                                        }
                                        $("#main-spinner").show();
                                        $.ajax({
                                            url:"{{route('contractor.contractor_task_payment')}}",
                                            type:"POST",
                                            dataType:"JSON",
                                            data:{
                                                "_token":"{{csrf_token()}}",
                                                amount_available:amount_val,
                                                task_id:task_id,
                                                date : date,
                                                bonus:bonus,
                                                penalty:penalty,
                                                bonus_description:bonus_description,
                                                penalty_description:penalty_description,
                                                cash_type:cash_type
                                            },
                                            success:function(data){
                                               $("#datatable_constructor_payment").DataTable().draw(true);
                                               window.location.reload();
                                            },
                                            complete:function(){
                                                $("#main-spinner").hide();

                                            }
                                        });
                                    }
                                },
                                cancel: function () {
                                },
                            },
                            onContentReady: function () {
                                var jc = this;
                                this.$content.find('form').on('submit', function (e) {
                                    e.preventDefault();
                                    jc.$$formSubmit.trigger('click');
                                });
                            }
                        });

            }
            $(document).on("change","select[name=extra_amount_type_each]",function(){
                let value = $(this).val();
                if(value==1){
                    $(".bonus-container-each").css('display','block');
                    $(".penalty-container-each").css('display','none');
                }else if(value==2){
                    $(".penalty-container-each").css('display','block');
                    $(".bonus-container-each").css('display','none');
                }
                else{
                    $(".bonus-container-each").css('display','none');
                    $(".penalty-container-each").css('display','none');
                }
            });
            $(document).ready(function() {
            
                var table = $('#datatable_constructor_payment').DataTable({
                    ordering: false,
                    "serverSide": true,
                    "lengthMenu": [
                    [20, 25, 50, 100, 500],
                    [20, 25, 50, 100, 500]
                ],
                    ajax: {
                        url:"{{ route('construction_constructor_payment.get_index') }}",
                        type:"GET",
                        data:function(d){
                            d.project_id = $("select[name=project]").val();
                            d.contractor_name = $("input[name=contractor_name]").val();
                            d.zone_id = $("select[name=zone_id]").val();
                            d.work_group_type_id = $("select[name=work_group_type_id]").val();
                        },
                    },
                    columns: [
                        {
                            "className": 'details-control',
                            "orderable": false,
                            "searchable": false,
                            "data": null,
                            "defaultContent": ' ',
                     },
                    {
                        data: 'DT_RowIndex'
                    },{
                        data: 'date'
                    }
                    ,{
                        data: 'start_work_date'
                    }
                    ,{
                        data: 'duration'
                    }
                    ,{
                        data: 'deadline'
                    }
                    ,{
                        data: 'project_name'
                    }
                    ,{
                        data: 'group_work_name'
                    }
                    ,{
                        data: 'block_name'
                    }
                    ,{
                        data: 'type_of_house'
                    }
                    , {
                        data: 'contractor_name'
                    },
                    {
                        data:'total_amount'
                    },
                    {
                        data: 'total_paid_amount'
                    },
                    {
                        data: 'action'
                    }, ],
                    "initComplete": function(settings, json) {
                        $('#main-spinner').hide();
                    }
                });
                $('#datatable_constructor_payment tbody').on('click', 'td.details-control', function () {
                    var tr = $(this).closest('tr');
                    var construction_id = tr.attr("id");
                    var row = table.row( tr );
                    if( row.child.isShown() ) {
                        row.child.hide();
                            tr.removeClass('shown');
                        }
                    else {
                        row.child( format(construction_id) ).show();
                        tr.addClass('shown');
                    }
                });
                $.fn.dataTable.ext.errMode = 'throw';
                
            });
            
            function display_frm_payment(id)
            {
                $("#main-spinner").show();
                var construction_id = id;
                var route = "{{ route('construction.constructor_payment_list_frm') }}";
                var status = 0;
                var row_select_id = [];
                $("table.tb-list-payment-"+id).find('tbody').find("tr.work-tr").each(function(){
                    status =1;
                    if($(this).find("td:eq(9)").find('input').is(":checked" )==true){
                        row_select_id.push($(this).attr("id"));
                    }
                });
                $.ajax({
                    url:route,
                    type:"POST",
                    dataType:"JSON",
                    data:{
                        "_token":"{{ csrf_token() }}",
                        construction_id:construction_id,
                        row_select_id:row_select_id,
                        status:status
                    },
                    success:function(data)
                    {
                        $("#form-payment").modal('show');
                        var d = 0;
                        var id_withdraw=[];
                        var amount_val = [];
                        $.each(data,function(index,val){
                            d += Number(val.amount)*Number(val.percentage_completed)/100 - Number(val.paid_amount);
                            id_withdraw.push(val.id);
                            amount_val.push(Number(val.amount)*Number(val.percentage_completed)/100 - Number(val.paid_amount));
                        });
                        var date = "{{ date('d-m-Y') }}";     
                        var content = `
                        <div class='col-md-12'>
                            <form action="" class="formName">
                                <div class='row'>
                                    <div class="form-group col-md-6">
                                        <label>Date:</label><input type="text"  placeholder="Date" value="${date}" class="date-work form-control date_picker" required />
                                    </div>
                                    <div class="form-group col-md-6">
                                        <label>Amount($):</label><input type="text" placeholder="$" value="${d}" class="amount-available-work number-only form-control" required readonly />
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="form-group col-md-12">
                                        <label>Extra Amount Type:</label>
                                        <select name="extra_amount_type" class="form-control">
                                            <option value="0" selected>N/A</option>
                                            <option value="1">Bonus</option>
                                            <option value="2">Penalty</option>
                                        </select>
                                    </div>
                                    
                                </div>
                                <div class="row bonus-container" style="display:none;">
                                    <div class="form-group col-md-6">
                                        <label>Bonus Amount:</label><input type="text"  placeholder="Bonus Amount" class="bonus-amount form-control" />
                                    </div>
                                    <div class="form-group col-md-6">
                                        <label>Bonus Description:</label><textarea class='form-control' name="bonus_description" id='bonus_description'></textarea>
                                    </div>
                                </div>
                                <div class="row penalty-container" style="display:none;">
                                    <div class="form-group col-md-6">
                                        <label>Penalty Amount:</label><input type="text"  placeholder="Penalty Amount" class="penalty-amount form-control" />
                                    </div>
                                    <div class="form-group col-md-6">
                                        <label>Penalty Description:</label><textarea class='form-control' name="penalty_description" id='penalty_description'></textarea>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="form-group col-md-12">
                                        <label>Cash Type:</label>
                                        <select name="cash_type" class="form-control" id="cash-type">
                                            <option value="11001" selected>Cash On Hand</option>
                                            <option value="11002">Cash In Bank</option>
                                        </select>
                                    </div>
                                    
                                </div>
                            </form>
                        </div>
                            `;

                        $.confirm({
                            title:'<H3>Payment</H3>',
                            content:content,
                            theme:'modern',
                            useBootstrap: false,
                            boxWidth: '40%',
                            buttons: {
                                formSubmit: {
                                    text: 'Submit',
                                    btnClass: 'btn-blue',
                                    action: function () {
                                        var date = this.$content.find('.date-work').val();
                                        var bonus = this.$content.find('.bonus-amount').val();
                                        var penalty = this.$content.find('.penalty-amount').val();
                                        var bonus_description = this.$content.find("#bonus_description").val();
                                        var penalty_description = this.$content.find("#penalty_description").val();
                                        var cash_type = this.$content.find("#cash-type").val();
                                        if(!date){
                                            $.alert('Please input value');
                                            return false;
                                        }
                                        if(Number(amount_val[0])<0){
                                            $.alert("Amount invalid !");
                                            $("#main-spinner").hide();
                                            return false;
                                        }
                                        $("#main-spinner").show();
                                        $.ajax({
                                            url:"{{route('construction.constructor_payment_list_frm_store')}}",
                                            type:"POST",
                                            dataType:"JSON",
                                            data:{
                                                "_token":"{{csrf_token()}}",
                                                amount_available:amount_val,
                                                id_withdraw_val:id_withdraw,
                                                date : date,
                                                bonus:bonus,
                                                penalty:penalty,
                                                bonus_description:bonus_description,
                                                penalty_description:penalty_description,
                                                cash_type:cash_type
                                            },
                                            success:function(data){
                                               $("#datatable_constructor_payment").DataTable().draw(true);
                                               window.location.reload();
                                            },
                                            complete:function(){
                                                $("#main-spinner").hide();

                                            }
                                        });
                                    }
                                },
                                cancel: function () {
                                },
                            },
                            onContentReady: function () {
                                var jc = this;
                                this.$content.find('form').on('submit', function (e) {
                                    e.preventDefault();
                                    jc.$$formSubmit.trigger('click');
                                });
                            }
                        });
                    },
                    complete:function()
                    {
                        $("#main-spinner").hide();
                    }
                });
                
            }
            $(document).on("change","select[name=extra_amount_type]",function(){
                let value = $(this).val();
                if(value==1){
                    $(".bonus-container").css('display','block');
                    $(".penalty-container").css('display','none');
                }else if(value==2){
                    $(".penalty-container").css('display','block');
                    $(".bonus-container").css('display','none');
                }
                else{
                    $(".bonus-container").css('display','none');
                    $(".penalty-container").css('display','none');
                }
            });
            $(document).on("focus",".date_picker",function(){
                $(this).datepicker({
                    dateFormat: 'dd-mm-yy',
                    changeMonth: true
                });
            });
            function show_upload(obj){
                var task_id = $(obj).data('task_id');
                var date = "{{ date('d-m-Y') }}";
                var content = `
                        <div class='col-md-6'>
                            <div class="row">
                                <form class="form-horizontal" role="form" action="{{route('save_upload_task_document')}}" method="post" enctype="multipart/form-data" id="form-save-task-document">
                                    @csrf
                                    <div class="row">
                                        <div class="col-sm-12" style="text-align: center;padding: 20px;margin-left: 100px;">
                                            <label class='required'>Date</label>
                                            <input type="text" id="date-input" name="date" class='form-control date_picker' value="${date}" required>
                                        </div>
                                        <div class="col-sm-12" style="text-align: center;padding: 20px;margin-left: 100px;">
                                            <input type="hidden" id="task-id-input" name="task_id" value="${task_id}">
                                            <input type="file" id="file-upload-input" name="file_name[]" multiple>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        `;
                $.alert({
                    title: 'Upload Document',
                    type: 'warning ',
                    useBootstrap: false,
                    boxWidth: '40%',
                    content:content,
                    theme: 'modern',
                    buttons: {
                        close: {
                            text: 'close',
                            btnClass: 'button_warning',
                        },
                        submit: {
                            text: 'submit',
                            btnClass: 'button_success',
                            action:function()
                            {
                                $("#form-save-task-document").submit();
                            }
                        }
                    }
                });
            }
            function show_document(obj)
            {
                var task_id = $(obj).data('task_id');
                var route = "{{route('show_upload_document',':id')}}";
                route = route.replace(":id",task_id);
                $("#main-spinner").show();
                $.ajax({
                    url:route,
                    type:"GET",
                    dataType:"JSON",
                    success:function (data) {
                        $("#main-spinner").hide();
                        var tr = '';
                        $.each(data,function (index,val) {
                            var local= "/assets/document/"+val.file_name;
                            tr += `<tr>
                                    <td>${index+1}</td>
                                    <td>${val.date.split('-')[2]+'-'+val.date.split('-')[1]+'-'+val.date.split('-')[0]}</td>
                                    <td>${val.file_name}</td>
                                    <td>
                                        <a style="color:white;margin-left:0;" href="${local}" download class="button_info btn-circle" title="Download">
                                            <i class="glyphicon glyphicon-save"></i>
                                        </a>
                                    </td>
                                </tr>`;
                        });
                        var content = `
                            <div class='table-responsive'>
                                <table width="100%">
                                    <thead>
                                        <tr>
                                            <th>No</th>
                                            <th>Date</th>
                                            <th>File Name</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${tr}
                                    </tbody>
                                </table>
                            </div>
                            `;
                        $.alert({
                            title: 'Download Document',
                            type: 'warning ',
                            useBootstrap: false,
                            boxWidth: '40%',
                            content:content,
                            theme: 'modern',
                            buttons: {
                                close: {
                                    text: 'close',
                                    btnClass: 'button_warning'
                                }
                            }
                        });
                    },
                    error:function () {

                    }
                });
            }
            function display_history_payment(construction_id)
            {
                $("#main-spinner").show();
                var route = "{{ route('construction.constructor_payment_list_history_index',':id') }}";
                route = route.replace(":id",construction_id);
                $.ajax({
                    url:route,
                    type:"GET",
                    dataType:"JSON",
                    success:function(data)
                    {
                        var tr = ``;
                        var button = ``;
                        $.each(data['data'],function(index,value){
                            var button = ``;
                            button +='<a href="javascript:void(0)" data-created_at ="'+value.created_at+'" data-construction_id ="'+value.construction_id+'" onclick="get_for_print(this)" class="btn btn-sm btn-primary"><span class="fa fa-print"></span></a>';

                            button +='<a style="color:white;margin-left:5px;" data-task_id = "'+value.task_id+'" href="javascript:void(0)" class="btn btn-sm btn-success btn-circle" onclick="show_upload(this)" title="Upload Document"><i class="glyphicon glyphicon-open"></i></a>';

                            button +='<a style="color:white;margin-left:5px;" data-task_id = "'+value.task_id+'" href="javascript:void(0)" class="btn btn-sm btn-info btn-circle" onclick="show_document(this)" title="Download Document"> <i class="glyphicon glyphicon-save"></i></a>';

                            tr +=`  <tr>
                                        <td>${index+1}</td>
                                        <td>${value.date.split('-')[2]+"-"+value.date.split('-')[1]+"-"+value.date.split('-')[0]}</td>
                                        <td>
                                            ${(value.banus_amount>0?("- "+"Banus Amount : $"+value.banus_amount+" ( "+value.bonus_note+" )"):"")}
                                            ${(value.penalty_amount>0?("- "+"Penalty Amount : $"+value.penalty_amount+" ( "+value.penalty_note+" )"):"")}
                                        </td>
                                        <td>${button}</td>
                                    </tr>`;
                        });
                        var content = `
                        <div class="table container-fluid">
                            <div class="row">
                                <div class="col-sm-3">ឈ្មោះគម្រោង :</div>
                                <div class="col-sm-3 text-left">${data['data_construction'].project_name}</div>
                                <div class="col-sm-3">ថ្ងៃបញ្ចប់ការងារ :</div>
                                <div class="col-sm-3 text-left">${data['data_construction'].contractor_name}</div>
                            </div>
                            <div class="row">
                                <div class="col-sm-3">អ្នកម៉ៅការ :</div>
                                <div class="col-sm-3 text-left">${data['data_construction'].contractor_name==null?'N/A':data['data_construction'].contractor_name}</div>
                                <div class="col-sm-3">តំបន់ :</div>
                                <div class="col-sm-3 text-left">${data['data_construction'].block_name==null?'N/A':data['data_construction'].block_name}</div>
                            </div>
                            <div class="row">
                                <div class="col-sm-3">ប្រភេទអគារ :</div>
                                <div class="col-sm-3 text-left">${data['data_construction'].type_of_house==null?'N/A':data['data_construction'].type_of_house}</div>
                                <div class="col-sm-3">ប្រភេទការងារ :</div>
                                <div class="col-sm-3 text-left">${data['data_construction'].group_work_name==null?'N/A':data['data_construction'].group_work_name}</div>
                            </div>
                        </div>
                        <div class='table-responsive'>
                            <table width="100%">
                                <thead>
                                    <tr>
                                        <th>No</th>
                                        <th>Date</th>
                                        <th>Description</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${tr}
                                </tbody>
                            </table>
                        </div>
                        `;
                        $.alert({
                            title: 'Payment History List',
                            type: 'green ',
                            useBootstrap: false,
                            boxWidth: '40%',
                            content:content,
                            theme: 'modern',
                            buttons: {
                                close: {
                                    text: 'close',
                                    btnClass: 'button_warning',
                                }
                            }
                        });
                    },
                    complete:function()
                    {
                        $("#main-spinner").hide();
                    }
                });
            }
            function get_for_print(obj)
            {
                var tr = ``;

                $.ajax({
                    url:"{{ route('construction.constructor_payment_list_history_get_detail') }}",
                    type:"POST",
                    dataType:"JSON",
                    async:false,
                    data:{
                        "_token":"{{ csrf_token()}}",
                        construction_id:$(obj).data('construction_id'),
                        created_at:$(obj).data('created_at')
                    },
                    success:function(data)
                    {
                        var total_amount = 0;
                        var total_balance_amount = 0;
                        var total_get_amount = 0;
                        var bonus = data['penalty_banus'].banus_amount;
                        var penalty = data['penalty_banus'].penalty_amount;
                        $.each(data['detail'],function(index,value){
                            total_amount+=value.amount;
                            total_balance_amount+=value.amount - value.get_amount;
                            total_get_amount+=value.get_amount;
                            tr+=`
                                <tr>
                                    <td>${index+1}</td>
                                    <td>${value.name} </td>
                                    <td>${value.amount.toFixed(2)} $</td>
                                    <td>${value.get_amount.toFixed(2)} $</td>
                                    <td>${(value.amount - value.get_amount).toFixed(2)} $</td>
                                    <td colspan='4'></td>
                                </tr>`;
                        });
                        tr+=`<tr>
                                <td colspan='2' style="text-align:right;">Total</td>
                                <td>${total_amount.toFixed(2)} $</td>
                                <td>${total_get_amount.toFixed(2)} $</td>
                                <td>${total_balance_amount.toFixed(2)} $</td>
                                <td colspan='4'></td>
                            </tr>
                            <tr>
                                <td colspan='2' style="text-align:right;">Grand Total</td>
                                <td colspan='4'>${(total_get_amount + (bonus==null?0:bonus) - (penalty==null?0:penalty)).toFixed(2)} $</td>
                            </tr>
                            `;
                            var content = `
                                <div class="form-box">
                                    <br/>
                                    <center><h2>វិក័យបត្រដកប្រាក់ការងារ</h2></center>
                                    <br/>
                                    <div class="table container-fluid">
                                        <div class="row">
                                            <div class="col-sm-2">ឈ្មោះគម្រោង:</div>
                                            <div class="col-sm-3 text-left">${data['main'].project_name}</div>
                                            <div class="col-sm-2">ថ្ងៃបញ្ចប់ការងារ:</div>
                                            <div class="col-sm-3 text-left">${data['deadline_date']}</div>
                                        </div>
                                        <div class="row">
                                            <div class="col-sm-2">អ្នកម៉ៅការ:</div>
                                            <div class="col-sm-3 text-left">${data['main'].constructor_name}</div>
                                            <div class="col-sm-2">ប្រាក់បន្ថែម:</div>
                                            <div class="col-sm-3 text-left">${bonus==null?"0":bonus} $</div>
                                        </div>
                                        <div class="row">
                                            <div class="col-sm-2">ទូរស័ព្ទលេខ:</div>
                                            <div class="col-sm-3 text-left">${data['main'].constructor_phone}</div>
                                            <div class="col-sm-2">ប្រាក់ពិន័យ:</div>
                                            <div class="col-sm-3 text-left">${penalty==null?"0":penalty} $</div>
                                        </div>
                                        <div class="row">
                                            <div class="col-sm-2">តំបន់:</div>
                                            <div class="col-sm-3 text-left">${data['main'].zone_name!=null?data['main'].zone_name:""}</div>
                                            <div class="col-sm-2"></div>
                                            <div class="col-sm-3 text-left"></div>
                                        </div>
                                    </div>
                                    <table style="margin-top: 30px" class="table">
                                        <thead>
                                            <tr>
                                                <th>លរ</th>
                                                <th>ប្រភេទការងារ</th>
                                                <th>ទឹកប្រាក់នៃការងារ</th>
                                                <th>ចំនួនទឹកប្រាក់</th>
                                                <th>ទឹកប្រាក់នៅសល់</th>
                                                <th colspan="4"​>ផ្សេងៗ</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            ${tr}
                                        </tbody>
                                    </table>
                                </div>
                                <form action="{{ route('construction.constructor_payment_list_history_print') }}" target="_blank" class="form-submit-print" method="POST">
                                    @csrf
                                    <input type='hidden' name="construction_id" value="${$(obj).data('construction_id')}">
                                    <input type="hidden" name="created_at" value="${$(obj).data('created_at')}">
                                </form>
                            `;
                            $.alert({
                                title: '',
                                useBootstrap: false,
                                boxWidth: '50%',
                                content:content,
                                theme: 'modern',
                                buttons: {
                                    close: {
                                        text: 'close',
                                        btnClass: 'button_warning',
                                    },
                                    
                                    print: {
                                        text: 'Print',
                                        btnClass: 'button_primary btn-print',
                                        keys: ['ctr', 'p'],
                                        action: function(){
                                            $('.form-submit-print').submit();
                                        }
                                    }
                                }
                            });
                    }
                });
            }
            
        </script>
    @endsection