<?= message_box('success'); ?>
<?= message_box('error'); ?>

<?php
$created = can_action_by_label('chart_of_accounts', 'created');
$edited = can_action_by_label('chart_of_accounts', 'edited');
if (!empty($created) || !empty($edited)) {
	$voucher_id = !empty($receipt_voucher->voucher_id) ? $receipt_voucher->voucher_id : null;
	$reference_no = '';
	if (!empty($receipt_voucher)) {
		$reference_no = $receipt_voucher->reference_no;
	} else {
		if (empty(config_item('receipt_voucher_format'))) {
			$reference_no .= config_item('receipt_voucher_prefix');
		}
		if (config_item('increment_receipt_voucher') == 'FALSE') {
			$this->load->helper('string');
			$reference_no .= random_string('nozero', 6);
		} else {
			$reference_no .= $this->accounting_model->generate_receipt_voucher_prefix();
		}
	}
	$voucher_date = !empty($receipt_voucher->date) ? $receipt_voucher->date : date('Y-m-d');
	$notes = !empty($receipt_voucher->notes) ? $receipt_voucher->notes : '';
	$account_selected = !empty($receipt_voucher->account_id) ? $receipt_voucher->account_id : '';
	$selected_account_label = !empty($account_selected) && !empty($accounts[$account_selected]) ? $accounts[$account_selected] : '';
	$client_lookup_input_base = 'receipt_client_lookup_';
	$client_labels = array();
	if (!empty($clients)) {
		foreach ($clients as $client_id => $client_name) {
			if (!empty($client_id)) {
				$client_labels[$client_id] = $client_name;
			}
		}
	}
	$render_client_lookup = function ($selected_id = '', $selected_label = '', $input_id = '') {
		$input_id = $input_id ?: 'receipt_client_lookup_' . uniqid();
		return '<div class="space-y-1" data-lookup="1" data-lookup-type="client" data-lookup-min-length="0" data-lookup-limit="4">'
			. '<input type="hidden" name="supplier_client_id[]" value="' . html_escape($selected_id) . '" data-lookup-hidden>'
			. '<div class="relative">'
			. '<input id="' . html_escape($input_id) . '" type="text" value="' . html_escape($selected_label) . '" autocomplete="off" placeholder="' . html_escape(lang('search') . ' ' . lang('client')) . '" class="w-full rounded-lg border border-border bg-input px-3 py-2 pr-10 text-sm dark:focus:border-secondary dark:focus:ring-3 dark:focus:ring-secondary/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-secondary/30" data-lookup-input="1">'
			. '<button type="button" class="absolute right-2 top-1/2 hidden -translate-y-1/2 rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground" data-lookup-clear tabindex="-1"><i data-lucide="x" class="h-4 w-4"></i></button>'
			. '<div class="absolute z-30 mt-1 hidden max-h-56 w-full overflow-y-auto rounded-lg border border-border bg-card shadow-lg" data-lookup-results></div>'
			. '</div>'
			. '<p class="hidden text-xs text-rose-500" data-lookup-status>' . html_escape(lang('search') . ' ' . lang('client')) . '</p>'
			. '</div>';
	};
	?>

	<div class="space-y-6">
		<div class="rounded-2xl border border-border bg-card p-6 shadow-sm">
			<div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
				<div>
					<p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('receipt_voucher') ?></p>
					<h1 class="text-2xl font-semibold text-foreground"><?= !empty($voucher_id) ? lang('edit') . ' ' . lang('receipt_voucher') : lang('new') . ' ' . lang('receipt_voucher') ?></h1>
					<p class="text-sm text-muted-foreground"><?= lang('manage') . ' ' . lang('receipt_voucher') ?></p>
				</div>
				<div class="flex flex-wrap items-center gap-2">
					<a href="<?= base_url('admin/accounting/' . $active) ?>" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium text-foreground hover:bg-muted">
						<i data-lucide="list" class="h-4 w-4"></i>
						<?= lang($active) ?>
					</a>
				</div>
			</div>
		</div>

		<?= form_open(base_url('admin/accounting/save_receipt_voucher/' . $voucher_id), array('class' => 'space-y-6', 'data-parsley-validate' => '', 'novalidate' => '', 'enctype' => 'multipart/form-data')); ?>
		<div class="grid grid-cols-1 xl:grid-cols-12 gap-6">
			<div class="xl:col-span-8 space-y-6">
				<div class="rounded-xl border border-border bg-card p-6 space-y-5">
					<div class="flex items-center gap-2 text-sm font-semibold text-foreground border-b border-border pb-3">
						<i data-lucide="file-text" class="h-5 w-5"></i>
						<h2 class="text-base font-semibold text-foreground"><?= lang('receipt_voucher') . ' ' . lang('details') ?></h2>
					</div>
					<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
						<?= form_input_group('reference_no', lang('reference_no'), $reference_no, 'text', true); ?>
						<?= form_datepicker('date', lang('date'), $voucher_date, true); ?>
						<?= form_lookup_group('account_id', lang('paid_from'), $account_selected, $selected_account_label, true, array(), '', array('type' => 'account', 'min_length' => 0, 'placeholder' => lang('search') . ' ' . lang('account'))); ?>
					</div>
					<?= form_textarea_group('notes', lang('notes'), $notes, 4, false); ?>
				</div>

				<div class="rounded-xl border border-border bg-card p-6 space-y-4">
					<div class="flex items-center gap-2 text-sm font-semibold text-foreground">
						<i data-lucide="layers" class="h-5 w-5"></i>
						<h2 class="text-base font-semibold text-foreground"><?= lang('items') ?></h2>
					</div>
					<div class="table-responsive">
						<table class="table w-full text-sm">
							<thead class="bg-muted/40 text-xs uppercase tracking-wide text-muted-foreground">
								<tr>
									<th class="px-3 py-2">#</th>
									<th class="px-3 py-2"><?= lang('client') ?></th>
									<th class="px-3 py-2"><?= lang('description') ?></th>
									<th class="px-3 py-2 text-right"><?= lang('amount') ?></th>
									<th class="px-3 py-2"></th>
								</tr>
							</thead>
							<tbody id="receipt_voucher_items" class="divide-y divide-border">
								<?php
								$i = 1;
								if (!empty($receipt_voucher_items)) {
									foreach ($receipt_voucher_items as $receipt_voucher_item) {
										$selected_client_id = !empty($receipt_voucher_item->supplier_client_id) ? $receipt_voucher_item->supplier_client_id : '';
										$selected_client_label = !empty($selected_client_id) && isset($client_labels[$selected_client_id]) ? $client_labels[$selected_client_id] : '';
										?>
										<tr class="item-row">
											<td class="px-3 py-3 text-muted-foreground"><?= $i ?></td>
											<td class="px-3 py-3">
												<?= $render_client_lookup($selected_client_id, $selected_client_label, $client_lookup_input_base . $i); ?>
											</td>
											<td class="px-3 py-3">
												<input type="text" name="description[]" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm description" value="<?= (!empty($receipt_voucher_item->description) ? $receipt_voucher_item->description : ''); ?>">
											</td>
											<td class="px-3 py-3">
												<input type="text" name="amount[]" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm text-right amount" value="<?= (!empty($receipt_voucher_item->amount) ? $receipt_voucher_item->amount : ''); ?>">
											</td>
											<td class="px-3 py-3 text-right">
												<button type="button" class="delete-row inline-flex items-center justify-center rounded-lg border border-rose-200 bg-rose-50 p-2 text-rose-600 hover:bg-rose-100">
													<i data-lucide="trash-2" class="h-4 w-4"></i>
												</button>
											</td>
										</tr>
										<?php
										$i++;
									}
								} else { ?>
									<tr class="item-row">
										<td class="px-3 py-3 text-muted-foreground"><?= $i ?></td>
										<td class="px-3 py-3">
											<?= $render_client_lookup('', '', $client_lookup_input_base . $i); ?>
										</td>
										<td class="px-3 py-3">
											<input type="text" name="description[]" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm description">
										</td>
										<td class="px-3 py-3">
											<input type="text" name="amount[]" required class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm text-right amount">
										</td>
										<td class="px-3 py-3 text-right">
											<button type="button" class="delete-row inline-flex items-center justify-center rounded-lg border border-rose-200 bg-rose-50 p-2 text-rose-600 hover:bg-rose-100">
												<i data-lucide="trash-2" class="h-4 w-4"></i>
											</button>
										</td>
									</tr>
								<?php } ?>
							</tbody>
							<tfoot>
								<tr>
									<td colspan="5" class="px-3 py-3">
										<div class="flex flex-wrap items-center justify-between gap-2">
											<button type="button" class="add-row inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted">
												<i data-lucide="plus" class="h-4 w-4"></i>
												<?= lang('add_row') ?>
											</button>
											<button type="button" class="add-row inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted">
												<i data-lucide="plus" class="h-4 w-4"></i>
												<?= lang('add_row') ?>
											</button>
										</div>
									</td>
								</tr>
							</tfoot>
						</table>
					</div>
				</div>
			</div>

			<aside class="xl:col-span-4 space-y-6">
				<div class="rounded-xl border border-border bg-card p-6 space-y-3">
					<div class="flex items-center gap-2 text-sm font-semibold text-foreground border-b border-border pb-2">
						<i data-lucide="calculator" class="h-5 w-5"></i>
						<h2 class="text-base font-semibold text-foreground"><?= lang('total') ?></h2>
					</div>
					<div class="flex items-center justify-between text-sm" id="total_amount">
						<span class="text-muted-foreground"><?= lang('total_amount') ?></span>
						<span class="total_amount font-semibold text-foreground">0.00</span>
						<input type="hidden" name="total_amount" value="0.00">
					</div>
				</div>
			</aside>
		</div>

		<div class="flex flex-wrap justify-end gap-3">
			<button type="submit" id="file-save-button" class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500">
				<i data-lucide="check" class="h-4 w-4"></i>
				<?= lang('save') ?>
			</button>
		</div>
		<?= form_close(); ?>
	</div>

	<script>
		function buildReceiptClientLookupCell(index) {
			return '' +
				'<div class="space-y-1" data-lookup="1" data-lookup-type="client" data-lookup-min-length="0" data-lookup-limit="4">' +
				'<input type="hidden" name="supplier_client_id[]" value="" data-lookup-hidden>' +
				'<div class="relative">' +
				'<input id="<?= $client_lookup_input_base ?>' + index + '" type="text" value="" autocomplete="off" placeholder="<?= html_escape(lang('search') . ' ' . lang('client')) ?>" class="w-full rounded-lg border border-border bg-input px-3 py-2 pr-10 text-sm dark:focus:border-secondary dark:focus:ring-3 dark:focus:ring-secondary/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-secondary/30" data-lookup-input="1">' +
				'<button type="button" class="absolute right-2 top-1/2 hidden -translate-y-1/2 rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground" data-lookup-clear tabindex="-1"><i data-lucide="x" class="h-4 w-4"></i></button>' +
				'<div class="absolute z-30 mt-1 hidden max-h-56 w-full overflow-y-auto rounded-lg border border-border bg-card shadow-lg" data-lookup-results></div>' +
				'</div>' +
				'<p class="hidden text-xs text-rose-500" data-lookup-status><?= html_escape(lang('search') . ' ' . lang('client')) ?></p>' +
				'</div>';
		}

		$(document).on("change blur keyup", function() {
			calculate_receipt_voucher();
		});

		$(document).on('keyup', '.amount', function() {
			if (/\D/g.test(this.value)) {
				this.value = this.value.replace(/\D/g, '');
			}
		});

		function calculate_receipt_voucher() {
			var total_amount = 0;
			$('.item-row').each(function() {
				var amount = $(this).find('.amount').val();

				if (amount !== '') {
					total_amount += parseFloat(amount);
				}
			});
			$('#total_amount .total_amount').html(total_amount.toFixed(2));
			$('input[name="total_amount"]').val(total_amount.toFixed(2));

			if (total_amount > 0) {
				$('#file-save-button').attr('disabled', false);
			} else {
				$('#file-save-button').attr('disabled', true);
			}
		}

		$(document).on('click', '.add-row', function(e) {
			e.preventDefault();
			const row = '<tr class="item-row">';
			const rowIndex = $('.item-row').length + 1;
			const serial_number_td = '<td class="px-3 py-3 text-muted-foreground">' + rowIndex + '</td>';
			const account_td = '<td class="px-3 py-3">' +
				buildReceiptClientLookupCell(rowIndex) +
				'</td>';
			const description_td = '<td class="px-3 py-3">' +
				'<input type="text" name="description[]" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm description">' +
				'</td>';
			const amount_td = '<td class="px-3 py-3">' +
				'<input type="text" name="amount[]" required class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm text-right amount">' +
				'</td>';
			const delete_td = '<td class="px-3 py-3 text-right">' +
				'<button type="button" class="delete-row inline-flex items-center justify-center rounded-lg border border-rose-200 bg-rose-50 p-2 text-rose-600 hover:bg-rose-100">' +
				'<i data-lucide="trash-2" class="h-4 w-4"></i>' +
				'</button>' +
				'</td>';
			const end_tr = '</tr>';
			$('#receipt_voucher_items').append(row + serial_number_td + account_td + description_td + amount_td + delete_td + end_tr);
			calculate_receipt_voucher();
			if (window.lucide) {
				window.lucide.createIcons();
			}
			if (window.initLookup) {
				window.initLookup(document.getElementById('receipt_voucher_items'));
			}
		});

		$(document).on('click', '.delete-row', function(e) {
			e.preventDefault();
			if ($('.item-row').length > 1) {
				$(this).closest('tr').remove();
				calculate_receipt_voucher();
			}
		});

		$(document).ready(function() {
			calculate_receipt_voucher();
			if (window.initLookup) {
				window.initLookup(document);
			}
		});
	</script>
<?php } ?>
