<?= 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)) {
	$journal_id = !empty($journal_entry->journal_id) ? $journal_entry->journal_id : null;
	$reference_no = '';
	if (!empty($journal_entry)) {
		$reference_no = $journal_entry->reference_no;
	} else {
		if (empty(config_item('journal_entry_format'))) {
			$reference_no .= config_item('journal_entry_prefix');
		}
		if (config_item('increment_journal_entry') == 'FALSE') {
			$this->load->helper('string');
			$reference_no .= random_string('nozero', 6);
		} else {
			$reference_no .= $this->accounting_model->generate_journal_entry_prefix();
		}
	}
	$journal_date = !empty($journal_entry->date) ? $journal_entry->date : date('Y-m-d');
	$notes = !empty($journal_entry->notes) ? $journal_entry->notes : '';
	$chart_lookup_input_base = 'journal_account_lookup_';
	$chart_account_labels = array();
	if (!empty($chart_of_accounts)) {
		foreach ($chart_of_accounts as $chart_of_account) {
			$chart_account_labels[$chart_of_account->chart_of_account_id] = $chart_of_account->name;
		}
	}
	$render_chart_lookup = function ($selected_id = '', $selected_label = '', $input_id = '') {
		$input_id = $input_id ?: 'journal_account_lookup_' . uniqid();
		return '<div class="space-y-1" data-lookup="1" data-lookup-type="chart_of_account" data-lookup-min-length="0" data-lookup-limit="4">'
			. '<input type="hidden" name="account[]" 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('account')) . '" 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('account')) . '</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('journal_entry') ?></p>
					<h1 class="text-2xl font-semibold text-foreground"><?= !empty($journal_id) ? lang('edit') . ' ' . lang('journal_entry') : lang('new') . ' ' . lang('journal_entry') ?></h1>
					<p class="text-sm text-muted-foreground"><?= lang('manage') . ' ' . lang('journal_entry') ?></p>
				</div>
				<div class="flex flex-wrap items-center gap-2">
					<a href="<?= base_url('admin/accounting/journal_entry') ?>" 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('journal_entry') ?>
					</a>
				</div>
			</div>
		</div>

		<?= form_open(base_url('admin/accounting/save_journal_entry/' . $journal_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('journal_entry') . ' ' . 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('journal_entry_date'), $journal_date, true); ?>
					</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('account') . ' ' . lang('entries') ?></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('account') ?></th>
									<th class="px-3 py-2"><?= lang('description') ?></th>
									<th class="px-3 py-2 text-right"><?= lang('debit') ?></th>
									<th class="px-3 py-2 text-right"><?= lang('credit') ?></th>
									<th class="px-3 py-2"></th>
								</tr>
							</thead>
							<tbody id="journal_entry_items" class="divide-y divide-border">
								<?php
								$i = 1;
								if (!empty($journal_entry_items)) {
									foreach ($journal_entry_items as $journal_entry_item) {
										$selected_account_id = !empty($journal_entry_item->chart_of_account_id) ? $journal_entry_item->chart_of_account_id : '';
										$selected_account_label = !empty($selected_account_id) && isset($chart_account_labels[$selected_account_id]) ? $chart_account_labels[$selected_account_id] : '';
										?>
										<tr class="item-row">
											<td class="px-3 py-3 text-muted-foreground"><?= $i ?></td>
											<td class="px-3 py-3">
												<?= $render_chart_lookup($selected_account_id, $selected_account_label, $chart_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($journal_entry_item->description) ? $journal_entry_item->description : ''); ?>">
											</td>
											<td class="px-3 py-3">
												<input type="text" name="debit[]" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm text-right debit" value="<?= (!empty($journal_entry_item->debit) ? $journal_entry_item->debit : ''); ?>">
											</td>
											<td class="px-3 py-3">
												<input type="text" name="credit[]" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm text-right credit" value="<?= (!empty($journal_entry_item->credit) ? $journal_entry_item->credit : ''); ?>">
											</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_chart_lookup('', '', $chart_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="debit[]" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm text-right debit">
										</td>
										<td class="px-3 py-3">
											<input type="text" name="credit[]" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm text-right credit">
										</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="6" 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('totals') ?></h2>
					</div>
					<div class="space-y-2 text-sm">
						<div class="flex items-center justify-between" id="total_debit">
							<span class="text-muted-foreground"><?= lang('total_debit') ?></span>
							<span class="total_debit font-semibold text-foreground">0.00</span>
							<input type="hidden" name="total_debit" value="0.00">
						</div>
						<div class="flex items-center justify-between" id="total_credit">
							<span class="text-muted-foreground"><?= lang('total_credit') ?></span>
							<span class="total_credit font-semibold text-foreground">0.00</span>
							<input type="hidden" name="total_credit" value="0.00">
						</div>
						<div class="flex items-center justify-between" id="total_diff">
							<span class="text-muted-foreground"><?= lang('total_diff') ?></span>
							<span class="total_diff font-semibold text-foreground">0.00</span>
						</div>
					</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 buildJournalLookupCell(index) {
			return '' +
				'<div class="space-y-1" data-lookup="1" data-lookup-type="chart_of_account" data-lookup-min-length="0" data-lookup-limit="4">' +
				'<input type="hidden" name="account[]" value="" data-lookup-hidden>' +
				'<div class="relative">' +
				'<input id="<?= $chart_lookup_input_base ?>' + index + '" type="text" value="" autocomplete="off" placeholder="<?= html_escape(lang('search') . ' ' . lang('account')) ?>" 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('account')) ?></p>' +
				'</div>';
		}

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

		$(document).on('keyup', '.debit, .credit', function() {
			if (/\D/g.test(this.value)) {
				this.value = this.value.replace(/\D/g, '');
			}
			if ($(this).hasClass('debit')) {
				$(this).closest('tr').find('.credit').val(0);
			}
			if ($(this).hasClass('credit')) {
				$(this).closest('tr').find('.debit').val(0);
			}
		});

		function calculate_journal_entry() {
			var total_debit = 0;
			var total_credit = 0;
			var total_diff = 0;
			$('.item-row').each(function() {
				var debit = $(this).find('.debit').val();
				var credit = $(this).find('.credit').val();

				if (debit !== '') {
					total_debit += parseFloat(debit);
				}
				if (credit !== '') {
					total_credit += parseFloat(credit);
				}
			});
			total_diff = total_debit - total_credit;
			$('#total_debit .total_debit').html(total_debit.toFixed(2));
			$('#total_credit .total_credit').html(total_credit.toFixed(2));
			$('#total_diff .total_diff').html(total_diff.toFixed(2));
			$('input[name="total_debit"]').val(total_debit.toFixed(2));
			$('input[name="total_credit"]').val(total_credit.toFixed(2));

			if (total_diff === 0) {
				$('#file-save-button').prop('disabled', false);
				$('#total_diff').removeClass('text-rose-600');
			} else {
				$('#file-save-button').prop('disabled', true);
				$('#total_diff').addClass('text-rose-600');
			}
		}

		$(document).on('click', '#file-save-button', function(e) {
			if ($('input[name="total_debit"]').val() !== $('input[name="total_credit"]').val()) {
				e.preventDefault();
				toastr['error']('<?= lang('total_debit_credit_not_equal') ?>');
				$('#total_diff').addClass('text-rose-600');
			}
		});

		$(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">' +
				buildJournalLookupCell(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 debit_td = '<td class="px-3 py-3">' +
				'<input type="text" name="debit[]" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm text-right debit">' +
				'</td>';
			const credit_td = '<td class="px-3 py-3">' +
				'<input type="text" name="credit[]" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm text-right credit">' +
				'</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>';
			$('#journal_entry_items').append(row + serial_number_td + account_td + description_td + debit_td + credit_td + delete_td + end_tr);
			calculate_journal_entry();
			if (window.lucide) {
				window.lucide.createIcons();
			}
			if (window.initLookup) {
				window.initLookup(document.getElementById('journal_entry_items'));
			}
		});

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

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