@extends('layouts.app')

@section('title')
    General Journal Entries
@stop

@section('breadcrumb')
    <ol class="breadcrumb pull-right">
        <li><a href="{{ route('home') }}"><i class="fa fa-dashboard"></i> Home</a></li>

        <li class="active">General Journal Entries</li>
    </ol>
@stop

@section('css')



    <link href="{{ asset('plugins/components/bootstrap-daterangepicker/daterangepicker.css') }}" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

    <style>
        .float {
            position: fixed;
            width: 160px;
            height: 40px;
            bottom: 40px;
            right: 40px;
            background-color: #003f5c;
            ;
            color: #FFF;
            border-radius: 50px;
            text-align: center;
            box-shadow: 2px 2px 3px #999;
            z-index: 999;
        }

        .my-float {
            margin-top: 22px;
        }

        .float:hover {
            color: #FFF;
            opacity: .8;
        }
    </style>
@endsection

@section('content')


    <div class="container-fluid">


        @can('isSuperAdmin')
            @include('partial.multiproject_select')
        @endcan
        @permission('create-voucher')
            <a onclick="$('#voucher-form').submit()" href="#" class="float">
                <span style='line-height: 36px;'><i class="fa fa-money "></i> Make Voucher</span>
                {{-- <i class="fa fa-plus my-float"></i> --}}
            </a>
        @endpermission



        <form id="voucher-form" method="post" action="{{ route('create-voucher') }}">
            {{ csrf_field() }}
            <input type="hidden" name="type" value="">
            <input type="hidden" name="id" value="">


        </form>


        <div id='updatecontent'>
            <div class="row" style="margin-top:25px;">

                <div class="col-md-12">
                    <div class="panel panel-info">
                        <div class="panel-heading">Customize Entries</div>
                        <div class="panel-wrapper collapse in" aria-expanded="true">
                            <div class="panel-body">
                                <form>
                                    <div class="form-body">
                                        <div class="row">

                                            <div class="col-md-4">

                                                <input type='hidden' name='multipro_id' value='all'
                                                    id='multipro_id_input'>

                                                <div class="form-group">
                                                    <label class="col-sm-4 control-label">By Account</label>
                                                    <div class="col-sm-8">
                                                        <div class="input-group">
                                                            <div class="input-group-addon">

                                                            </div>
                                                            <select class="form-control chosen-select" id="c_account">
                                                                <option value="0">None</option>
                                                                @foreach ($accounts as $ac)
                                                                    <option value="{{ $ac->id }}">{{ $ac->number }}
                                                                        -
                                                                        {{ $ac->name }}</option>
                                                                @endforeach
                                                            </select>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>



                                            <div class="col-md-4">



                                                <div class="form-group">
                                                    <label class="col-sm-4 control-label">Date range</label>
                                                    <div class="col-sm-8">
                                                        <div class="input-group" id="date-div">
                                                            <div class="input-group-addon">
                                                                <i class="fa fa-calendar"></i>
                                                            </div>
                                                            <input type="text" class="form-control pull-right"
                                                                id="daterange-btn" name='date_range'>

                                                        </div>
                                                        @if ($errors->has('date_range'))
                                                            <span class="help-block">
                                                                <strong>{{ $errors->first('date_range') }}</strong>
                                                            </span>
                                                        @endif
                                                    </div>
                                                    <!-- /.input group -->
                                                </div>
                                            </div>

                                            <div class="form-actions pull-right" style="margin-right: 30PX;">
                                                <button type="button" class="btn btn-success update-record"> <i
                                                        class="fa fa-check"></i> Update</button>
                                            </div>
                                        </div>

                                    </div>



                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!--./row-->


            <div class="pull-right">


                <form class="form-inline" method="get" onsubmit="return getSearcableResult(this)"
                    style="position: relative;top: 7rem;right: 2.2rem;z-index: 999;">
                    <div class="form-group mb-2">
                        <input type="search" name="search_voucher" id="search_voucher" class="form-control"
                            placeholder="Search by type & amount">
                    </div>

                    <button type="submit" class="btn btn-success mb-2">Search</button>
                </form>


            </div>

            <!-- /row -->
            <div class="row" id="update-table">

                <div class="col-sm-12">
                    <div class="white-box">

                        <h3 class="box-title">List of General Journal Entries</h3>

                        <div class="table-responsive">

                            <table id="myTable" class="table table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th>Type</th>
                                        <th>Checked</th>
                                        <th>Posted</th>
                                        <th>Date</th>
                                        <th>Entry No.</th>
                                        <th>Cheque No.</th>
                                        <th>Receipt No.</th>
                                        <th>Account</th>
                                        <!-- <th>Narration</th> -->
                                        <!-- <th>Class</th> -->
                                        <th>Debit/Credit (+/-)</th>
                                        <th>Action</th>

                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($allEntries as $entry)
                                        <tr ondblclick="showEntry('{{ $entry->entry_no }}')">

                                            @if ($entry->voucher_type == \App\GeneralJournalEntry::CRV)
                                                <td>CRV-{{ $entry->voucher_no }}</td>
                                            @elseif($entry->voucher_type == \App\GeneralJournalEntry::BRV)
                                                <td>BRV-{{ $entry->voucher_no }}</td>
                                            @elseif($entry->voucher_type == \App\GeneralJournalEntry::CPV)
                                                <td>CPV-{{ $entry->voucher_no }}</td>
                                            @elseif($entry->voucher_type == \App\GeneralJournalEntry::BPV)
                                                <td>BPV-{{ $entry->voucher_no }}</td>
                                            @elseif($entry->voucher_type == \App\GeneralJournalEntry::JV)
                                                <td>JV-{{ $entry->voucher_no }}</td>
                                            @else
                                                <td></td>
                                            @endif

                                            <td>
                                                @if ($entry->is_check)
                                                    <i class="fa fa-check" style="color:green"></i>
                                                @else
                                                    <i class="fa fa-close" style="color: red;"></i>
                                                @endif

                                            <td>
                                                @if ($entry->is_post)
                                                    <i class="fa fa-check" style="color:green"></i>
                                                @else
                                                    <i class="fa fa-close" style="color: red;"></i>
                                                @endif
                                            </td>

                                            <td>{{ date('d/m/Y', strtotime($entry->date)) }}</td>
                                            <td class="text-right">{{ $entry->entry_no }}</td>
                                            <td>
                                                {{ $entry->cheaque_no ? $entry->cheaque_no : '' }}
                                            </td>

                                            <td>
                                                @if ($entry->dealer_package_voucher == 1)
                                                    @if ($entry->dealerReceipt)
                                                        <a
                                                            href="{{ route('openfile.package.detailReceipt', [$entry->dealerReceipt->id]) }}">
                                                            {{ $entry->dealerReceipt->receipt_no }}
                                                        </a>
                                                    @endif
                                                @elseif($entry->customer_refund_unit == 1)
                                                    @if ($entry->customerUnitRefundReceipt)
                                                        <a
                                                            href="{{ route('receipt.refund-openfile.detail', [$entry->customerUnitRefundReceipt->id]) }}">
                                                            {{ $entry->customerUnitRefundReceipt->receipt_no }}
                                                        </a>
                                                    @endif
                                                @elseif($entry->dealer_refund_openfile == 1)
                                                    @if ($entry->dealerOpenFileRefundReceipt)
                                                        <a
                                                            href="{{ route('receipt.refund.detail', [$entry->dealerOpenFileRefundReceipt->id]) }}">
                                                            {{ $entry->dealerOpenFileRefundReceipt->receipt_no }}
                                                        </a>
                                                    @endif
                                                @elseif($entry->cancel_close_unit == 1)
                                                    @if ($entry->CustomerCancelUnitReceipt)
                                                        <a
                                                            href="{{ route('receipt.cancel-closeunit.detail', [$entry->CustomerCancelUnitReceipt->id]) }}">
                                                            {{ $entry->CustomerCancelUnitReceipt->receipt_no }}
                                                        </a>
                                                    @endif
                                                    @elseif($entry->cancel_open_unit == 1)
                                                    @if ($entry->DealerOpenFileCancelReceipt)
                                                        <a
                                                            href="{{ route('receipt.cancel-openunit.detail', [$entry->DealerOpenFileCancelReceipt->id]) }}">
                                                            {{ $entry->DealerOpenFileCancelReceipt->receipt_no }}
                                                        </a>
                                                    @endif
                                                @else
                                                    @if ($entry->receipt)
                                                        <a href="{{ route('receipt.detail', [$entry->receipt->id]) }}">
                                                            {{ $entry->receipt->receipt_no }}
                                                        </a>
                                                    @endif
                                                @endif
                                            </td>

                                            <td>{{ $entry->account ? $entry->account->name : '' }}</td>
                                            <!-- <td>{{ $entry->voucher ? $entry->voucher->narration : '' }}</td> -->
                                            <!-- <td>{{ $entry->class ? $entry->class->name : '' }}</td> -->
                                            <td class="text-right">{{ number_format($totalAmount[$entry->entry_no]) }}
                                            </td>
                                            <td>
                                                <!-- <span onclick="showEntry('{{ $entry->entry_no }}')" style="cursor: pointer;" class="btn btn-sm btn-primary"> Show</span> -->

                                                @permission('view-voucher')
                                                    <a href="{{ route('voucher-detail', ['id' => $entry->entry_no]) }}"
                                                        class="btn btn-sm btn-default">View</a>
                                                @endpermission

                                                @permission('delete-voucher')
                                                    <a href="{{ route('voucher-delete', ['id' => $entry->entry_no]) }}"
                                                        class="btn btn-sm btn-danger" data-toggle="confirmation"
                                                        data-placement="left" data-title="Are you sure to delete?">Delete</a>
                                                @endpermission



                                            </td>
                                        </tr>
                                    @endforeach

                                </tbody>
                            </table>
                            {{ $allEntries->links() }}
                        </div>
                    </div>
                </div>
            </div>

        </div>
        <!-- /.row -->
    </div>
    <!-- /.container-fluid -->

@stop

@section('js')

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script>

    <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>

    <script>
        function getSearcableResult(self) {
            $('.preloader').fadeIn();

            query = $(self).find('#search_voucher').val();

            var data = {
                'query': query
            };
            $.get('/general-journal-entries/update-query', data, function(data) {
                document.getElementById('update-table').innerHTML = data;

                $('#myTable').DataTable({
                    'paging': false,
                    'searching': false,
                    'info': true
                });
                $('.preloader').fadeOut();
            });


            return false;
        }



        function callFunction() {
            $(function() {
                $('#myTable').DataTable({
                    'pageLength': 50,
                    'paging': false,
                    'ordering': false,
                    'searching': false,
                    'info': false,
                });

            });
            const year = new Date().getFullYear();

            const this_fiscal_year_start_date = new Date(year + '-' + {{ \App\ChartOfAccount::FISCAL_YEAR_START }} +
            '-01');

            const this_fiscal_year_end_date = new Date((year + 1) + '-' + {{ \App\ChartOfAccount::FISCAL_YEAR_END }} +
                '-30');

            const last_fiscal_year_start_date = new Date((year - 1) + '-' + {{ \App\ChartOfAccount::FISCAL_YEAR_START }} +
                '-01');

            const last_fiscal_year_end_date = new Date(year + '-' + {{ \App\ChartOfAccount::FISCAL_YEAR_END }} + '-30');




            $('#daterange-btn').daterangepicker({
                    ranges: {
                        'Today': [moment(), moment()],
                        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                        'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                        'This Month': [moment().startOf('month'), moment().endOf('month')],
                        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month')
                            .endOf(
                                'month')
                        ],
                        'This Fiscal Year': [this_fiscal_year_start_date, this_fiscal_year_end_date],
                        'Last Fiscal Year': [last_fiscal_year_start_date, last_fiscal_year_end_date]
                    },
                    startDate: moment().subtract(29, 'days'),
                    endDate: moment()
                },
                function(start, end) {
                    $('#daterange-btn span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
                }
            );

            $('.update-record').on('click', function() {

                $('.preloader').fadeIn();

                date_range = $('#daterange-btn').val();
                account = $('#c_account').val();
                name = $('#c_name').val();
                multipro_id = $('#multipro_id_input').val();



                var data = {
                    'date_range': date_range,
                    'account': account,
                    'name': name,
                    'multipro_id': multipro_id
                };
                $.get('/general-journal-entries/update-entries', data, function(data) {
                    document.getElementById('update-table').innerHTML = data;

                    $('#myTable').DataTable({
                        'paging': false,
                        'searching': false,
                        'info': true
                    });
                    toastr.success("Report updated.");
                });

                $('.preloader').fadeOut();
            });
        }
        callFunction();

        function addDebit() {
            sum = 0;
            $('.debit').each(function() {
                if (this.innerHTML) {
                    sum += parseInt(this.innerHTML);
                }
            });
            document.getElementById('debit-total').innerHTML = sum;
            checkTotal();
        }

        function addCredit() {
            sum = 0;
            $('.credit').each(function() {
                if (this.innerHTML) {
                    sum += parseInt(this.innerHTML);
                }
            });
            document.getElementById('credit-total').innerHTML = sum;
            checkTotal();
        }

        function checkTotal() {

            debit = parseInt(document.getElementById('debit-total').innerHTML);
            credit = parseInt(document.getElementById('credit-total').innerHTML);
            if (debit == credit) {
                $("#search").prop("disabled", false);

                document.getElementById('debit-total').style.color = 'black';
                document.getElementById('credit-total').style.color = 'black';
                $("#update").prop("disabled", false);
            } else {
                $("#search").prop("disabled", true);

                document.getElementById('debit-total').style.color = 'red';
                document.getElementById('credit-total').style.color = 'red';
                $("#update").prop("disabled", false);
            }

        }

        $('#search').click(function() {

            date = $('#date').val();
            entry_no = $('#entry_no').val();
            adjusting_entry = 0;
            if ($('#adjusting_entry').prop("checked") == true) {
                adjusting_entry = 1;
            }
            account = [];
            $('select[name="account[]"]').each(function() {
                if ($(this).val() != 0)
                    account.push($(this).val());
            });
            name1 = [];
            $('select[name="name1[]"]').each(function() {
                name1.push($(this).val());
            });

            class_id = [];
            $('select[name="class_id[]"]').each(function() {
                class_id.push($(this).val());
            });

            debit = [];
            $('.debit').each(function() {
                if (this.innerHTML) {
                    debit.push(parseInt(this.innerHTML));
                }
            });

            credit = [];
            $('.credit').each(function() {
                if (this.innerHTML) {
                    credit.push(parseInt(this.innerHTML));
                }
            });

            memo = [];
            $('.memo').each(function() {
                if (this.innerHTML) {
                    memo.push(this.innerHTML);
                }
            });

            data = {
                'date': date,
                'entry_no': entry_no,
                'adjusting_entry': adjusting_entry,
                'account': account,
                'debit': debit,
                'credit': credit,
                'memo': memo,
                'name': name1,
                'class_id': class_id
            };

            $.get('/general-journal-entries/add', data, function(data) {

                toastr.success("Entry added successfully.");

                window.location.reload(1);
            });
        });

        function updateEntry() {

            date = $('#date').val();
            entry_no = $('#entry_no').val();
            adjusting_entry = 0;
            if ($('#adjusting_entry').prop("checked") == true) {
                adjusting_entry = 1;
            }
            account = [];
            $('select[name="account[]"]').each(function() {
                if ($(this).val() != 0)
                    account.push($(this).val());
            });
            name1 = [];
            $('select[name="name1[]"]').each(function() {
                name1.push($(this).val());
            });

            class_id = [];
            $('select[name="class_id[]"]').each(function() {
                class_id.push($(this).val());
            });

            debit = [];
            $('.debit').each(function() {
                if (this.innerHTML) {
                    debit.push(parseInt(this.innerHTML));
                }
            });

            credit = [];
            $('.credit').each(function() {
                if (this.innerHTML) {
                    credit.push(parseInt(this.innerHTML));
                }
            });

            memo = [];
            $('.memo').each(function() {
                if (this.innerHTML) {
                    memo.push(this.innerHTML);
                }
            });

            data = {
                'date': date,
                'entry_no': entry_no,
                'adjusting_entry': adjusting_entry,
                'account': account,
                'debit': debit,
                'credit': credit,
                'memo': memo,
                'name': name1,
                'class_id': class_id
            };

            $.get('/general-journal-entries/update', data, function(data) {

                toastr.success("Entry updated successfully.");

                window.location.reload(1);
            });
        }

        function approveEntry() {


            entry_no = $('#entry_no').val();


            data = {
                'entry_no': entry_no
            };

            $.get('/general-journal-entries/approve-entry', data, function(data) {

                toastr.success("Entry updated successfully.");

                window.location.reload(1);
            });
        }


        function showEntry(entry_no) {

            data = {
                'entry_no': entry_no
            };

            $.get('/general-journal-entries/show', data, function(data) {

                document.getElementById('form-div').innerHTML = data;

                $('.chosen-select').chosen - select();

                $(window).scrollTop(0);

            });


        }

        function approveEntryModal(entry_no) {

            data = {
                'entry_no': entry_no
            };

            $.get('/general-journal-entries/approve-modal', data, function(data) {

                document.getElementById('form-div').innerHTML = data;

                $('.chosen-select').chosen - select();

                $(window).scrollTop(0);

            });


        }

        function deleteEntry(entry_no) {

            $.confirm({
                title: 'Confirm!',
                content: 'You cannot revert this.Do you want to proceed!.',
                buttons: {
                    confirm: function() {
                        data = {
                            'entry_no': entry_no
                        };
                        $.get('/general-journal-entries/delete', data, function(data) {
                            toastr.success("Entry deleted successfully.");
                            window.location.reload(1);
                        });
                    },
                    cancel: function() {

                    }
                }
            });



        }


        function updateStatus(value) {
            $('.preloader').fadeIn();

            if (value === 'search') {

                $('.preloader').fadeOut();
                return false;
            }
            var data = {
                'multipro_id': value,
            };

            $.get('{{ route('entry.all') }}', data, function(data) {
                $('.preloader').fadeOut();
                $('#myTable tbody').empty();



                document.getElementById('updatecontent').innerHTML = data;




                $('#multipro_id_input').val(value);
                callFunction();
                toastr.success("Search updated.");


                $('.preloader').fadeOut();
            });

        }
    </script>

@stop
