@extends('backend.layout.main')

@section('content')
@if(session()->has('not_permitted'))
    <div class="alert alert-danger alert-dismissible text-center">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        {{ session()->get('not_permitted') }}
    </div>
@endif
@if(session()->has('message'))
    <div class="alert alert-success alert-dismissible text-center">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        {{ session()->get('message') }}
    </div>
@endif
@if($errors->any())
    <div class="alert alert-danger text-center">{{ $errors->first() }}</div>
@endif

<section>
    <div class="container-fluid">
        @if(in_array('suppliers-add', $all_permission))
            <a href="{{ route('supplier.create') }}" class="btn btn-info">
                <i class="dripicons-plus"></i> {{ trans('file.Add Supplier') }}
            </a>
        @endif
    </div>

    <div class="table-responsive">
        <table id="supplier-table" class="table">
            <thead>
                <tr>
                    <th class="not-exported"></th>
                    <th>{{ trans('file.Supplier Details') }}</th>
                    <th>{{ trans('file.Total Purchases') }}</th>
                    <th>{{ trans('file.Cash Paid') }}</th>
                    <th>{{ trans('file.Credit Used') }}</th>
                    <th>{{ trans('file.Total Settled') }}</th>
                    <th>{{ trans('file.Total Returned') }}</th>
                    <th>{{ trans('file.Supplier Credit') }}</th>
                    <th>{{ trans('file.Total Due') }}</th>
                    <th>{{ trans('file.Last Purchase Date') }}</th>
                    <th class="not-exported">{{ trans('file.action') }}</th>
                </tr>
            </thead>
            <tbody>
                @foreach($suppliers as $supplier)
                    @php $summary = $supplierSummaries->get($supplier->id); @endphp
                    <tr data-id="{{ $supplier->id }}">
                        <td>{{ $supplier->id }}</td>
                        <td>
                            <strong>{{ $supplier->name }}</strong>
                            <br>{{ $supplier->company_name }}
                            <br>{{ $supplier->phone_number }}
                            <br><small>{{ $supplier->address }}</small>
                        </td>
                        <td>{{ \App\Support\NumberFormatter::natural($summary['total_purchases']) }}</td>
                        <td>{{ \App\Support\NumberFormatter::natural($summary['cash_paid']) }}</td>
                        <td>{{ \App\Support\NumberFormatter::natural($summary['credit_used']) }}</td>
                        <td>{{ \App\Support\NumberFormatter::natural($summary['total_settled']) }}</td>
                        <td>{{ \App\Support\NumberFormatter::natural($summary['total_returned']) }}</td>
                        <td>{{ \App\Support\NumberFormatter::natural($summary['available_credit']) }}</td>
                        <td>
                            <strong class="{{ $summary['total_due'] > 0 ? 'text-danger' : 'text-success' }}">
                                {{ \App\Support\NumberFormatter::natural($summary['total_due']) }}
                            </strong>
                        </td>
                        <td data-order="{{ $summary['last_purchase_at'] ?: '' }}">
                            {{ $summary['last_purchase_at'] ? date(config('date_format'), strtotime($summary['last_purchase_at'])) : '-' }}
                        </td>
                        <td>
                            <div class="btn-group">
                                <button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown">
                                    {{ trans('file.action') }} <span class="caret"></span>
                                </button>
                                <ul class="dropdown-menu edit-options dropdown-menu-right dropdown-default">
                                    <li>
                                        <a href="{{ route('supplier.show', $supplier->id) }}" class="btn btn-link">
                                            <i class="dripicons-preview"></i> {{ trans('file.Supplier Statement') }}
                                        </a>
                                    </li>
                                    @if(in_array('suppliers-edit', $all_permission))
                                        <li>
                                            <a href="{{ route('supplier.edit', $supplier->id) }}" class="btn btn-link">
                                                <i class="dripicons-document-edit"></i> {{ trans('file.edit') }}
                                            </a>
                                        </li>
                                    @endif
                                    @if($canPaySuppliers && $summary['total_due'] > 0)
                                        <li>
                                            <button
                                                type="button"
                                                class="clear-due btn btn-link"
                                                data-toggle="modal"
                                                data-target="#clearDueModal"
                                                data-id="{{ $supplier->id }}"
                                                data-name="{{ $supplier->name }}"
                                                data-due="{{ $summary['total_due'] }}"
                                                data-credit="{{ $summary['available_credit'] }}"
                                            >
                                                <i class="dripicons-wallet"></i> {{ trans('file.Record Supplier Payment') }}
                                            </button>
                                        </li>
                                    @endif
                                    @if(in_array('suppliers-delete', $all_permission))
                                        <li class="divider"></li>
                                        <li>
                                            {{ Form::open(['route' => ['supplier.destroy', $supplier->id], 'method' => 'DELETE']) }}
                                                <button type="submit" class="btn btn-link" onclick="return confirmDelete()">
                                                    <i class="dripicons-trash"></i> {{ trans('file.delete') }}
                                                </button>
                                            {{ Form::close() }}
                                        </li>
                                    @endif
                                </ul>
                            </div>
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</section>

<div id="clearDueModal" tabindex="-1" role="dialog" aria-hidden="true" class="modal fade text-left">
    <div role="document" class="modal-dialog">
        <div class="modal-content">
            {!! Form::open(['route' => 'supplier.clearDue', 'method' => 'post', 'id' => 'supplier-payment-form']) !!}
            <div class="modal-header">
                <h5 class="modal-title">{{ trans('file.Record Supplier Payment') }}</h5>
                <button type="button" data-dismiss="modal" class="close">&times;</button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="supplier_id">
                <div class="row mb-3">
                    <div class="col-6">
                        <small>{{ trans('file.Supplier Name') }}</small>
                        <strong id="payment-supplier-name" class="d-block"></strong>
                    </div>
                    <div class="col-6">
                        <small>{{ trans('file.Current Due') }}</small>
                        <strong id="payment-current-due" class="d-block text-danger"></strong>
                    </div>
                    <div class="col-6 mt-3">
                        <small>{{ trans('file.Available Credit') }}</small>
                        <strong id="payment-available-credit" class="d-block"></strong>
                    </div>
                    <div class="col-6 mt-3">
                        <small>{{ trans('file.Main Cash Balance') }}</small>
                        <strong class="d-block">{{ \App\Support\NumberFormatter::natural($mainCashBalance) }}</strong>
                    </div>
                </div>
                <div class="form-group">
                    <label>{{ trans('file.Cash Payment') }}</label>
                    <input type="number" name="amount" min="0" step="0.01" class="form-control" value="0">
                </div>
                <div class="form-group">
                    <label>{{ trans('file.Use Supplier Credit') }}</label>
                    <input type="number" name="credit_amount" min="0" step="0.01" class="form-control" value="0">
                </div>
                <div class="form-group">
                    <label>{{ trans('file.Remaining Due After Payment') }}</label>
                    <input type="text" id="remaining-due" class="form-control" readonly>
                </div>
                <div class="form-group">
                    <label>{{ trans('file.Note') }}</label>
                    <textarea name="note" rows="3" class="form-control"></textarea>
                </div>
                <button type="submit" class="btn btn-primary">
                    <i class="dripicons-checkmark"></i> {{ trans('file.submit') }}
                </button>
            </div>
            {!! Form::close() !!}
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
    $("ul#people").siblings('a').attr('aria-expanded', 'true');
    $("ul#people").addClass('show');
    $("ul#people #supplier-list-menu").addClass('active');

    var currentDue = 0;
    var currentCredit = 0;

    function naturalNumber(value) {
        return Number(value || 0).toLocaleString(undefined, {maximumFractionDigits: 2});
    }

    function updateRemainingDue() {
        var cash = Number($("#clearDueModal input[name='amount']").val() || 0);
        var credit = Number($("#clearDueModal input[name='credit_amount']").val() || 0);
        $('#remaining-due').val(naturalNumber(Math.max(0, currentDue - cash - credit)));
    }

    $('.clear-due').on('click', function () {
        currentDue = Number($(this).data('due'));
        currentCredit = Number($(this).data('credit'));
        $("#clearDueModal input[name='supplier_id']").val($(this).data('id'));
        $("#clearDueModal input[name='amount']").val(0).attr('max', currentDue);
        $("#clearDueModal input[name='credit_amount']").val(0).attr('max', Math.min(currentCredit, currentDue));
        $('#payment-supplier-name').text($(this).data('name'));
        $('#payment-current-due').text(naturalNumber(currentDue));
        $('#payment-available-credit').text(naturalNumber(currentCredit));
        updateRemainingDue();
    });

    $("#clearDueModal input[name='amount'], #clearDueModal input[name='credit_amount']").on('input', updateRemainingDue);

    function confirmDelete() {
        return confirm(@json(trans('file.Are you sure you want to delete this supplier')));
    }

    var table = $('#supplier-table').DataTable({
        order: [[1, 'asc']],
        language: {
            lengthMenu: '_MENU_ {{ trans("file.records per page") }}',
            info: '<small>{{ trans("file.Showing") }} _START_ - _END_ (_TOTAL_)</small>',
            search: '{{ trans("file.Search") }}',
            paginate: {
                previous: '<i class="dripicons-chevron-left"></i>',
                next: '<i class="dripicons-chevron-right"></i>'
            }
        },
        columnDefs: [
            {orderable: false, targets: [0, 10]},
            {checkboxes: {selectRow: true}, targets: 0}
        ],
        select: {style: 'multi', selector: 'td:first-child'},
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, 'All']],
        dom: '<"row"lfB>rtip',
        buttons: [
            {extend: 'pdf', text: '<i class="fa fa-file-pdf-o"></i>', exportOptions: {columns: ':visible:Not(.not-exported)'}},
            {extend: 'excel', text: '<i class="dripicons-document-new"></i>', exportOptions: {columns: ':visible:Not(.not-exported)'}},
            {extend: 'print', text: '<i class="fa fa-print"></i>', exportOptions: {columns: ':visible:Not(.not-exported)'}},
            @if(in_array('suppliers-delete', $all_permission))
            {
                text: '<i class="dripicons-cross"></i>',
                className: 'buttons-delete',
                action: function () {
                    var ids = [];
                    table.rows({selected: true}).every(function () {
                        ids.push($(this.node()).data('id'));
                    });
                    if (!ids.length) {
                        alert(@json(trans('file.No supplier is selected')));
                        return;
                    }
                    if (!confirm(@json(trans('file.Are you sure you want to delete selected suppliers')))) {
                        return;
                    }
                    $.ajax({
                        type: 'POST',
                        url: '{{ url("supplier/deletebyselection") }}',
                        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                        data: {supplierIdArray: ids},
                        success: function (response) {
                            alert(response.message);
                            window.location.reload();
                        },
                        error: function (xhr) {
                            alert((xhr.responseJSON && xhr.responseJSON.message) || xhr.responseText);
                        }
                    });
                }
            },
            @endif
            {extend: 'colvis', text: '<i class="fa fa-eye"></i>', columns: ':gt(0)'}
        ]
    });
</script>
@endpush
