<!-- $po=Payment::class -->

@use(Carbon\Carbon)
@use(App\Models\Account)
@use(App\Models\Checkout)

@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="card card-dark">
		<div class="card-body">
			<form method="POST" action="{{ url('r/payment',$po?->id ?? '') }}">
				@csrf

				<x-leenooks::button.success class="float-right" row="true"/>
				<div class="row">
					<div class="col-12 col-sm-6 col-lg-3">
						<div class="row">
							<div class="col-12 col-md-9 col-lg-12">
								<!-- Account -->
								<!-- @todo Only show active accounts or accounts with outstanding invoices -->
								<x-leenooks::form.select name="account_id" icon="fa-user" label="Account" feedback="Sweep Type is required" helper="Account to add payment to." :options="Account::active()->with(['user'])->get()->sortBy('name')->map(fn($item,$key)=>['id'=>$item->id,'value'=>$item->name])" :value="$po?->account_id ?? ''"/>
							</div>
						</div>

						<div class="row">
							<div class="col-12 col-md-9 col-lg-12">
								<!-- Received -->
								<x-leenooks::form.date name="paid_at" icon="fa-calendar" label="Date Received" feedback="Payment Date is required" helper="Date payment received" :value="($po?->paid_at ?? Carbon::now())->format('Y-m-d')"/>
							</div>
						</div>

						<!-- METHOD -->
						<div class="row">
							<div class="col-12 col-md-9 col-lg-12">
								<x-leenooks::form.select name="checkout_id" icon="fa-dollar-sign" label="Payment Method" :options="Checkout::orderBy('name')->get()->map(fn($item,$key)=>['id'=>$item->id,'value'=>$item->name])" :value="$po?->checkout_id ?? ''"/>
							</div>
						</div>
					</div>

					<div class="col-12 col-sm-6 col-log-3">
						<div class="row">
							<div class="col-12 col-md-6">
								<!-- Amount -->
								<x-leenooks::form.text class="text-right" id="total_amt" name="total_amt" icon="fa-dollar-sign" label="Amount" helper="Amount received" :value="$po?->total_amt ?? 0"/>
							</div>
						</div>

						<div class="row">
							<div class="col-12 col-md-6">
								<!-- Payment Fee -->
								<x-leenooks::form.text class="text-right" id="fees_amt" name="fees_amt" icon="fa-dollar-sign" label="Fee" helper="Payment fees" :value="$po?->fees_amt ?? ''"/>
							</div>
						</div>

						<div class="row">
							<div class="col-12 col-md-6">
								<!-- Balance -->
								<x-leenooks::form.text class="text-right" id="balance" name="balance" icon="fa-dollar-sign" label="Balance" helper="Payment unallocated" :value="$po?->total ?? 0" disabled/>
							</div>
						</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">
								{{ $message }}
							</span>
						@enderror
					</div>
				</div>

				<div class="row">
					<!-- Buttons -->
					<div class="col">
						<x-leenooks::button.cancel/>
						<x-leenooks::button.submit class="float-right">@if($po?->exists ?? FALSE)Update @else Add @endif</x-leenooks::button.submit>
					</div>
				</div>
			</form>
		</div>
	</div>

	<x-leenooks::errors/>
@endsection

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

			$.ajax({
				type: 'POST',
				dataType: 'html',
				cache: false,
				url: '{{ url('r/account/invoices') }}',
				data: {
					aid: account,
					pid: {{ $po?->id ?? 'null' }},
					errors: {!! $errors !!},
					old: {!! json_encode(old()) !!}
				},
				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;

			$('input[id^=invoices_]').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','input[id^=invoices_]',balance);
	</script>
@append