<?php
$sidebar_mode = !empty($sidebar_mode) ? $sidebar_mode : 'payment';
$selected_invoice_id = !empty($selected_invoice_id) ? (int) $selected_invoice_id : 0;
$sidebar_page = !empty($sidebar_page) ? (int) $sidebar_page : 1;
$sidebar_pages = !empty($sidebar_pages) ? (int) $sidebar_pages : 1;
$sidebar_total = isset($sidebar_total) ? (int) $sidebar_total : 0;
$sidebar_search = isset($sidebar_search) ? (string) $sidebar_search : '';
$sidebar_invoices = !empty($sidebar_invoices) ? $sidebar_invoices : array();
$sidebar_selected_invoice = !empty($sidebar_selected_invoice) ? $sidebar_selected_invoice : null;
$sidebar_endpoint = base_url('admin/invoice/invoice_sidebar/' . $sidebar_mode . '/' . $selected_invoice_id);
$sidebar_base_path = base_url('admin/invoice/manage_invoice/' . $sidebar_mode . '/');
$sidebar_page_url = $sidebar_base_path . $selected_invoice_id;

$sidebar_query_args = array();
if ($sidebar_search !== '') {
    $sidebar_query_args['q'] = $sidebar_search;
}
if ($sidebar_page > 1) {
    $sidebar_query_args['page'] = $sidebar_page;
}
$sidebar_query_suffix = !empty($sidebar_query_args) ? '?' . http_build_query($sidebar_query_args) : '';
$render_sidebar_invoice_card = function ($invoice_row, $is_current = false) use ($sidebar_mode, $sidebar_base_path, $sidebar_query_suffix) {
    if (empty($invoice_row)) {
        return;
    }

    $total_amount = isset($invoice_row->total_amount) ? (float) $invoice_row->total_amount : 0;
    $paid_amount = isset($invoice_row->paid_amount) ? (float) $invoice_row->paid_amount : 0;
    $due_amount = $total_amount - $paid_amount;
    if ($due_amount < 0) {
        $due_amount = 0;
    }
    $payment_status = $this->invoice_model->resolve_invoice_status_from_summary($invoice_row, $paid_amount, $due_amount);
    $amount_to_show = $sidebar_mode === 'payment' ? $due_amount : $total_amount;
    $currency = !empty($invoice_row->currency) ? $invoice_row->currency : config_item('default_currency');
    $is_selected = !empty($is_current) || ((int) $invoice_row->invoices_id === (int) $this->uri->segment(5));
    $item_url = $sidebar_base_path . (int) $invoice_row->invoices_id;
    if (!empty($sidebar_query_suffix)) {
        $item_url .= $sidebar_query_suffix;
    }
    ?>
    <a href="<?= $item_url ?>"
       class="block border-b border-slate-200 px-4 py-4 transition hover:bg-slate-100 dark:border-slate-700 dark:hover:bg-slate-700/50 <?= $is_selected ? 'bg-blue-50 dark:bg-slate-700/70' : 'bg-white dark:bg-slate-900' ?>">
        <div class="flex items-start justify-between gap-4">
            <div class="min-w-0">
                <div class="truncate text-sm font-semibold text-slate-900 dark:text-white">
                    <?= html_escape(!empty($invoice_row->client_name) ? $invoice_row->client_name : '-') ?>
                </div>
                <div class="mt-1 truncate text-xs text-slate-500 dark:text-slate-400">
                    <?= html_escape($invoice_row->reference_no) ?>
                </div>
                <div class="mt-1 text-xs text-slate-400 dark:text-slate-500">
                    <?= display_date($invoice_row->invoice_date) . ' ' . display_time($invoice_row->invoice_date) ?>
                </div>
            </div>
            <div class="shrink-0 text-right">
                <div class="text-sm font-bold text-slate-900 dark:text-white">
                    <?= display_money($amount_to_show, $currency) ?>
                </div>
            </div>
        </div>
    </a>
    <?php
};
?>

<style>
	[data-invoice-sidebar] .invoice-sidebar-scroll::-webkit-scrollbar {
		width: 8px;
	}
	[data-invoice-sidebar] .invoice-sidebar-scroll::-webkit-scrollbar-track {
		background: rgba(15, 23, 42, 0.35);
		border-radius: 999px;
	}
	[data-invoice-sidebar] .invoice-sidebar-scroll::-webkit-scrollbar-thumb {
		background: rgba(148, 163, 184, 0.45);
		border-radius: 999px;
	}
	[data-invoice-sidebar] .invoice-sidebar-scroll::-webkit-scrollbar-thumb:hover {
		background: rgba(148, 163, 184, 0.6);
	}
</style>

<div class="overflow-hidden rounded-lg border border-slate-200 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900"
     data-invoice-sidebar
     data-sidebar-endpoint="<?= $sidebar_endpoint ?>">
    <div class="border-b border-slate-200 px-4 py-4 dark:border-slate-700">
        <h3 class="text-sm font-bold uppercase tracking-wide text-slate-900 dark:text-white">
            <?= lang('all_invoices') ?>
        </h3>
    </div>

    <div class="border-b border-slate-200 px-3 py-3 dark:border-slate-700">
        <form action="<?= $sidebar_page_url ?>" method="get" class="relative" data-invoice-sidebar-search-form>
            <span class="pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
                <i data-lucide="search" class="h-4 w-4"></i>
            </span>
            <input
                type="search"
                name="q"
                value="<?= html_escape($sidebar_search) ?>"
                placeholder="Search by ID, name, or amount..."
                class="w-full rounded-xl border border-slate-300 bg-slate-100 py-3 pl-11 pr-4 text-sm text-slate-900 outline-none transition placeholder:text-slate-400 focus:border-primary focus:bg-white focus:ring-2 focus:ring-primary/20 dark:border-slate-600 dark:bg-slate-900 dark:text-white dark:focus:bg-slate-900"
            >
            <?php if ($sidebar_page > 1) { ?>
                <input type="hidden" name="page" value="<?= (int) $sidebar_page ?>">
            <?php } ?>
        </form>
    </div>

    <div class="invoice-sidebar-scroll overflow-y-auto" style="max-height: 28rem;">
        <div class="divide-y divide-slate-200 dark:divide-slate-700">
            <?php if (!empty($sidebar_invoices)) { ?>
                <?php foreach ($sidebar_invoices as $invoice_row) { ?>
                    <?php $render_sidebar_invoice_card($invoice_row); ?>
                <?php } ?>
            <?php } else { ?>
                <div class="px-4 py-8 text-center text-sm text-slate-400">
                    <div class="mx-auto mb-3 flex h-10 w-10 items-center justify-center rounded-full border border-slate-200 bg-slate-100 text-slate-400 dark:border-slate-700 dark:bg-slate-700 dark:text-slate-300">
                        <i data-lucide="file-search" class="h-5 w-5"></i>
                    </div>
                    <p class="font-medium text-slate-700 dark:text-slate-300"><?= lang('nothing_to_display') ?></p>
                    <?php if ($sidebar_search !== '') { ?>
                        <p class="mt-1 text-xs text-slate-500 dark:text-slate-400"><?= lang('search') ?>: <?= html_escape($sidebar_search) ?></p>
                    <?php } ?>
                </div>
            <?php } ?>
        </div>
    </div>

    <div class="border-t border-slate-200 px-4 py-3 dark:border-slate-700">
        <?php
        $prev_page = $sidebar_page > 1 ? $sidebar_page - 1 : null;
        $next_page = $sidebar_page < $sidebar_pages ? $sidebar_page + 1 : null;
        $page_query = array();
        if ($sidebar_search !== '') {
            $page_query['q'] = $sidebar_search;
        }
        ?>
        <div class="flex items-center justify-between gap-3">
            <?php if (!empty($prev_page)) { ?>
                <a href="<?= $sidebar_page_url . '?' . http_build_query(array_merge($page_query, array('page' => $prev_page))) ?>" class="inline-flex items-center gap-2 rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-600 transition hover:bg-slate-50 dark:border-slate-600 dark:bg-slate-700 dark:text-slate-200 dark:hover:bg-slate-600">
                    <i data-lucide="chevron-left" class="h-4 w-4"></i>
                    <span>Prev</span>
                </a>
            <?php } else { ?>
                <span class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-4 py-2 text-sm font-medium text-slate-400 dark:border-slate-700 dark:bg-slate-700 dark:text-slate-500">
                    <i data-lucide="chevron-left" class="h-4 w-4"></i>
                    <span>Prev</span>
                </span>
            <?php } ?>

            <div class="text-center text-sm font-medium text-slate-500 dark:text-slate-300">
                <?= $sidebar_page ?> of <?= $sidebar_pages ?>
            </div>

            <?php if (!empty($next_page)) { ?>
                <a href="<?= $sidebar_page_url . '?' . http_build_query(array_merge($page_query, array('page' => $next_page))) ?>" class="inline-flex items-center gap-2 rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-600 transition hover:bg-slate-50 dark:border-slate-600 dark:bg-slate-700 dark:text-slate-200 dark:hover:bg-slate-600">
                    <span>Next</span>
                    <i data-lucide="chevron-right" class="h-4 w-4"></i>
                </a>
            <?php } else { ?>
                <span class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-4 py-2 text-sm font-medium text-slate-400 dark:border-slate-700 dark:bg-slate-700 dark:text-slate-500">
                    <span>Next</span>
                    <i data-lucide="chevron-right" class="h-4 w-4"></i>
                </span>
            <?php } ?>
        </div>
    </div>
</div>

<script>
	(function () {
		const sidebar = document.querySelector('[data-invoice-sidebar]');
		if (!sidebar) return;

		const form = sidebar.querySelector('[data-invoice-sidebar-search-form]');
		const input = form ? form.querySelector('input[name="q"]') : null;
		const pageInput = form ? form.querySelector('input[name="page"]') : null;
		if (!form || !input) return;

		let searchTimer = null;
		function submitSearch() {
			if (pageInput) {
				pageInput.value = '1';
			}
			form.submit();
		}

		input.addEventListener('input', function () {
			clearTimeout(searchTimer);
			searchTimer = setTimeout(submitSearch, 350);
		});

		form.addEventListener('submit', function () {
			if (pageInput && !pageInput.value) {
				pageInput.value = '1';
			}
		});
	})();
</script>
