<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css"/>

<?php
$range_start = !empty($range[0]) ? $range[0] : date('Y-m-01');
$range_end = !empty($range[1]) ? $range[1] : date('Y-m-d');
$start_date = date('F d, Y', safe_strtotime($range_start));
$end_date = date('F d, Y', safe_strtotime($range_end));
?>
<div class="space-y-5">
	<div class="hidden-print rounded-2xl border border-border bg-background/60 p-4 shadow-sm">
		<div class="flex flex-col gap-2 border-b border-border pb-4 md:flex-row md:items-center md:justify-between">
			<div>
				<h3 class="text-lg font-semibold text-foreground"><?= lang('bank_reconciliation') ?></h3>
				<p class="text-sm text-muted-foreground"><?= lang('bank_reconciliation_intro') ?></p>
			</div>
			<span class="inline-flex rounded-full border border-border bg-background px-3 py-1 text-xs font-medium text-muted-foreground">
				<?= !empty($reconciliations) ? count($reconciliations) : 0 ?> <?= lang('records') ?>
			</span>
		</div>
		<?= form_open(base_url('admin/accounting/bank_reconciliation'), array('method' => 'get', 'class' => 'mt-4 grid grid-cols-1 gap-4 md:grid-cols-12 items-start')) ?>
			<div class="md:col-span-3">
				<?= form_lookup_group(
					'account_id',
					lang('account'),
					!empty($account_id) ? $account_id : '',
					!empty($account_label) ? $account_label : '',
					false,
					array('id' => 'bank_reconciliation_account_lookup'),
					'',
					array(
						'type' => 'account',
						'min_length' => 0,
						'placeholder' => lang('search') . ' ' . lang('account'),
					)
				) ?>
			</div>
			<div class="md:col-span-5">
				<label class="mb-1 block text-sm font-medium text-foreground"><?= lang('date_range') ?></label>
				<div class="sales-report-date-range relative flex w-full items-center gap-2 overflow-visible rounded-xl border border-border bg-card px-3 py-2 shadow-sm focus-within:border-primary">
					<i data-lucide="calendar-range" class="h-4 w-4 text-muted-foreground"></i>
					<input
						type="text"
						name="range"
						id="bank_reconciliation_range"
						value="<?= html_escape($start_date . ' - ' . $end_date) ?>"
						placeholder="<?= lang('select_date_range') ?>"
						readonly
						class="w-full border-0 bg-transparent p-0 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none">
				</div>
			</div>
			<div class="md:col-span-2 mt-6">
				<button type="submit" class="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:bg-primary/90">
					<i data-lucide="play" class="h-4 w-4"></i>
					<?= lang('run_report') ?>
				</button>
			</div>
		</form>
	</div>

	<div class="overflow-hidden rounded-2xl border border-border bg-card shadow-sm">
		<div class="overflow-x-auto">
			<table class="min-w-full text-sm">
			<thead class="border-b border-border text-xs uppercase tracking-wide text-muted-foreground">
				<tr>
					<th class="px-4 py-3 text-left"><?= lang('date') ?></th>
					<th class="px-4 py-3 text-left"><?= lang('account') ?></th>
					<th class="px-4 py-3 text-left"><?= lang('reference_no') ?></th>
					<th class="px-4 py-3 text-left"><?= lang('notes') ?></th>
					<th class="px-4 py-3 text-right"><?= lang('amount') ?></th>
					<th class="px-4 py-3 text-left"><?= lang('status') ?></th>
					<th class="px-4 py-3 text-right"><?= lang('action') ?></th>
				</tr>
			</thead>
			<tbody class="divide-y divide-border">
				<?php if (!empty($reconciliations)): foreach ($reconciliations as $row): ?>
					<tr class="hover:bg-muted/30">
						<td class="px-4 py-3 text-muted-foreground"><?= display_date($row->statement_date) ?></td>
						<td class="px-4 py-3 font-medium text-foreground"><?= html_escape($row->account_name) ?></td>
						<td class="px-4 py-3 text-muted-foreground">
							<?php if (!empty($row->journal_id)): ?>
								<a href="<?= base_url('admin/accounting/view_journal_entry/' . $row->journal_id) ?>" class="text-primary hover:underline"><?= html_escape($row->reference_no) ?></a>
							<?php else: ?>
								<?= html_escape($row->statement_reference) ?>
							<?php endif; ?>
						</td>
						<td class="px-4 py-3 text-muted-foreground"><?= html_escape($row->statement_description) ?></td>
						<td class="px-4 py-3 text-right font-medium text-foreground"><?= display_money($row->statement_amount, default_currency()) ?></td>
						<td class="px-4 py-3">
							<?php if ($row->status === 'matched'): ?>
								<span class="label label-success"><?= lang('matched') ?></span>
							<?php elseif ($row->status === 'unmatched'): ?>
								<span class="label label-warning"><?= lang('unmatched') ?></span>
							<?php else: ?>
								<span class="label label-default"><?= html_escape($row->status) ?></span>
							<?php endif; ?>
						</td>
						<td class="px-4 py-3 text-right">
							<?php if (!empty($row->journal_id)): ?>
								<a class="btn btn-xs btn-primary" href="<?= base_url('admin/accounting/view_journal_entry/' . $row->journal_id) ?>"><?= lang('view') ?></a>
							<?php endif; ?>
						</td>
					</tr>
					<?php endforeach; else: ?>
						<tr><td colspan="7" class="px-4 py-8 text-center text-muted-foreground"><?= lang('nothing_to_display') ?></td></tr>
				<?php endif; ?>
			</tbody>
			</table>
		</div>
	</div>
</div>

<script type="text/javascript">
	var bankReconciliationRangeInput = $('#bank_reconciliation_range');
	var bankReconciliationRangeValue = bankReconciliationRangeInput.val();
	var bankReconciliationWrap = $('.sales-report-date-range');
	var bankReconciliationPicker = null;

	function positionBankReconciliationDateRangePicker() {
		if (!bankReconciliationPicker || !bankReconciliationPicker.container || !bankReconciliationPicker.container.length) {
			return;
		}
		var offset = bankReconciliationWrap.offset();
		if (!offset) {
			return;
		}
		var pickerNode = bankReconciliationPicker.container.get(0);
		pickerNode.style.setProperty('position', 'absolute', 'important');
		pickerNode.style.setProperty('left', offset.left + 'px', 'important');
		pickerNode.style.setProperty('right', 'auto', 'important');
		pickerNode.style.setProperty('top', (offset.top + bankReconciliationWrap.outerHeight() + 10) + 'px', 'important');
		pickerNode.style.setProperty('min-width', bankReconciliationPicker.container.hasClass('show-calendar') ? '680px' : '220px', 'important');
		pickerNode.style.setProperty('max-width', 'calc(100vw - ' + (offset.left + 24) + 'px)', 'important');
	}

	function initBankReconciliationDateRangePicker() {
		if (bankReconciliationPicker) {
			return bankReconciliationPicker;
		}
		bankReconciliationRangeInput.daterangepicker({
			autoUpdateInput: true,
			locale: {
				format: 'MMMM D, YYYY',
				applyLabel: <?= json_encode(lang('apply')) ?>,
				cancelLabel: <?= json_encode(lang('cancel')) ?>,
				fromLabel: <?= json_encode(lang('from')) ?>,
				toLabel: <?= json_encode(lang('to')) ?>,
				customRangeLabel: <?= json_encode(lang('custom_range')) ?>
			},
			startDate: '<?= html_escape($start_date) ?>',
			endDate: '<?= html_escape($end_date) ?>',
			drops: 'down',
			opens: 'right',
			ranges: {
				<?= json_encode(lang('today')) ?>: [moment(), moment()],
				<?= json_encode(lang('yesterday')) ?>: [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
				<?= json_encode(lang('last_7_days')) ?>: [moment().subtract(6, 'days'), moment()],
				<?= json_encode(lang('last_30_days')) ?>: [moment().subtract(29, 'days'), moment()],
				<?= json_encode(lang('this_month')) ?>: [moment().startOf('month'), moment().endOf('month')],
				<?= json_encode(lang('last_month')) ?>: [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
			}
		});

		bankReconciliationPicker = bankReconciliationRangeInput.data('daterangepicker');
		bankReconciliationRangeInput.off('click.daterangepicker focus.daterangepicker keyup.daterangepicker');
		if (bankReconciliationPicker && bankReconciliationRangeValue) {
			var bankRangeParts = bankReconciliationRangeValue.split(' - ');
			if (bankRangeParts.length === 2) {
				var bankStart = moment(bankRangeParts[0], 'MMMM D, YYYY', true);
				var bankEnd = moment(bankRangeParts[1], 'MMMM D, YYYY', true);
				if (bankStart.isValid() && bankEnd.isValid()) {
					bankReconciliationPicker.setStartDate(bankStart);
					bankReconciliationPicker.setEndDate(bankEnd);
					bankReconciliationPicker.updateView();
					bankReconciliationPicker.updateCalendars();
				}
			}
		}
		bankReconciliationPicker.hide();
		bankReconciliationPicker.container.hide();
		bankReconciliationPicker.container.on('click', '.ranges li', function () {
			window.setTimeout(positionBankReconciliationDateRangePicker, 0);
		});
		positionBankReconciliationDateRangePicker();
		return bankReconciliationPicker;
	}

	if (typeof moment !== 'undefined' && typeof bankReconciliationRangeInput.daterangepicker === 'function') {
		if (bankReconciliationWrap.length) {
			bankReconciliationWrap.on('click', function () {
				var picker = initBankReconciliationDateRangePicker();
				if (picker) {
					positionBankReconciliationDateRangePicker();
					picker.show();
				}
			});
			$(document).on('mousedown', function (event) {
				if ($(event.target).closest('.daterangepicker').length) {
					return;
				}
				if (bankReconciliationPicker && !bankReconciliationWrap.is(event.target) && bankReconciliationWrap.has(event.target).length === 0) {
					bankReconciliationPicker.hide();
				}
			});
		}

		bankReconciliationRangeInput.on('show.daterangepicker', function () {
			if (bankReconciliationPicker) {
				positionBankReconciliationDateRangePicker();
				bankReconciliationPicker.updateCalendars();
			}
		});

		bankReconciliationRangeInput.on('apply.daterangepicker', function (ev, picker) {
			bankReconciliationRangeValue = picker.startDate.format('MMMM D, YYYY') + ' - ' + picker.endDate.format('MMMM D, YYYY');
			$(this).val(bankReconciliationRangeValue);
		});

		bankReconciliationRangeInput.on('cancel.daterangepicker', function () {
			$(this).val(bankReconciliationRangeValue || '');
			if (bankReconciliationPicker && bankReconciliationRangeValue) {
				var restoredRangeParts = bankReconciliationRangeValue.split(' - ');
				if (restoredRangeParts.length === 2) {
					var restoredStartDate = moment(restoredRangeParts[0], 'MMMM D, YYYY', true);
					var restoredEndDate = moment(restoredRangeParts[1], 'MMMM D, YYYY', true);
					if (restoredStartDate.isValid() && restoredEndDate.isValid()) {
						bankReconciliationPicker.setStartDate(restoredStartDate);
						bankReconciliationPicker.setEndDate(restoredEndDate);
					}
				}
				bankReconciliationPicker.updateView();
				bankReconciliationPicker.updateCalendars();
			}
		});
	}
</script>
