{{--Get the Page Format--}}
@extends('layouts.app')

{{--Set Page Title--}}
@section('title', 'Manage Company Bills')

{{--Include any Internal JS Code--}}
@section('internal-js')
    <script>
        $(document).ready(function () {
            $('#example').dataTable({
                dom: 'lBfrtip',
                buttons: [
                    { extend: 'excel', className: 'download-buttons'},
                    { extend: 'pdf', className: 'download-buttons'},
                ],
                footerCallback: function ( row, data, start, end, display ) {
                    var api = this.api(), data;
                    var numberRenderer = $.fn.dataTable.render.number(',', '.', 2).display;

                    // Remove the formatting to get integer data for summation
                    var intVal = function ( i ) {
                        return typeof i === 'string' ? i.replace(/[\.]/g, '.').replace(/[\,]/g, '') * 1 : typeof i === 'number' ? i : 0;
                    };

                    // Total over all pages
                    totalBillAmount = api.column( 3 ).data().reduce( function (a, b) {return intVal(a) + intVal(b);}, 0 );

                    // Total over this page
                    currentBillAmount = api.column( 3, { page: 'current'} ).data().reduce( function (a, b) {return intVal(a) + intVal(b);}, 0 );

                    // Update footer
                    $( api.column( 3 ).footer() ).html(numberRenderer(currentBillAmount) +'<br>('+ numberRenderer(totalBillAmount) +')').css('color', 'blue');

                },
            } );
            $('#example1').dataTable();
        });
        function addNewBill(){
            var route_link = '/add-new-bill';

            $('#edit_dialog_content').html('<div style="text-align: center; margin: 20px 0 20px 0;"><img src="{{asset('images/loads/loader.gif')}}" border=0></div>');
            $('#edit_dialog_content').load(encodeURI(route_link));
            $('#edit_dialog_content').dialog({
                modal: true,
                width: 750,
                title: "Create New Bill for the Company",
                buttons: [
                    {
                        text: "Save Details",
                        icon: "ui-icon-check",
                        click: function(e) {
                            if(confirm('Are you sure to Save Entered Details?')){
                                e.preventDefault();
                                var datas = $('#add-new-bill').serializeArray();

                                $.ajax({
                                    method: "POST",
                                    url: route_link,
                                    data: datas,

                                    success: function (res){
                                        // alert(res);
                                        if(res == 'empty fields'){
                                            alert('Please Fill out all fields marked with a Red Asterisks*');
                                        }else if(res == 'zero amount'){
                                            alert('Entered Bill Amount should be greater than 0');
                                        }else if(res == 'bill exists'){
                                            alert('You have a Similar Bill. Please confirm that');
                                        }else if(res == 'stamp exist'){
                                            alert('There was an Internal System Error. Please Try Again');
                                        }else if(res == 'error bill master'){
                                            alert('There was an Internal System Error. Please Try Again');
                                        }else if(res == 'error' ){
                                            alert('System is Unable to perform this Request. Please try again');
                                            window.location = '/acc-bills-manager?submit=false';
                                        }else if(res == 'success'){
                                            window.location = '/acc-bills-manager?submit=true';
                                        }else{
                                            alert('System Encountered an Error. Please Contact System Admin');
                                            window.location = '/acc-bills-manager?error=system';
                                        }
                                    }
                                });
                            }
                            return false;
                        }
                    }
                ],
                open: function() {
                    $(this).parent().css({'top': 100});
                }
            });
        }
    </script>
@endsection

{{--Include any Internal CSS Code--}}
@section('internal-css')
    <style>
        #example th, td {
            text-align: left;
            padding: 5px;
        }
        #example tr:hover {background-color: #a3aef6;}
        #example1 th, td {
            text-align: left;
            padding: 5px;
        }
        #example1 tr:hover {background-color: #a3aef6;}
    </style>

@endsection

{{--Control Page Header/Links--}}
@section('headers')
    @include('headers.finance-header')
@endsection

{{--Set Page Heading--}}
@section('heading')
    Manage Company Bills
@endsection
@section('done-by', '')

{{--Page Content Goes here--}}
@section('content')
    @isset($_GET['submit'])
        @if($_GET['submit'] == 'true')
            <div class="yesFound error-section">A New Bill has been Created Successfully</div><br>
        @endif
        @if($_GET['submit'] == 'false')
            <div class="notFound error-section">Error Submitting New Bill Details for Storage. Please Try again</div><br>
        @endif
    @endisset
    @isset($_GET['error'])
        @if($_GET['error'] == 'system')
            <div class="notFound error-section">System Encountered and Error. Please Contact System Administrator for help from the Live Support </div><br>
        @endif
    @endisset

    <div class="tab">
        <button class="tablinks" onclick="openCity(event, 'general')" id="defaultOpen">Bills Manager</button>
        @if(app('UserReads')->log == 1)
            <button class="tablinks" onclick="openCity(event, 'log')" >LOG</button>
        @endif
    </div>
    <div class="tabcontent" id="general">
        <h3 class="error">Manage Company Bills
            <button style="margin-left: 20px; cursor: pointer;height: 25px" onclick="addNewBill()">+ Add New Bill</button>
        </h3>
        <table id="example" class="display" style="width: 100%; border-collapse: collapse;">
            <thead>
            <tr style="background-color: #a1b5d3">
                <th>No</th>
                <th>Vendor Name</th>
                <th>Branch</th>
                <th>Current Balance</th>
                <th>< 30 Days</th>
                <th>31 to 60 Days</th>
                <th>61 to 90 Days</th>
                <th>91 to 180 Days</th>
                <th>181 to 365 Days</th>
                <th>> 365 Days</th>
                <th>View Account</th>
            </tr>
            </thead>
            <tbody>
            @foreach($lists as $list)
                @if($list->currentVendorBalance($list->id) != null && $list->currentVendorBalance($list->id)['currentBalance'] > 0)
                    <tr>
                        <td class="ar"></td>
                        <td><a href="{{url('acc-vendor/'.$list->stamp)}}" class="inner" style="color: red; font-weight: bold" target="_blank">{!! strtoupper($list->name) !!}</a></td>
                        <td>
                            @if($list->branchDetails != null)
                                {!! $list->branchDetails->name !!}
                            @else
                                <span class="error"><b>No Branch Details Found</b></span>
                            @endif
                        </td>
                        <td style="font-weight: bold" class="error">{!! number_format($list->currentVendorBalance($list->id)['currentBalance'],2) !!}</td>
                        <td><b>{!! number_format($list->currentVendorBalance($list->id)['lessThanThirty'],2) !!}</b></td>
                        <td><b>{!! number_format($list->currentVendorBalance($list->id)['thirtyAndSixty'],2) !!}</b></td>
                        <td><b>{!! number_format($list->currentVendorBalance($list->id)['sixtyAndNinety'],2) !!}</b></td>
                        <td><b>{!! number_format($list->currentVendorBalance($list->id)['ninetyAndOneEighty'],2) !!}</b></td>
                        <td><b>{!! number_format($list->currentVendorBalance($list->id)['oneEightyAndThreeSixtyFive'],2) !!}</b></td>
                        <td><b class="error">{!! number_format($list->currentVendorBalance($list->id)['moreThanThreeSixtyFive'],2) !!}</b></td>
                        <td><a href="{{url('acc-vendor/'.$list->stamp)}}" class="inner" style="color: red; font-weight: bold" target="_blank"><i class="fa fa-eye error" style="font-size: 14px"></i></a></td>
                    </tr>
                @endif
            @endforeach
            </tbody>
            <tfoot>
            <tr style="background-color: #a1b5d3">
                <th>No</th>
                <th>Vendor Name</th>
                <th>Branch</th>
                <th>Current Balance</th>
                <th>< 30 Days</th>
                <th>31 to 60 Days</th>
                <th>61 to 90 Days</th>
                <th>91 to 180 Days</th>
                <th>181 to 365 Days</th>
                <th>> 365 Days</th>
                <th>View Account</th>
            </tr>
            </tfoot>
        </table>
    </div>
    <div class="tabcontent" id="log">
        <span onclick="this.parentElement.style.display='none'" class="topright">&times</span>
        <h3 class="error">Audit Trails [LOGs]</h3>
        <table id="example1" class="display" style="width:100%; border-collapse: collapse">
            <thead>
            <tr style="background-color: #a1b5d3">
                <th style="text-align: left">No</th>
                <th style="text-align: left">Log Narration.</th>
                <th style="text-align: left">User</th>
                <th style="text-align: left">Date & Time</th>
            </tr>
            </thead>
            <tbody>
            @if(isset($history))
                @foreach($history as $histo)
                    <tr>
                        <td style="width: 50px" class="br"></td>
                        <td class="error">{!!   $histo->narration !!}</td>
                        <td></td>
                        <td>{{$histo->created_at->format('d/m/Y') .' at '. $histo->created_at->format('h:i:s a')}}</td>
                    </tr>
                @endforeach
            @endif
            </tbody>
            <tfoot>
            <tr style="background-color: #a1b5d3">
                <th style="text-align: left">No</th>
                <th style="text-align: left">Log Narration.</th>
                <th style="text-align: left">User</th>
                <th style="text-align: left">Date & Time</th>
            </tr>
            </tfoot>
        </table>
    </div>
@endsection

{{--System Hints Page--}}
@section('modal_heading')
    <h1>Manage Company Bills </h1>
@endsection
@section('modal_title')
    <h3><u>Dashboard Functionalities</u></h3>
    <b>
        <ol>
            <li>View all Bills for the Company</li>
            <li>Add New Bills</li>
            <li>Delete Disapprove Bills</li>
            <li>View LOGs[Audit Trail]</li>
        </ol>
    </b>
@endsection
