<?php Fun::lang() ?>
@extends('layouts.app-accounting')
@section('content')

<div class="page">
    <div class="top-content">
        <div class="row">
            <div class="col-sm-12 col-xs-12">
                <div class="title-add">
                    <div class="pull-left">
                        <h3>{{__('administrator.journal_list')}}</h3>
                    </div>
                    <div class="pull-right">
                    {{--@can('Accounting-Journal-Create')--}}
                        <a href="{{route('journal.create')}}" class="btn btn-info fa fa-plus">{{__('administrator.add_new')}}</a>
                    {{--@endcan--}}
                    </div>
                </div>
            </div>
            <div class="col-sm-12 block-action">
                <p class="pull-right btn-action btn btn-xs btn-info" data-toggle="tooltip" data-placement="top" title="Hide/Show"><i class="fa fa-caret-down" aria-hidden="true"></i></p>
                {{--@can('Accounting-Journal-Print-Voucher')--}}
                {!! Form::open(array('route' => 'voucher.print','method'=>'POST','id'=>'print-voucher')) !!}
                <input type="hidden" name="voucher" id="voucher">
                <button type="submit" class="pull-right btn btn-xs btn-warning" data-toggle="tooltip" data-placement="top" title="Print Voucher"><i class="fa fa-print" aria-hidden="true"></i></button>
                {!! Form::close() !!}
                {{--@endcan--}}
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12" id="block-action" style="display:none">
                <div class="content-action">
                    {!! Form::open(['class'=>'form_search']) !!}
                    <div class="form-group  col-sm-2 col-xs-2">
                        <label>Reference Number</label>
                        {!! Form::text('reference_no', null, array('placeholder' => 'Reference Number','class' => 'form-control ref_no')) !!}
                    </div>
                    {{--<div class="form-group  col-sm-3 col-xs-3">--}}
                    {{--<label>Select Project</label>--}}
                    {{--{!! Form::select('journal_by_project', $projects, null, ['class' => 'form-control select2','id'=>'project_id']) !!}--}}
                    {{--</div>--}}

                    <div class="form-group col-sm-2 col-xs-2" id="available-box">
                        <label>Start Date</label>
                        {!! Form::text('start_date', null, array('placeholder' => 'Start Date','class' => 'form-control date_picker start_date','autocomplete' => 'off')) !!}
                    </div>
                    <div class="form-group col-sm-2 col-xs-2" id="available-box">
                        <label>End Date</label>
                        {!! Form::text('end_date', null, array('placeholder' => 'End Date','class' => 'form-control date_picker end_date','autocomplete' => 'off')) !!}
                    </div>
                    {!! Form::close() !!}
                    <div class="col-sm-12" style="text-align: right">
                        <button type="button" class="button_lg button_primary fa fa-search btn_search" > Search</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-12 col-xs-12">
            <div class="form-wrapper">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="table-responsive">
                            <table id="table_journal" class="table table-bordered table-striped table-condensed table-hover">
                                <thead>
                                    <tr>
                                        <th><label for="checkall">
                                                <input type="checkbox" id="checkall">
                                            </label>
                                        </th>
                                        <th>No</th>
                                        <th >{{__('administrator.journal')}}</th>
                                        <th >{{__('administrator.user_name')}}</th>
                                        {{--<th >Project Name</th>--}}
                                        <th>{{__('administrator.reference_number')}}</th>
                                        <th>{{__('administrator.voucher_type')}}</th>
                                        <th>{{__('administrator.voucher_number')}}</th>
                                        <th>{{__('administrator.account_type')}}</th>
                                        <th>{{__('administrator.invoice_number')}}</th>
                                        <th>{{__('administrator.description')}}</th>
                                        <th>{{__('administrator.debit')}}</th>
                                        <th>{{__('administrator.credit')}}</th>
                                        <th >{{__('administrator.action')}}</th>
                                    </tr>
                                </thead>
                                <tbody id="tbody"></tbody>
                                <tfoot id="tfoot">
                                    <tr>
                                        <td colspan="10" class="text-right bold-green">Total </td>
                                        <td class="bold-orange total_debit"></td>
                                        <td class="bold-orange total_credit"></td>
                                        <td></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade bs-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dm">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
                <h3 class="modal-title text-danger">Warning...!</h3>
            </div>
            <br />
            <div class="row">
                <div class="col-md-12">
                    <div class="col-md-10">
                        <h4>Receivable amount must be smaller than or equal available amount.</h4>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" data-dismiss="modal" class="button_primary"><i class="fa fa-close"></i> Close</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
@include('Accounting.journal.confirm-delete')
@endsection

@section('script')
<script type="text/javascript">

    $(document).ready(function () {
        getTable();
        $('#journal-del').on('click',function (e) {
            e.preventDefault();
            var id = $('#delete-id').val();
            $.ajax({
                url:"{{route('journal_confirm_delete')}}",
                type:"POST",
                dataType:"JSON",
                data:{
                    "_token": "{{ csrf_token() }}",
                    "delete_id" : id
                },
                success:function (data) {
                    $('#form-delete').modal('hide');
                    $('#table_journal').DataTable().ajax.reload();
                    $('.p-message').html(data.message);
                    $('#jn-div').show();
                },
                error:function (err) {
                    console.log(err);
                }
            });
        });
        $('.btn_search').on('click',function (e) {
            getTable();
        });
    });

    var ArrId = [];
    $(document).on('change', '#checkall', function() {
        ArrId = [];
        if ($(this).is(':checked')) {
            $('button[type="submit"]').removeAttr('disabled');
            $('.checkbox').each(function() {
                $(this).prop('checked', true);
                var id = $(this).attr('id');
                ArrId.push(id);
            });
        } else {
            $('.checkbox').each(function() {
                $(this).prop('checked', false);
                ArrId = [];
            });
        }
        push_data(ArrId);
    });
    $(document).on('change', '.checkbox', function() {
        var id = $(this).attr('id');
        if ($(this).is(':checked')) {
            $('input[type="submit"]').removeAttr('disabled');
            ArrId.push(id);
        }
        else {
            var index = ArrId.indexOf(id);
            if (index > -1) {
                ArrId.splice(index, 1);
            }
        }
        push_data(ArrId);
    });
    $(document).on('click', '.btn-action', function() {
        $('#block-action').toggle("fast");
    });


    $("form").submit(function(e) {
        if (ArrId === undefined || ArrId.length == 0) {
            $.alert({
                title: 'Error',
                icon: 'fa fa-warning',
                type: 'orange',
                content: 'No fields Selected' +
                    '<hr>' +
                    'Please Select Any Fields',
            });
            return false;
        }
    });

    function push_data(obj) {
        $('#voucher').val(obj);
    }

    function push_array(obj) {
        obj = [];
        $('.checkbox').each(function() {
            var id = $(this).attr('id');
            obj.push(id);
        });
        return obj;
    }

    function search_journal() {

        var ref = $('.ref_no').val();
        var project = $('#project_id').val();
        var supplier = $('#supplier_id').val();
        var end_date = $('.end_date').val();
        var start_date = $('.start_date').val();
        var tr="";
        var total_debit = 0;
        var total_credit = 0;
        var btn_edit = '';
        var btn_delete = '';
        var check_edit = "<?php echo Gate::check('Accounting-Journal-Edit'); ?>";
        var check_delete = "<?php echo Gate::check('Accounting-Journal-Delete'); ?>";
            $.ajax({
                url: "{{ route('datatable.get-journal')}}",
                method: "POST",
                dataType: "json",
                data: {
                    ref: ref,
                    start_date: start_date,
                    end_date: end_date,
                    project: project,
                    supplier: supplier,
                    _token: '{{ csrf_token() }}',
                },
                success: function(data) {
                    $('#tbody').empty();
                    $('#tfoot').empty();
                    if(data == "")
                    {
                        tr+=`<tr align="center"><td colspan="11">No Data</td></tr>`;
                    }
                    else
                    {
                        $.each(data,function(index,val){
                            var route_edit = "{{route('journal.edit',':id')}}";
                            route_edit.replace(':id',val.id);
                            total_credit+=val.journal_credit;
                            total_debit+=val.journal_debit;
                            var checkbox = `<label><input id="${val.id}" class="checkbox" type="checkbox"></label>`;
                            if(val.journal_status != 1)
                            {
                                if(check_edit == 1)
                                {
                                    btn_edit= `<a href="${route_edit}" class="btn btn-sm btn-success" style="margin-right: 5px"><i class="fa fa-edit"></i></a>`;
                                }
                                if(check_delete == 1)
                                {
                                    btn_delete = `<a href="#" data-id="${val.id}" data-toggle="modal" data-target="#form-delete" class="btn btn-sm btn-danger confirm_delete"><i class="fa fa-trash"></i></a>`;
                                }
                            }
                            var pro_id='';
                            var supplier_id='';
                            var ref_num='';
                            var tran_ids='';

                            if (val.project_name!='' && val.project_name!=null){
                                pro_id=val.project_name;
                            }
                            if (val.supplier_name!='' && val.supplier_name!=null){
                                supplier_id=val.supplier_name;
                            }
                            if (val.journal_reference_number!='' && val.journal_reference_number!=null ){
                                ref_num=val.journal_reference_number;
                            }
                            if (val.tran_id !='' && val.tran_id !=null ){
                                tran_ids=val.tran_id;
                            }
                            tr +=    `<tr>
                                        <td>${checkbox}</td>
                                        <td>${(tran_ids)}</td>
                                        <td>${val.journal_paydate}</td>
                                        <td>${val.user_name}</td>
                                        <td>${pro_id}</td>
                                        <td>${supplier_id}</td>
                                        <td>${ref_num}</td>
                                        <td>${val.voucher_type != null ? val.voucher_type : ""}</td>
                                        <td>${val.voucher_ref !=null ? val.voucher_ref : ""}</td>
                                        <td>${val.acc_name}</td>
                                        <td>${val.journal_invoice}</td>
                                        <td>${val.journal_des}</td>
                                        <td>${val.journal_debit}</td>
                                        <td>${val.journal_credit}</td>
                                        <td>${btn_edit} ${btn_delete}</td>
                                    </tr>`;
                        });
                    }
                    var footer =    `<tr>
                                        <td colspan="11" class="text-right bold-green">Total </td>
                                        <td class="bold-orange">$${parseFloat(total_debit).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')}</td>
                                        <td class="bold-orange">$${parseFloat(total_credit).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')}</td>
                                        <td></td>
                                    </tr>`;
                    $('#tfoot').append(footer);
                    $('#tbody').append(tr);
                }
            });
    }
    $(document).on('click','.confirm_delete',function () {
        var id = $(this).data('id');
        $('#delete-id').val(id);
        $('#form-delete').modal('show');
    });
    function getTable(){
        let form = $('.form_search').serialize();
        $('#table_journal').DataTable().destroy();
        $('#table_journal').DataTable({
            "aaSorting": [],
            "pagingType": "full_numbers",
            "serverSide":true,
            "lengthMenu": [
                [20, 50, 100, 250, 500],
                [20, 50, 100, 250, 500]
            ],
            ajax: "/get-journal?"+ form,
            columns: [
                {
                    data: 'checkbox'
                },
                {
                    data: 'id'
                },
                {
                    data: 'journal_paydate'
                },
                {
                    data: 'name'
                },

                {
                    data: 'journal_reference_number'
                },
                {
                    data: 'voucher'
                },
                {
                    data: 'voucher_ref'
                },
                {
                    data: 'account_code'
                },
                {
                    data: 'journal_invoice'
                },
                {
                    data: 'journal_des'
                },
                {
                    data: 'journal_debit'
                },
                {
                    data: 'journal_credit'
                },
                {  data: 'action'}
            ],
            "initComplete": function(settings, json) {
            },
            "fnDrawCallback": function ( row, data, start, end, display ) {
                let tr = $('#tbody tr');
                let total_debit_usd = 0;
                let total_debit_baht = 0;
                let total_credit_usd = 0;
                let total_credit_baht = 0;
                $.each(tr,function (ii,vv) {
                    let amount_debit = $(this).find('td:nth-child(12) span').data('amount');
                    let amount_credit = $(this).find('td:nth-child(13) span').data('amount');
                    let cur_id = $(this).find('td:nth-child(12) span').data('curr');
                    amount_debit = amount_debit?parseFloat(amount_debit):0;
                    amount_credit = amount_credit?parseFloat(amount_credit):0;
                    if(cur_id===2){
                        total_debit_usd+=amount_debit;
                        total_credit_usd+=amount_credit;
                    }

                    if(cur_id===3){
                        total_debit_baht+=amount_debit;
                        total_credit_baht+=amount_credit;
                    }
                });
                tdu = total_debit_usd?('$'+total_debit_usd.toFixed(2)):'';
                tdb = total_debit_baht?('฿'+total_debit_baht.toFixed(2)):'';
                tcu = total_credit_usd?('$'+total_credit_usd.toFixed(2)):'';
                tcb = total_credit_baht?('฿'+total_credit_baht.toFixed(2)):'';
                $('#tfoot tr:first-child ').find('.total_debit').html((tdu?(tdu+'<br>'):'')+tdb);
                $('#tfoot tr:first-child ').find('.total_credit').html((tcu?(tcu+'<br>'):'')+tcb);
            },
        });
    }


</script>
@endsection
