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

{{--Set Page Title--}}
@section('title', 'Company Requisition Reports')

{{--Include any Internal JS Code--}}
@section('internal-js')
    <script>
        $(document).ready(function () {
            $('#insurers1').DataTable( {
                dom: 'lBfrtip',
                buttons: [
                    { extend: 'excel', className: 'download-buttons' },
                ],
                "paging":   false,
            } );
            $('#insurer-list').select2();
            $('#status-list').select2();
            $('#currency-list').select2();
            $('#type-list').select2();
            $('#requisition-type-list').select2();

            $('#requisition-type-list').on('change', function (){
                let type = $(this).val();

                if(type == 'premium'){
                    $('#clients-div').show();
                    $('#insurers-div').hide();
                }else if(type == 'commission'){
                    $('#clients-div').hide();
                    $('#insurers-div').show();
                }else{
                    $('#clients-div').hide();
                    $('#insurers-div').hide();
                }

            });

            $('#client-name').on('input paste', function (){
                let name = $(this).val();
                if(name != ""){
                    $.ajax({
                        method: 'GET',
                        url: '/search-client-by-name/'+name,
                        data: name,
                        success: function (res){
                            if(res != ""){
                                $('#client-search-results').show();
                                $('#client-search-results').html(res);
                            }else{
                                $('#client-search-results').hide();
                            }
                        }
                    });
                }

            });


            $('#date-from').on('change', function (){
                $('#date-to').attr('required', true);
            });
            $('#date-to').on('change', function (){
                $('#date-from').attr('required', true);
            });

            /**Anytime the Selector Class is clicked: Show Delete ALl Button**/
            $('.selectRequisition').click(function (){
                if($('.selectRequisition').is(':checked')){
                    $('#delete-all-div').show();
                }else{
                    $('#delete-all-div').hide();
                }
            });
        });

        function createNewRequisition(){
            var route_link = '/create-new-requisition';

            $('#edit_dialog_content').html('<div style="text-align: center; margin: 20px 0 20px 0;"><img src="{{asset('images/loads/loader.gif')}}" border=0></div>')
            .load(encodeURI(route_link))
            .dialog({
                modal: true,
                width: 550,
                title: "Create a New Requisition",
                buttons: [
                    {
                        text: "Create Requisition",
                        icon: "ui-icon-check",
                        id: "my-button-1",
                        click: function(e) {
                            if(confirm('Are you sure to Create a New Requisition with Entered Details?')){
                                e.preventDefault();
                                $("#my-button-1").attr('disabled', true).text('Please Wait....');
                                var datas = $('#create-new-requisition').serializeArray();
                                $.ajax({
                                    method: "POST",
                                    url: route_link,
                                    data: datas,
                                    success: function (res){
                                        if(res == 'error'){
                                            alert('There was an internal error. Please contact System Admin');
                                            location.reload();
                                        }else if(res == 'success'){
                                            alert('Requisition Created Successfully');
                                            location.reload();
                                        }else if(res == 'empty type'){
                                            alert('Please select a Requisition Type to proceed');
                                            $("#my-button-1").attr('disabled', false).text('Create Requisition');
                                        }else if(res == 'empty debit type'){
                                            alert('Select a Ledger to be Debited');
                                            $("#my-button-1").attr('disabled', false).text('Create Requisition');
                                        }else if(res == 'empty amount'){
                                            alert('Please enter the Requisition Amount');
                                            $("#my-button-1").attr('disabled', false).text('Create Requisition');
                                        }else if(res == 'empty date'){
                                            alert('Please Select a Requisition Date');
                                            $("#my-button-1").attr('disabled', false).text('Create Requisition');
                                        }else{
                                            alert('System encountered an error. please contact System Admin');
                                            location.reload();
                                        }
                                    }
                                });
                            }
                            return false;
                        }
                    }
                ],
                open: function() {
                    $(this).parent().css({'top': 50});
                },
            });
        }

        /**Pay for an Approved Requisition**/
        function payRequisition(id,name){
            var route_link = '/pay-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>')
                .load(encodeURI(route_link))
                .dialog({
                modal: true,
                width: 550,
                title: "Make a Payment to a Requisition for: " + name,
                buttons: [
                    {
                        text: "Continue & Pay",
                        icon: "ui-icon-check",
                        id: "my-button-1",
                        click: function(e) {
                            if(confirm('Are you sure to Pay the Amount on the Selected Requisition?')){
                                e.preventDefault();
                                $("#my-button-1").attr('disabled', true).text('Please Wait....');
                                var datas = $('#pay-requisition').serializeArray();
                                $.ajax({
                                    method: "POST",
                                    url: route_link,
                                    data: datas,
                                    success: function (res){
                                        if(res == 'error'){
                                            alert('There was an internal error. Please contact System Admin');
                                            location.reload();
                                        }else if(res == 'success'){
                                            alert('Payment Posted Successfully');
                                            location.reload();
                                        }else if(res == 'empty account'){
                                            alert('Please select an Account to make payment from');
                                            $("#my-button-1").attr('disabled', false).text('Create Requisition');
                                        }else if(res == 'empty mode'){
                                            alert('Please Select Payment Mode before you can proceed');
                                            $("#my-button-1").attr('disabled', false).text('Create Requisition');
                                        }else if(res == 'empty sub mode'){
                                            alert('Please select the Sub-Mode of Payment');
                                            $("#my-button-1").attr('disabled', false).text('Create Requisition');
                                        }else if(res == 'empty ref'){
                                            alert('Please Enter the payment Reference before you can continue');
                                            $("#my-button-1").attr('disabled', false).text('Create Requisition');
                                        }else{
                                            alert('System encountered an error. please contact System Admin');
                                            location.reload();
                                        }
                                    }
                                });
                            }
                            return false;
                        }
                    }
                ],
                open: function() {
                    $(this).parent().css({'top': 50});
                },
            });
        }

        /**Run a First Approval**/
        function firstApproval(id){
            if(confirm('Are you sure to First Approve this Requisition?')){
                $.ajax({
                    method: "GET",
                    url: '/requisition-first-approval/'+id,
                    data: id,
                    success: function (res){
                        if(res == 'error'){
                            alert('There was an internal error. Please contact System Admin');
                            location.reload();
                        }else if(res == 'success'){
                            alert('Requisition First Approved successfully');
                            location.reload();
                        }else{
                            alert('System encountered an error. please contact System Admin');
                            location.reload();
                        }
                    }
                });
            }
            return false;
        }

        /**Run a First Approval**/
        function secondApproval(id){
            if(confirm('Are you sure to Second Approve this Requisition?')){
                $.ajax({
                    method: "GET",
                    url: '/requisition-second-approval/'+id,
                    data: id,
                    success: function (res){
                        if(res == 'error'){
                            alert('There was an internal error. Please contact System Admin');
                            location.reload();
                        }else if(res == 'success'){
                            alert('Requisition Second Approved successfully');
                            location.reload();
                        }else{
                            alert('System encountered an error. please contact System Admin');
                            location.reload();
                        }
                    }
                });
            }
            return false;
        }

        /**Create a Function Delete a Requisition and Revert back the Cart**/
        function deleteRequisition(id){
            if(confirm('Are you sure to Delete this Requisition and Revert it back to a Cart?')){
                $.ajax({
                    method: "GET",
                    url: '/requisition-delete/'+id,
                    data: id,
                    success: function (res){
                        if(res == 'error'){
                            alert('There was an internal error. Please contact System Admin');
                            location.reload();
                        }else if(res == 'success'){
                            alert('Requisition Deleted successfully');
                            location.reload();
                        }else{
                            alert('System encountered an error. please contact System Admin');
                            location.reload();
                        }
                    }
                });
            }
            return false;

        }

        /**Delete all Selected Requisitions**/
        function deleteAllSelectedRequisitions(){
            if(confirm('Are you sure to Delete all the Selected Requisitions?')){
                $('.selectRequisition:checkbox:checked').each(function (){
                    if($(this).is(':checked')){
                       /**We will be using AJAX to Delete the Items One By One**/
                       $.ajax({
                           method : 'GET',
                           url : '/delete-requisition-from-batch/'+$(this).val(),
                           data: $(this).val(),
                           success: function (res){
                               if(res === 'error'){
                                   alert('Requisition Number '+$(this).val() + ' was not Deleted');
                               }
                           },
                           error: function (jqXHR, textStatus, errorThrown){
                               alert('This is the Delete Function Error: ' + errorThrown);
                           }
                       });
                    }
                });
              window.location = '/requisition';
            }
            return false;
        }
    </script>
@endsection

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

@endsection

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

{{--Set Page Heading--}}
@section('heading', 'Company Requisition Report')
@section('done-by', '')

{{--Page Content Goes here--}}
@section('content')
    <button onclick="createNewRequisition()" type="button" class="navButtons" style="background-color: #4682a8; margin-bottom: 0; margin-left: 0"> <i class="fa fa-plus-circle" ></i> &nbsp;Create a New Requisition</button>
    <div class="inputDivider" style="margin-top: 10px; text-align: left; background-color: lightcyan">
        {!! Form::open(['action'=>['Payments\RequisitionController@showRequisitions'], 'method'=>'POST', 'id'=>'filter-requisitions', 'class'=>'fields-small']) !!}
        <div class="guestDetails_input_right">
            <div class="guestDetails_inputLabel">
                &nbsp;
            </div>
            <div class="guestDetails_input_right">
                <button type="submit" name="search" style="cursor: pointer"><i class="fa fa-search" aria-hidden="true"></i></button>
            </div>
        </div>
        <div class="guestDetails_input_right">
            <div class="guestDetails_inputLabel">
                Date Added To:<span class="error">*</span>
            </div>
            <div class="guestDetails_input_right">
                {!! Form::date('to', $search['to'] ?? null, ['id'=>'date-to','style'=>'cursor:pointer', 'class'=>'input-text-height']) !!}
            </div>
        </div>
        <div class="guestDetails_input_right">
            <div class="guestDetails_inputLabel">
                Date Added From:<span class="error">*</span>
            </div>
            <div class="guestDetails_input_right">
                {!! Form::date('from',  $search['from'] ?? null, ['id'=>'date-from','style'=>'cursor:pointer', 'class'=>'input-text-height']) !!}
            </div>
        </div>
        <div class="guestDetails_input_right">
            <div class="guestDetails_inputLabel">
                Requisition No:<span class="error">*</span>
            </div>
            <div class="guestDetails_input_right">
                {!! Form::text('payment-no', '', ['size'=>10,'class'=>'input-text-height', 'id'=>'receipt-no','autocomplete'=>'off']) !!}
            </div>
        </div>
        <div class="guestDetails_input_right">
            <div class="guestDetails_inputLabel">
                Requisition Status:<span class="error">*</span>
            </div>
            <div class="guestDetails_input_right">
                <select name="requisition-status" id="type-list" style="width: 120px">
                    <option value="all" >ALL</option>
                    <option value="approved">APPROVED</option>
                    <option value="disapproved">DISAPPROVED</option>
                </select>
            </div>
        </div>
        <div class="guestDetails_input_right">
            <div class="guestDetails_inputLabel">
                Requisition Type:<span class="error">*</span>
            </div>
            <div class="guestDetails_input_right">
                <select name="requisition-type" id="requisition-type-list" style="width: 120px">
                    <option value="all" >ALL</option>
                    <option value="bank-transfer">BANK TRANSFER</option>
                    <option value="payroll">PAYROLL</option>
                </select>
            </div>
        </div>
        <div class="guestDetails_inputDividerNone" style="height: 0"></div>
        {!! Form::close() !!}
    </div>

    @if($requisitions != null)
        <div class="guestDetails_inputDivider"></div>
        <div>
            <!--Export Links/Buttons-->
            <span onclick="this.parentElement.style.display='none'" class="topright" style="margin-left: 20px">&times</span>
            <div id="delete-all-div" style="display: none">
                <button onclick="deleteAllSelectedRequisitions()" type="button" class="navButtons" style="background-color: #ef112a; margin-bottom: 0; margin-left: 0"> <i class="fa fa-trash"></i> DELETE ALL SELECTED REQUISITIONS</button>
                <div class="guestDetails_inputDivider"></div>
            </div>
            <table id="insurers1" class="" style="width: 100%; border-collapse: collapse; ">
                <thead>
                <tr style="background-color: #a1b5d3">
                    <th>No</th>
                    <th>Selector</th>
                    <th>RQ No.</th>
                    <th>Type</th>
                    <th>Dr Ledger</th>
                    <th>Paid To</th>
                    <th>Payee</th>
                    <th>Narration</th>
                    <th>Amount</th>
                    <th>Currency</th>
                    <th>Exchange rate</th>
                    <th>Status</th>
                    <th>Date Raised</th>
                    <th>User</th>
                    <th>Approve</th>
                    <th>Remove</th>
                    <th>Print</th>
                    <th>First Approver</th>
                    <th>Second Approver</th>
                </tr>
                </thead>
                <tbody>
                @if($requisitions != null || session('requisitions'))
                    @foreach($requisitions as $req)
                        <tr>
                            <td class="ar"></td>
                            <td>
                                @if($req->req_status == 'paid')
                                    <i class="error">Already Paid</i>
                                @else
                                    <input type="checkbox" class="selectRequisition" value="{!! $req->id !!}">
                                @endif

                            </td>
                            <td><a href="{{url('requisition-details/'.$req->id.'?type=summary')}}" class="inner"><b class="error">RQ00{{$req->id}}</b></a></td>
                            <td>{{$req->req_type}}</td>

                            <td>
                                @if($req->account != null)
                                    {!! strtoupper($req->account->acc_name) !!}
                                @endif
                            </td>
                            <td>
                                <b>
                                    @if($req->req_type == 'remit-premium')
                                        @if($req->insurer != null)
                                            {!! strtoupper($req->insurer->nm) !!}
                                        @endif
                                    @elseif($req->type == 'agent-commission')
                                        @if($req->agent != null)
                                            {!! strtoupper($req->agent->contact_person) !!}
                                        @endif
                                    @endif
                                </b>
                            </td>

                            <td>{!! $req->payee !!}</td>
                            <td>{!! $req->nar !!}</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->lastName !!}
                                @endif
                            </td>
                            <td>
                                @if($req->first_approved == 0)
                                    <button onclick="firstApproval('{{$req->id}}')" class="section-button" style="width: 100px"> First Approval</button>
                                @else
                                    @if($req->second_approved == 0)
                                        <button onclick="secondApproval('{{$req->id}}')" class="section-button" style="width: 120px"> Second Approval</button>
                                    @endif
                                @endif
                                @if($req->req_status == 'pending payment')
                                    <button onclick="payRequisition('{{$req->id}}', '{{$req->payee}}')" class="section-button" style="width: 100px"> PAY NOW <i class="fa fa-money"></i></button>
                                @endif
                            </td>
                            <td>
                                @if($req->first_approved == 0)
                                    <i onclick="deleteRequisition('{{$req->id}}')" class="fa fa-trash-o error" style="font-size: 22px; cursor: pointer"></i>
                                @endif
                            </td>
                            <td><a href="{{url('requisition-pdf/'.$req->id.'/AddWatermark')}}" class="inner" target="_blank"><b class="error"><i class="fa fa-print" style="font-size: 22px"></i></b></a></td>
                            <td>
                                @if($req->firstApprover != null)
                                    {!! $req->firstApprover->firstName." ".$req->firstApprover->lastName !!}
                                @else
                                    -
                                @endif
                            </td>
                            <td>
                                @if($req->secondApprover != null)
                                    {!! $req->secondApprover->firstName." ".$req->secondApprover->lastName !!}
                                @else
                                    -
                                @endif
                            </td>
                        </tr>
                    @endforeach
                @endif
                </tbody>
                <tfoot>
                <tr style="background-color: #a1b5d3">
                    <th>No</th>
                    <th>Selector</th>
                    <th>RQ No.</th>
                    <th>Type</th>
                    <th>Dr Ledger</th>
                    <th>Paid To</th>
                    <th>Payee</th>
                    <th>Narration</th>
                    <th>Amount</th>
                    <th>Currency</th>
                    <th>Exchange rate</th>
                    <th>Status</th>
                    <th>Date Raised</th>
                    <th>User</th>
                    <th>Approve</th>
                    <th>Remove</th>
                    <th>Print</th>
                    <th>First Approver</th>
                    <th>Second Approver</th>
                </tr>
                </tfoot>
            </table>
        </div>
    @endif

@endsection

{{--System Hints Page--}}
@section('modal_heading')
    <h1>Company Requisitions</h1>
@endsection
@section('modal_title')
    <h3><u>Dashboard Functionalities</u></h3>
    <b>
        <ol>
            <li>View all Types of Requisitions for the Company</li>
            <li>Filter through available Requisitions to Generate Reports</li>
            <li>Export Requisitions Report</li>
        </ol>
    </b>
@endsection
