@extends('adminlte::layouts.app')

@section('htmlheader_title')
	Payment
@endsection
@section('page_title')
	Payment
@endsection

@section('contentheader_title')
	Record Payment
@endsection
@section('contentheader_description')
@endsection

@section('main-content')
	<div class="row">
		<div class="col-6">
			<div class="card card-dark">
				<div class="card-header">
					<h1 class="card-title">Record Payment</h1>
					@if(session()->has('success'))
						<span class="ml-3 pt-0 pb-0 pr-1 pl-1 btn btn-outline-success"><small>{{ session()->get('success') }}</small></span>
					@endif
				</div>

				<div class="card-body">
					<form class="g-0 needs-validation" method="POST" role="form">
						@csrf

						<div class="row">
							<!-- DATE RECEIVED -->
							<div class="col-4">
								<div class="form-group has-validation">
									<label for="paid_at">Date Received</label>
									<div class="input-group">
										<div class="input-group-prepend">
											<span class="input-group-text"><i class="fas fa-fw fa-calendar"></i></span>
										</div>
										<input type="date" class="form-control @error('paid_at') is-invalid @enderror" id="paid_at" name="paid_at" value="{{ old('paid_at',($o->exists ? $o->paid_at : \Carbon\Carbon::now())->format('Y-m-d')) }}" required>
										<span class="invalid-feedback" role="alert">
											@error('paid_at')
												{{ $message }}
											@else
												Payment Date is required.
											@enderror
										</span>
									</div>
									<span class="input-helper">Date Payment Received.</span>
								</div>
							</div>

							<!-- AMOUNT -->
							<div class="offset-4 col-4">
								<div class="form-group has-validation">
									<label for="total_amt">Amount</label>
									<div class="input-group">
										<div class="input-group-prepend">
											<span class="input-group-text"><i class="fas fa-fw fa-dollar-sign"></i></span>
										</div>
										<input type="text" class="text-right form-control @error('total_amt') is-invalid @enderror" id="total_amt" name="total_amt" value="{{ number_format(old('total_amt',$o->exists ? $o->total_amt : 0),2) }}" required>
										<span class="invalid-feedback" role="alert">
											@error('total_amt')
												{{ $message }}
											@else
												Payment Amount is required.
											@enderror
										</span>
									</div>
									<span class="input-helper">Amount Received.</span>
								</div>
							</div>
						</div>

						<div class="row">
							<!-- METHOD -->
							<div class="col-4">
								<div class="form-group has-validation">
									<label for="checkout_id">Payment Method</label>
									<div class="input-group">
										<div class="input-group-prepend">
											<span class="input-group-text"><i class="fas fa-fw fa-dollar-sign"></i></span>
										</div>
										<select class="form-control @error('checkout_id') is-invalid @enderror" id="checkout_id" name="checkout_id" required>
											<option value=""></option>
											@foreach (\App\Models\Checkout::orderBy('name')->get() as $co)
												<option value="{{ $co->id }}" {{ $co->id == old('checkout_id',$o->exists ? $o->checkout_id : NULL) ? 'selected' : '' }}>{{ $co->name }}</option>
											@endforeach
										</select>
										<span class="invalid-feedback" role="alert">
											@error('checkout_id')
												{{ $message }}
											@else
												Payment Method is required.
											@enderror
										</span>
									</div>
									<span class="input-helper">Payment Method.</span>
								</div>
							</div>

							<!-- PAYMENT FEE -->
							<div class="offset-4 col-4">
								<div class="form-group has-validation">
									<label for="fees_amt">Fee</label>
									<div class="input-group">
										<div class="input-group-prepend">
											<span class="input-group-text"><i class="fas fa-fw fa-dollar-sign"></i></span>
										</div>
										<input type="text" class="text-right form-control @error('fees_amt') is-invalid @enderror" id="fees_amt" name="fees_amt" value="{{ number_format(old('fees_amt',$o->exists ? $o->fees_amt : 0),2) }}">
										<span class="invalid-feedback" role="alert">
											@error('fees_amt')
												{{ $message }}
											@else
												Total Fees is required.
											@enderror
										</span>
									</div>
									<span class="input-helper">Amount Received.</span>
								</div>
							</div>
						</div>

						<div class="row">
							<!-- ACCOUNT -->
							<div class="col-6">
								<div class="form-group has-validation">
									<label for="account_id">Account</label>
									<div class="input-group">
										<div class="input-group-prepend">
											<span class="input-group-text"><i class="fas fa-fw fa-user"></i></span>
										</div>
										<!-- @todo Only show active accounts or accounts with outstanding invoices -->
										<select class="form-control @error('account_id') is-invalid @enderror" id="account_id" name="account_id" required>
											<option value=""></option>
											@foreach (\App\Models\Account::active()->with(['user'])->get()->sortBy('name') as $ao)
												<option value="{{ $ao->id }}" {{ $ao->id == old('account_id',$o->exists ? $o->account_id : NULL) ? 'selected' : '' }}>{{ $ao->name }}</option>
											@endforeach
										</select>

										<span class="invalid-feedback" role="alert">
											@error('account_id')
											{{ $message }}
											@else
												Account is required.
												@enderror
										</span>
									</div>
									<span class="input-helper">Account to add payment to.</span>
									<i class="fas fa-spinner d-none"></i>
								</div>
							</div>

							<!-- BALANCE -->
							<div class="offset-2 col-4">
								<label for="fees_amt">Balance</label>
								<div class="input-group">
									<div class="input-group-prepend">
										<span class="input-group-text"><i class="fas fa-fw fa-dollar-sign"></i></span>
									</div>
									<input type="text" class="text-right form-control @error('fees_amt') is-invalid @enderror" id="balance" value="{{ number_format($o->exists ? $o->balance : 0,2) }}" disabled>
								</div>
							</div>
						</div>

						<div class="row mt-3 mb-3">
							<div class="col-12">
								<div id="invoices"></div>
								@error('invoices')
									<span class="invalid-feedback d-block mt-2 mb-2" role="alert">
										{{ $message }}
									</span>
								@enderror
							</div>
						</div>

						<div class="row">
							<div class="col-12">
								<a href="{{ url('/home') }}" class="btn btn-danger">Cancel</a>
								@can('wholesaler')
									<button type="submit" name="submit" class="btn btn-success mr-0 float-right">@if ($site->exists)Save @else Add @endif</button>
								@endcan
							</div>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
@endsection

@section('page-scripts')
	@css(select2)
	@js(select2,autofocus)

	<script type="text/javascript">
		function populate(account,spinner) {
			spinner.toggleClass('d-none').toggleClass('fa-spin');

			$.ajax({
				type: 'POST',
				dataType: 'html',
				cache: false,
				url: '{{ url('api/r/invoices') }}'+'/'+account,
				data: {pid:{{ $o->id ?: 'null' }}},
				timeout: 2000,
				error: function(x) {
					spinner.toggleClass('d-none').toggleClass('fa-spin');
					alert('Failed to submit');
				},
				success: function(data) {
					spinner.toggleClass('d-none').toggleClass('fa-spin');
					$("div[id=invoices]").empty().append(data);
				}
			});
		}

		function balance() {
			var alloc = 0;

			$('.invoice').each(function() {
				alloc += parseFloat($(this).val());
			})

			$('#balance').val(($('#total_amt').val()-alloc).toFixed(2))
		}

		$(document).ready(function() {
			if ($('#account_id').val()) {
				var spinner = $('#account_id').parent().parent().find('i.fas.fa-spinner');

				populate($('#account_id').val(),spinner);
			}

			$('#account_id').select2({
				sorter: data => data.sort((a, b) => a.text.localeCompare(b.text)),
			})
				.on('change',function(e) {
					if (! $(this).val()) {
						$("div[id=invoices]").empty();
						return;
					}

					var spinner = $(this).parent().parent().find('i.fas.fa-spinner');

					populate($(this).val(),spinner);
				});

			$('#total_amt').on('change',balance);
		});

		$(document).on('change','.invoice',balance);
	</script>
@append
