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

{{--Set Page Title--}}
@section('title', 'Vendor Account')

{{--Include any Internal JS Code--}}
@section('internal-js')
    <script>
        $(document).ready(function () {
            $('#example2').dataTable();

            $('#example1').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;};

                    // Bill AMounts
                    totalBillAmount = api.column( 4 ).data().reduce( function (a, b) {return intVal(a) + intVal(b);}, 0 );
                    currentBillAmount = api.column( 4, { page: 'current'} ).data().reduce( function (a, b) {return intVal(a) + intVal(b);}, 0 );
                    $( api.column( 4 ).footer() ).html(numberRenderer(currentBillAmount) +'<br>('+ numberRenderer(totalBillAmount) +')').css('color', 'blue');


                    // Paid Bill Amounts
                    totalPaidAmount = api.column( 5 ).data().reduce( function (a, b) {return intVal(a) + intVal(b);}, 0 );
                    currentPaidAmount = api.column( 5, { page: 'current'} ).data().reduce( function (a, b) {return intVal(a) + intVal(b);}, 0 );
                    $( api.column( 5 ).footer() ).html(numberRenderer(currentPaidAmount) +'<br>('+ numberRenderer(totalPaidAmount) +')').css('color', 'blue');

                    // Bill Balance Amounts
                    totalBalanceAmount = api.column( 7 ).data().reduce( function (a, b) {return intVal(a) + intVal(b);}, 0 );
                    currentBalanceAmount = api.column( 7, { page: 'current'} ).data().reduce( function (a, b) {return intVal(a) + intVal(b);}, 0 );
                    $( api.column( 7 ).footer() ).html(numberRenderer(currentBalanceAmount) +'<br>('+ numberRenderer(totalBalanceAmount) +')').css('color', 'blue');
                },
            });

            $('#search-vehicle').select2();

            $('#submit-search').on('click', function (){
                var account = $('#search-vehicle').val();
                if(account == ""){
                    alert('Please Select a Vendor Account to Search');
                }else{
                    window.location = '/acc-vendor/'+account;
                }
            });

            /**MAXIMIZE AND MINIMIZE THE HEADER SECTION**/
            $('#minimize').on('click', function (){
                $('#main-div-section').slideUp();
                $('#maximize').show();
                $('#minimize').hide();
            });
            $('#maximize').on('click', function (){
                $('#main-div-section').slideDown();
                $('#maximize').hide();
                $('#minimize').show();
            });
        });

        /**Create a Function to Create a Requisition for the Vendor**/
        function createVendorRequisition(id){
            var route_link = '/create-vendor-requisition/'+id;

            $('#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: 550,
                title: "Create New Requisition for the Vendor",
                buttons: [
                    {
                        text: "Save Details",
                        icon: "ui-icon-check",
                        click: function(e) {
                            if(confirm('Are you sure to Save Entered Details?')){
                                e.preventDefault();
                                var datas = $('#create-vendor-requisition').serializeArray();

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

                                    success: function (res){
                                        // alert(res);
                                        if(res == 'empty type'){
                                            alert('Please Provide the Requisition Type to proceed');
                                        }else if(res == 'empty debit type'){
                                            alert('Please provide the Debit Account to Proceed');
                                        }else if(res == 'empty amount'){
                                            alert('Please provide the Requisition Amount to Proceed');
                                        }else if(res == 'empty date'){
                                            alert('Please Provide Requisition Date');
                                        }else if(res == 'empty bill'){
                                            alert('Please specify the Bill you wish to create a Requisition for');
                                        }else if(res == 'more amount'){
                                            alert('Requisition Amount cannot be greater than the Current Bill Balance');
                                        }else if(res == 'error' ){
                                            alert('System is Unable to perform this Request. Please try again');
                                            location.reload();
                                        }else if(res == 'success'){
                                            alert('Requisition Created Successfully');
                                            location.reload();
                                        }else{
                                            alert('System Encountered an Error. Please Contact System Admin');
                                            location.reload();
                                        }
                                    }
                                });
                            }
                            return false;
                        }
                    }
                ],
                open: function() {
                    $(this).parent().css({'top': 100});
                }
            });
        }

        /**Create a Function to View and Upload Files on a Bill**/
        function uploadBillDocs(id){
            var route_link = '/view-or-upload-bill-documents/'+id;
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $('#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: 700,
                title: "View or Upload Bill Documents to a Vendor File",
                buttons: [
                    {
                        text: "Continue to Save Documents",
                        icon: "ui-icon-check",
                        id: "my-button-1",
                        click: function(e) {
                            if(confirm('Are you sure to upload attached Documents?')){
                                e.preventDefault();
                                $("#my-button-1").attr('disabled', true).html('<div style="text-align: center; margin: 2px 0 2px 0;"><img src="{{asset('images/loads/loader.gif')}}" border=0></div>');
                                var datas = new FormData($('#upload-bill-files')[0]);

                                $.ajax({
                                    method: "POST",
                                    url: route_link,
                                    data: datas,
                                    enctype: 'multipart/form-data',
                                    contentType: false,
                                    processData: false,
                                    success: function (res){
                                        if(res == 'no file attached'){
                                            alert('You did not attach any File to be uploaded');
                                            $("#my-button-1").attr('disabled', false).text('Continue to Save Documents');
                                        }else if(res == 'Wrong file format'){
                                            alert('Please provide a required format for the Documents.');
                                            $("#my-button-1").attr('disabled', false).text('Continue to Save Documents');
                                        }else if(res == 'no other docs'){
                                            alert('You Selected to Upload other Docs but you have not attached any Document.');
                                            $("#my-button-1").attr('disabled', false).text('Continue to Save Documents');
                                        }else if(res == 'empty name one'){
                                            alert('Please Provide Name for Document 1.');
                                            $("#my-button-1").attr('disabled', false).text('Continue to Save Documents');
                                        }else if(res == 'empty name two'){
                                            alert('Please Provide Name for Document 2.');
                                            $("#my-button-1").attr('disabled', false).text('Continue to Save Documents');
                                        }else if(res == 'empty name three'){
                                            alert('Please Provide Name for Document 3.');
                                            $("#my-button-1").attr('disabled', false).text('Continue to Save Documents');
                                        }else if(res == 'empty name four'){
                                            alert('Please Provide Name for Document 4.');
                                            $("#my-button-1").attr('disabled', false).text('Continue to Save Documents');
                                        }else if(res == 'empty name five'){
                                            alert('Please Provide Name for Document 5.');
                                            $("#my-button-1").attr('disabled', false).text('Continue to Save Documents');
                                        }else if(res == 'error'){
                                            alert('There is an Internal error trying to save the Documents');
                                            location.reload();
                                        } else if(res == 'success'){
                                            alert('Documents have been uploaded successfully');
                                            location.reload();
                                        }else{
                                            alert('There is an Internal error trying to save the Documents');
                                            location.reload();
                                        }
                                    }
                                });
                            }
                            return false;
                        }
                    }
                ],
                open: function() {
                    $(this).parent().css({'top': 50});
                }
            });
        }

        /**Create a Function to View a Payment's Details for a Specific Vendor Bill**/
        function viewPaymentStatement(id){
            var route_link = '/view-bill-payment-details/'+id;

            $('#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: 950,
                title: "View Paid Bills Payment Report",
                open: function() {
                    $(this).parent().css({'top': 50});
                }
            });
        }
    </script>
@endsection

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

        #example2 th, td {
            text-align: left;
            padding: 5px;
        }
        #example2 tr:hover {background-color: #a3aef6;}
    </style>
@endsection

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

{{--Set Page Heading--}}
@section('heading')
    Vendor Account:
    @isset($vendor)
        <span class="error">{!! strtoupper($vendor->name) !!}</span>
    @endisset
@endsection

@section('searches')
    <div style="float: right">
        <br>
        {!! Form::open(['method'=>'POST']) !!}
        <div class="guestDetails_input">
            <div class="guestDetails_input" style="text-align: center">
                <select name="search-vehicle" id="search-vehicle" style="width: 200px">
                    <option value="">--Select Vendor Account--</option>
                    @if(isset($vendors))
                        @foreach($vendors as $row)
                            <option value="{{$row->stamp}}">{!! strtoupper($row->name) !!}</option>
                        @endforeach
                    @endif
                </select>
            </div>
        </div>
        <div class="guestDetails_input">
            <div class="guestDetails_input">
                <button type="button" id="submit-search" style="width: auto; height: 22px; cursor: pointer" title="Search a Product"><i class="fa fa-search" aria-hidden="true"></i></button>
            </div>
        </div>
        {!! Form::close() !!}
    </div>
@endsection
{{--Page Content Goes here--}}
@section('content')
    <div style="float: left">
        <button onclick="printOptions('{{$vendor->stamp}}')" type="button" class="navButtons" style="margin-left: 0px;background-color: #f1d414; color: black"><i class="fa fa-print"></i> &nbsp;PRINT OPTIONS</button>
        <button onclick="createVendorRequisition('{{$vendor->stamp}}')" type="button" class="navButtons" style="background-color: #04ab25; color: white"><i class="fa fa-money"></i> &nbsp;CREATE REQUISITION</button>
    </div>
    <div style="text-align: right">
        <button type="button" class="navButtons" style="background-color: #2f45d7" onclick="editVendorDetails('{{$vendor->id}}')"><i class="fa fa-pencil-square-o"></i> &nbsp;EDIT VENDOR</button>
        @if(auth()->user()->admin == 1)
            <button onclick="deleteVendor('{{$vendor->stamp}}')" type="button" class="navButtons" style="background-color: #f10e21"><i class="fa fa-trash"></i> &nbsp;DELETE VENDOR</button>
        @endif
    </div>
    <div style="background-color: rgba(234,236,238,0.72); border-radius: 5px; padding: 5px 6px">
        <div style="float: right;">
            <i id="minimize" class="fa fa-chevron-up" aria-hidden="true" title="Minimize" style="cursor: pointer"></i>
            <i id="maximize" class="fa fa-chevron-down" aria-hidden="true" title="Maximize" style="cursor: pointer; display: none"></i>
        </div><br>
        <div id="main-div-section">
            <div class="wrapperer" id="client-table-wrapper">
                <div class="column" style="max-width: 12%">
                    <table  style="width: 100%; border-collapse: collapse">
                        <tr >
                            <th rowspan="6"><img src="{{asset('images/user.png')}}" style="width: 100px; height: 90px; border-radius: 50%"><br>
                                @if(app('CompanyModules')->dms == 1)
                                    <button type="button" style="cursor: pointer; font-size: 8pt"><i class="fa fa-upload" aria-hidden="true"></i> &nbsp; Upload Photo</button>
                                @endif
                            </th>
                        </tr>
                    </table>
                </div>
                <div class="column">
                    <table  class="table" style="width: 100%; border-collapse:collapse; margin: 5px">
                        <tr>
                            <th>Vendor Name:</th>
                            <td><b class="error">{!! strtoupper($vendor->name) !!}</b></td>
                        </tr>
                        <tr>
                            <th>Branch:</th>
                            <td>
                                @if($vendor->branchDetails)
                                    <b class="error">{!! strtoupper($vendor->branchDetails->name) !!}</b>
                                @else
                                    -
                                @endif
                            </td>
                        </tr>
                        <tr>
                            <th>Date Created:</th>
                            <td><b>{{$vendor->created_at->format('j F Y H:i:s')}}</b></td>
                        </tr>
                    </table>
                </div>
                <div class="column">
                    <table class="table" style="width: 100%; border-collapse:collapse; margin: 5px">
                        <tr>
                            <th>Expense Account:</th>
                            <td>
                                @if($vendor->expenseAccount)
                                    <b class="error">{!! strtoupper($vendor->expenseAccount->acc_name) !!}</b>
                                @else
                                    -
                                @endif
                            </td>
                        </tr>
                        <tr>
                            <th>Email Address:</th>
                            <td><b style="color: #0000cc">{!! $vendor->email !!}</b></td>
                        </tr>
                        <tr>
                            <th>Phone Number:</th>
                            <td><b>{!! strtoupper($vendor->phone) !!}</b></td>
                        </tr>
                    </table>

                </div>
                <div class="column">
                    <table class="table" style="width: 100%; border-collapse:collapse; margin: 5px">
                        <tr>
                            <th>Account Number:</th>
                            <td><b class="error">{!! strtoupper($vendor->acc_no) !!}</b></td>
                        </tr>
                    </table>
                    <div class="guestDetails_inputDivider"></div>
                    <table style="width: 100%; border-collapse: collapse;">
                        <tr>
                            <td>
                                <button type="button" class="navButtons" style="background-color: #d9ffff;color: black; margin-bottom: 0;font-weight: bold; min-width: 200px ;font-size: 14px">ACC BAL
                                    (<span class="error">KES</span>):
                                    <b class="error" style="margin-left: 10px">
                                        {{number_format($vendor->currentVendorBalance($vendor->id)['currentBalance'],2)}}
                                    </b>
                                </button>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div><br>
    <div class="tab">
        <button class="tablinks" onclick="openCity(event, 'policies')" id="defaultOpen" >Recent Transactions</button>
        <button class="tablinks" onclick="openCity(event, 'reqs')" id="defaultOpen" >Pending Requisitions
            <span class="
            @if(count($pendingRequisitions) > 0)
                {{'countItems'}}
            @else
                {{'zeroItems'}}
            @endif
            ">&nbsp;{{count($pendingRequisitions)}}&nbsp;</span>
        </button>
    </div>

    <div class="tabcontent" id="policies">
        <h3 ><span class="error" style="margin-right: 20px">Recent Transaction Listing(Max of 10 Last Entries)</span></h3>

        <table id="example1" class="display" style="width: 100%; border-collapse: collapse">
            <thead>
            <tr style="background-color: #a1b5d3">
                <th>No</th>
                <th>Trans Type</th>
                <th>Ref</th>
                <th>Details</th>
                <th>Bill Amount</th>
                <th>Paid Amount</th>
                <th>Payments</th>
                <th>Bill Balance</th>
                <th>Bill Date</th>
                <th>Bill Due Date</th>
                <th>View/Upload Docs</th>
            </tr>
            </thead>
            <tbody>
            @foreach($recentTransactions as $row)
                <tr>
                    <td class="ar"></td>
                    <td>BILL</td>
                    <td><b class="error">{!! $row->ref !!}</b></td>
                    <td>{!! $row->narration !!}</td>
                    <td class="error" style="font-weight: bold">{{number_format($row->amount, 2)}}</td>
                    <td class="success" style="font-weight: bold">{{number_format(abs($row->billPaidAmount($row->id)), 2)}}</td>
                    <td><i title="View Payments made on Bill" class="fa fa-eye error" style="font-size: 16px;cursor: pointer; margin-left: 5px" onclick="viewPaymentStatement('{{$row->id}}')"></i></td>
                    <td class="error" style="font-weight: bold">{{number_format($row->amount - abs($row->billPaidAmount($row->id)), 2)}}</td>
                    <td>{{date('d/m/Y', strtotime($row->date))}}</td>
                    <td>{{date('d/m/Y', strtotime($row->due_date))}}</td>
                    <td><i class="fa fa-upload error" style="font-size: 16px; cursor: pointer" onclick="uploadBillDocs('{{$row->id}}')"></i></td>
                </tr>
            @endforeach

            </tbody>
            <tfoot>
            <tr style="background-color: #a1b5d3">
                <th>No</th>
                <th>Trans Type</th>
                <th>Ref</th>
                <th>Details</th>
                <th>Bill Amount</th>
                <th>Paid Amount</th>
                <th>Payments</th>
                <th>Bill Balance</th>
                <th>Bill Date</th>
                <th>Bill Due Date</th>
                <th>View/Upload Docs</th>
            </tr>
            </tfoot>
        </table>
    </div>

    {{--Pending Requisitions--}}
    <div class="tabcontent" id="reqs">
        <h3 ><span class="error" style="margin-right: 20px">Unauthorized and Unpaid Requisitions</span></h3>

        <table id="example2" class="display" style="width: 100%; border-collapse: collapse">
            <thead>
            <tr style="background-color: #a1b5d3">
                <th>No</th>
                <th>Req Number</th>
                <th>Type</th>
                <th>Dr Ledger</th>
                <th>Payee</th>
                <th>Requisition Amount</th>
                <th>Currency</th>
                <th>Exchange rate</th>
                <th>Status</th>
                <th>Date Requisitioned</th>
                <th>Requisitioned By</th>
                <th>View More</th>
            </tr>
            </thead>
            <tbody>
            @foreach($pendingRequisitions as $req)
                <tr>
                    <td class="br"></td>
                    <td><a href="{{url('requisition-details/'.$req->id.'?type=summary')}}" class="inner" target="_blank"><b class="error">RQ00{{$req->id}}</b></a></td>
                    <td>BILL PAYMENT</td>
                    <td>
                        @if($req->account != null)
                            {!! strtoupper($req->account->acc_name) !!}
                        @endif
                    </td>
                    <td>{!! $req->payee !!}</td>
                    <td><b>{!! number_format($req->amount,2) !!}</b></td>
                    <td>
                        @if($req->currencyDetails != null)
                            <b class="error">{!! $req->currencyDetails->abbr !!}</b>
                        @endif
                    </td>
                    <td>{!! number_format($req->conversion_rate,2) !!}</td>
                    <td>
                        @if($req->first_approved == 0)
                            <i class="error">Pending First Approval</i>
                        @else
                            @if($req->second_approved == 0)
                                <i class="error">Pending Second Approval</i>
                            @else
                                <b class="error">{!!  $req->req_status !!}</b>
                            @endif
                        @endif
                    </td>
                    <td>{{date('d/m/Y', strtotime($req->req_date))}}</td>
                    <td>
                        @if($req->user != null)
                            {!! $req->user->firstName[0].". ".$req->user->laststName !!}
                        @endif
                    </td>
                    <td><a href="{{url('requisition-details/'.$req->id.'?type=summary')}}" class="inner" target="_blank"><i class="fa fa-eye error" style="font-size: 16px; cursor: pointer" onclick="viewVenedorRequisition()"></i></a></td>
                </tr>
            @endforeach
            </tbody>
            <tfoot>
            <tr style="background-color: #a1b5d3">
                <th>No</th>
                <th>Req Number</th>
                <th>Type</th>
                <th>Dr Ledger</th>
                <th>Payee</th>
                <th>Requisition Amount</th>
                <th>Currency</th>
                <th>Exchange rate</th>
                <th>Status</th>
                <th>Date Requisitioned</th>
                <th>Requisitioned By</th>
                <th>View More</th>
            </tr>
            </tfoot>
        </table>
    </div>
@endsection
@section('created-by')
    * Vendor Account Created
    @if($vendor->user != null)
        By <b>{{$vendor->user->firstName." ".$vendor->user->laststName}}</b>
    @endif
    on <b>{{$vendor->created_at->format('j F Y H:i:s')}}</b>
@endsection

{{--System Hints Page--}}
@section('modal_heading')
    <h1>Vendor Account</h1>
@endsection
@section('modal_title')
    <h3><u>Dashboard Functionalities</u></h3>
    <b>
        <ol>
            <li>View Vendor Details</li>
            <li>Amend Vendor Details</li>
            <li>Vendor Transactional Report</li>
            <li>Delete a Wrongly created Vendor</li>
        </ol>
    </b>
@endsection
