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

<?php
$edited = can_action('152', 'edited');
$deleted = can_action('152', 'deleted');
$paid_amount = $this->purchase_model->calculate_to('paid_amount', $sales_info->purchase_id);
$payment_status = $this->purchase_model->get_payment_status($sales_info->purchase_id);
$currency = $this->purchase_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
$can_edit = $this->purchase_model->can_action('tbl_purchases', 'edit', array('purchase_id' => $sales_info->purchase_id));
$can_delete = $this->purchase_model->can_action('tbl_purchases', 'delete', array('purchase_id' => $sales_info->purchase_id));

$sales_info->company_heading = lang('supplier');
$purchase_detail_active_tab = !empty($purchase_detail_active_tab) ? $purchase_detail_active_tab : 'overview';
$purchase_payment_count = isset($purchase_payment_count) ? (int) $purchase_payment_count : 0;
$supplier_purchase_history_count = isset($supplier_purchase_history_count) ? (int) $supplier_purchase_history_count : 0;
$supplier_return_history_count = isset($supplier_return_history_count) ? (int) $supplier_return_history_count : 0;
$supplier_purchase_history = !empty($supplier_purchase_history) ? $supplier_purchase_history : array();
$supplier_return_history = !empty($supplier_return_history) ? $supplier_return_history : array();
$supplier_purchase_history_page = !empty($supplier_purchase_history_page) ? (int) $supplier_purchase_history_page : 1;
$supplier_purchase_history_pages = !empty($supplier_purchase_history_pages) ? (int) $supplier_purchase_history_pages : 1;
$supplier_return_history_page = !empty($supplier_return_history_page) ? (int) $supplier_return_history_page : 1;
$supplier_return_history_pages = !empty($supplier_return_history_pages) ? (int) $supplier_return_history_pages : 1;
$purchase_tab_link = function ($tab, $extra = array()) {
	$params = array_merge($_GET, $extra, array('tab' => $tab));
	foreach ($params as $key => $value) {
		if ($value === null || $value === '') {
			unset($params[$key]);
		}
	}
	$query = http_build_query($params);
	return current_url() . (!empty($query) ? '?' . $query : '');
};
?>

<div class="space-y-6">
	<div class="flex flex-wrap items-center gap-2 rounded-2xl border border-border bg-card p-3 shadow-sm">
		<?php
		$purchase_tabs = array(
			'overview' => array('label' => 'Overview', 'icon' => 'layout-grid', 'count' => null),
			'payments' => array('label' => lang('payment'), 'icon' => 'wallet', 'count' => $purchase_payment_count),
			'purchases' => array('label' => 'Purchase History', 'icon' => 'shopping-cart', 'count' => $supplier_purchase_history_count),
			'returns' => array('label' => 'Return Stock', 'icon' => 'rotate-ccw', 'count' => $supplier_return_history_count),
		);
		foreach ($purchase_tabs as $tab_key => $tab_meta) {
			$is_active = $purchase_detail_active_tab === $tab_key;
			?>
			<a href="<?= $purchase_tab_link($tab_key, $tab_key === 'purchases' ? array('purchase_page' => 1) : ($tab_key === 'returns' ? array('return_page' => 1) : array())) ?>"
			   class="inline-flex items-center gap-2 rounded-xl border px-4 py-2 text-sm font-semibold transition <?= $is_active ? 'border-slate-900 bg-slate-900 text-white shadow-sm dark:border-slate-100 dark:bg-slate-100 dark:text-slate-900' : 'border-slate-200 bg-white text-slate-600 hover:border-slate-300 hover:text-slate-900 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300 dark:hover:border-slate-600 dark:hover:text-slate-100' ?>">
				<i data-lucide="<?= html_escape($tab_meta['icon']) ?>" class="h-4 w-4"></i>
				<span><?= html_escape($tab_meta['label']) ?></span>
				<?php if ($tab_meta['count'] !== null) { ?>
					<span class="inline-flex min-w-[1.5rem] items-center justify-center rounded-full px-2 py-0.5 text-[11px] font-bold <?= $is_active ? 'bg-white/20 text-white dark:bg-slate-900/10 dark:text-slate-900' : 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-200' ?>">
						<?= (int) $tab_meta['count'] ?>
					</span>
				<?php } ?>
			</a>
		<?php } ?>
	</div>

	<?php if ($purchase_detail_active_tab === 'overview') { ?>
		<?php
		$this->load->view('admin/common/sales_details_modern', array(
			'sales_info' => $sales_info,
			'all_items' => $all_items,
			'paid_amount' => $paid_amount,
			'invoice_due' => $invoice_due,
			'payment_status' => $payment_status,
			'footer' => isset($footer) ? $footer : null,
			'document_label' => lang('purchase'),
		));
		?>
	<?php } ?>

		<?php $all_payment_info = $this->db->where('purchase_id', $sales_info->purchase_id)->get('tbl_purchase_payments')->result();
		if ($purchase_detail_active_tab === 'payments' && !empty($all_payment_info)) { ?>
			<div class="overflow-hidden rounded-2xl border border-border bg-card shadow-sm">
				<div class="flex flex-wrap items-center justify-between gap-3 border-b border-border px-5 py-4">
					<div class="flex min-w-0 items-center gap-3">
						<span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10 text-primary">
							<i data-lucide="wallet" class="h-5 w-5"></i>
						</span>
						<div class="min-w-0">
							<h2 class="text-base font-semibold text-foreground"><?= lang('payment') . ' ' . lang('details') ?></h2>
							<p class="mt-1 text-sm text-muted-foreground"><?= count($all_payment_info) ?> <?= lang('payments') ?></p>
						</div>
					</div>
				</div>
				<div class="overflow-x-auto">
					<table class="w-full table-auto divide-y divide-border">
						<thead class="bg-muted/40">
							<tr class="text-left text-xs font-semibold uppercase tracking-wide text-muted-foreground">
								<th class="px-5 py-3"><?= lang('transaction_id') ?></th>
								<th class="px-5 py-3"><?= lang('payment_date') ?></th>
								<th class="px-5 py-3 text-right"><?= lang('amount') ?></th>
								<th class="px-5 py-3"><?= lang('payment_mode') ?></th>
								<th class="px-5 py-3 text-right"><?= lang('action') ?></th>
							</tr>
						</thead>
						<tbody class="divide-y divide-border bg-card">
							<?php foreach ($all_payment_info as $v_payments_info) {
								if (is_numeric($v_payments_info->payment_method)) {
									$payment_methods = $this->purchase_model->check_by(array('payment_methods_id' => $v_payments_info->payment_method), 'tbl_payment_methods');
									$payment_method_name = !empty($payment_methods->method_name) ? $payment_methods->method_name : '-';
								} else {
									$payment_method_name = !empty($v_payments_info->payment_method) ? $v_payments_info->payment_method : '-';
								}
								?>
								<tr id="purchase-payment-<?= (int) $v_payments_info->payments_id ?>" class="text-sm text-foreground transition hover:bg-muted/30">
									<td class="px-5 py-4 align-middle">
										<a class="font-semibold text-primary hover:underline" href="<?= base_url('admin/purchase/payments_details/' . $v_payments_info->payments_id) ?>"><?= html_escape($v_payments_info->trans_id) ?></a>
									</td>
									<td class="whitespace-nowrap px-5 py-4 align-middle text-muted-foreground"><?= display_date($v_payments_info->payment_date); ?></td>
									<td class="whitespace-nowrap px-5 py-4 text-right align-middle font-semibold"><?= display_money($v_payments_info->amount, $currency->symbol) ?></td>
									<td class="px-5 py-4 align-middle">
										<span class="inline-flex items-center rounded-full bg-muted px-2.5 py-1 text-xs font-medium text-foreground"><?= html_escape($payment_method_name); ?></span>
									</td>
									<td class="px-5 py-4 align-middle">
										<div class="flex items-center justify-end gap-1">
											<?php if (!empty($can_edit) && !empty($edited)) { ?>
												<a href="<?= base_url('admin/purchase/all_payments/' . $v_payments_info->payments_id) ?>" class="inline-flex h-7 mb-1 w-8 items-center justify-center rounded-lg border border-violet-200 bg-violet-50 text-violet-700 transition hover:bg-violet-100 dark:border-violet-900/60 dark:bg-violet-950/30 dark:text-violet-300 dark:hover:bg-violet-900/40" title="<?= lang('edit') ?>"><i data-lucide="pencil" class="h-4 w-4"></i></a>
											<?php } ?>
											<?php if (!empty($can_delete) && !empty($deleted)) { ?>
												<?= ajax_anchor(
													base_url('admin/purchase/delete_payment/' . $v_payments_info->payments_id),
													lang('delete'),
													array(
														"class" => "inline-flex h-7 mb-1 items-center justify-center rounded-lg border border-rose-200 bg-rose-50 px-3 text-xs font-semibold text-rose-700 transition hover:bg-rose-100 dark:border-rose-900/60 dark:bg-rose-950/30 dark:text-rose-300 dark:hover:bg-rose-900/40",
														"title" => lang('delete'),
														"data-fade-out-on-success" => "#purchase-payment-" . $v_payments_info->payments_id
													)
												) ?>
											<?php } ?>
											<a href="<?= base_url('admin/purchase/send_payment/' . $v_payments_info->payments_id . '/' . $v_payments_info->amount) ?>" class="inline-flex h-7 mb-1 w-8 items-center justify-center rounded-lg border border-emerald-200 bg-emerald-50 text-emerald-700 transition hover:bg-emerald-100 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300 dark:hover:bg-emerald-900/40" title="<?= lang('send_email') ?>"><i data-lucide="mail" class="h-4 w-4"></i></a>
											<a href="<?= base_url('admin/purchase/payments_pdf/' . $v_payments_info->payments_id) ?>" class="inline-flex h-7 mb-1 w-8 items-center justify-center rounded-lg border border-amber-200 bg-amber-50 text-amber-700 transition hover:bg-amber-100 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300 dark:hover:bg-amber-900/40" title="<?= lang('pdf') ?>"><i data-lucide="file-text" class="h-4 w-4"></i></a>
										</div>
									</td>
								</tr>
							<?php } ?>
						</tbody>
				</table>
			</div>
		</div>
	<?php } ?>

	<?php if ($purchase_detail_active_tab === 'payments' && empty($all_payment_info)) { ?>
		<div class="rounded-2xl border border-border bg-card px-6 py-12 text-center shadow-sm">
			<div class="mx-auto mb-4 inline-flex h-12 w-12 items-center justify-center rounded-full border border-border text-muted-foreground">
				<i data-lucide="wallet" class="h-5 w-5"></i>
			</div>
			<h3 class="text-lg font-semibold text-foreground"><?= lang('nothing_to_display') ?></h3>
			<p class="mt-2 text-sm text-muted-foreground">No payment entries have been recorded for this purchase yet.</p>
		</div>
	<?php } ?>

	<?php if ($purchase_detail_active_tab === 'purchases') { ?>
		<div class="overflow-hidden rounded-2xl border border-border bg-card shadow-sm">
			<div class="flex flex-wrap items-center justify-between gap-3 border-b border-border px-5 py-4">
				<div class="flex min-w-0 items-center gap-3">
					<span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-sky-50 text-sky-700 dark:bg-sky-950/40 dark:text-sky-300">
						<i data-lucide="shopping-cart" class="h-5 w-5"></i>
					</span>
					<div class="min-w-0">
						<h2 class="text-base font-semibold text-foreground">Purchase History</h2>
						<p class="mt-1 text-sm text-muted-foreground">Recent supplier purchases with dates, status, and order totals.</p>
					</div>
				</div>
				<span class="rounded-full bg-muted px-3 py-1 text-xs font-semibold text-foreground"><?= (int) $supplier_purchase_history_count ?> records</span>
			</div>
			<div class="overflow-x-auto">
				<table class="w-full table-auto divide-y divide-border">
					<thead class="bg-muted/40">
						<tr class="text-left text-xs font-semibold uppercase tracking-wide text-muted-foreground">
							<th class="px-5 py-3"><?= lang('reference_no') ?></th>
							<th class="px-5 py-3"><?= lang('purchase_date') ?></th>
							<th class="px-5 py-3"><?= lang('due_date') ?></th>
							<th class="px-5 py-3"><?= lang('status') ?></th>
							<th class="px-5 py-3 text-right"><?= lang('amount') ?></th>
						</tr>
					</thead>
					<tbody class="divide-y divide-border bg-card">
						<?php if (!empty($supplier_purchase_history)) { ?>
							<?php foreach ($supplier_purchase_history as $purchase) {
								$purchase_total = $this->purchase_model->get_purchase_total_amount($purchase->purchase_id);
								$purchase_status = $this->purchase_model->get_payment_status($purchase->purchase_id);
								$status_class = 'bg-rose-100 text-rose-700 dark:bg-rose-950/30 dark:text-rose-300';
								if ($purchase_status == 'fully_paid') {
									$status_class = 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-300';
								} elseif ($purchase_status == 'partially_paid') {
									$status_class = 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-300';
								} elseif ($purchase_status == 'cancelled') {
									$status_class = 'bg-slate-200 text-slate-700 dark:bg-slate-800 dark:text-slate-300';
								}
								?>
								<tr class="text-sm text-foreground transition hover:bg-muted/30">
									<td class="px-5 py-4 align-middle">
										<a class="font-semibold text-primary hover:underline" href="<?= base_url('admin/purchase/purchase_details/' . $purchase->purchase_id) ?>"><?= html_escape($purchase->reference_no) ?></a>
									</td>
									<td class="whitespace-nowrap px-5 py-4 align-middle text-muted-foreground"><?= !empty($purchase->purchase_date) ? display_date($purchase->purchase_date) : '-' ?></td>
									<td class="whitespace-nowrap px-5 py-4 align-middle text-muted-foreground"><?= !empty($purchase->due_date) ? display_date($purchase->due_date) : '-' ?></td>
									<td class="px-5 py-4 align-middle"><span class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold <?= $status_class ?>"><?= lang($purchase_status) ?></span></td>
									<td class="whitespace-nowrap px-5 py-4 text-right align-middle font-semibold"><?= display_money($purchase_total, $currency->symbol) ?></td>
								</tr>
							<?php } ?>
						<?php } else { ?>
							<tr>
								<td colspan="5" class="px-5 py-10 text-center text-sm text-muted-foreground"><?= lang('nothing_to_display') ?></td>
							</tr>
						<?php } ?>
					</tbody>
				</table>
			</div>
			<div class="flex flex-wrap items-center justify-between gap-3 border-t border-border px-5 py-4 text-sm text-muted-foreground">
				<span>Page <?= $supplier_purchase_history_page ?> of <?= max(1, $supplier_purchase_history_pages) ?></span>
				<div class="flex items-center gap-2">
					<a href="<?= $purchase_tab_link('purchases', array('purchase_page' => max(1, $supplier_purchase_history_page - 1))) ?>"
					   class="inline-flex h-9 items-center justify-center rounded-lg border border-border px-3 font-semibold transition <?= $supplier_purchase_history_page <= 1 ? 'pointer-events-none opacity-40' : 'hover:bg-muted' ?>">
						<?= lang('previous') ?>
					</a>
					<a href="<?= $purchase_tab_link('purchases', array('purchase_page' => min($supplier_purchase_history_pages, $supplier_purchase_history_page + 1))) ?>"
					   class="inline-flex h-9 items-center justify-center rounded-lg border border-border px-3 font-semibold transition <?= $supplier_purchase_history_page >= $supplier_purchase_history_pages ? 'pointer-events-none opacity-40' : 'hover:bg-muted' ?>">
						<?= lang('next') ?>
					</a>
				</div>
			</div>
		</div>
	<?php } ?>

	<?php if ($purchase_detail_active_tab === 'returns') { ?>
		<div class="overflow-hidden rounded-2xl border border-border bg-card shadow-sm">
			<div class="flex flex-wrap items-center justify-between gap-3 border-b border-border px-5 py-4">
				<div class="flex min-w-0 items-center gap-3">
					<span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-amber-50 text-amber-700 dark:bg-amber-950/40 dark:text-amber-300">
						<i data-lucide="rotate-ccw" class="h-5 w-5"></i>
					</span>
					<div class="min-w-0">
						<h2 class="text-base font-semibold text-foreground">Return Stock History</h2>
						<p class="mt-1 text-sm text-muted-foreground">Supplier returns with status and outstanding balance tracking.</p>
					</div>
				</div>
				<span class="rounded-full bg-muted px-3 py-1 text-xs font-semibold text-foreground"><?= (int) $supplier_return_history_count ?> records</span>
			</div>
			<div class="overflow-x-auto">
				<table class="w-full table-auto divide-y divide-border">
					<thead class="bg-muted/40">
						<tr class="text-left text-xs font-semibold uppercase tracking-wide text-muted-foreground">
							<th class="px-5 py-3"><?= lang('reference_no') ?></th>
							<th class="px-5 py-3"><?= lang('return_stock_date') ?></th>
							<th class="px-5 py-3"><?= lang('status') ?></th>
							<th class="px-5 py-3 text-right"><?= lang('due') ?></th>
						</tr>
					</thead>
					<tbody class="divide-y divide-border bg-card">
						<?php if (!empty($supplier_return_history)) { ?>
							<?php foreach ($supplier_return_history as $return_stock) {
								$return_status = $this->return_stock_model->get_payment_status($return_stock->return_stock_id);
								$due_amount = $this->return_stock_model->calculate_to('return_stock_due', $return_stock->return_stock_id);
								$return_class = 'bg-rose-100 text-rose-700 dark:bg-rose-950/30 dark:text-rose-300';
								if ($return_status == 'fully_paid') {
									$return_class = 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-300';
								} elseif ($return_status == 'partially_paid') {
									$return_class = 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-300';
								} elseif ($return_status == 'cancelled') {
									$return_class = 'bg-slate-200 text-slate-700 dark:bg-slate-800 dark:text-slate-300';
								}
								?>
								<tr class="text-sm text-foreground transition hover:bg-muted/30">
									<td class="px-5 py-4 align-middle">
										<a class="font-semibold text-primary hover:underline" href="<?= base_url('admin/return_stock/return_stock_details/' . $return_stock->return_stock_id) ?>"><?= html_escape($return_stock->reference_no) ?></a>
									</td>
									<td class="whitespace-nowrap px-5 py-4 align-middle text-muted-foreground"><?= !empty($return_stock->return_stock_date) ? display_date($return_stock->return_stock_date) : '-' ?></td>
									<td class="px-5 py-4 align-middle"><span class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold <?= $return_class ?>"><?= lang($return_status) ?></span></td>
									<td class="whitespace-nowrap px-5 py-4 text-right align-middle font-semibold"><?= display_money($due_amount, $currency->symbol) ?></td>
								</tr>
							<?php } ?>
						<?php } else { ?>
							<tr>
								<td colspan="4" class="px-5 py-10 text-center text-sm text-muted-foreground"><?= lang('nothing_to_display') ?></td>
							</tr>
						<?php } ?>
					</tbody>
				</table>
			</div>
			<div class="flex flex-wrap items-center justify-between gap-3 border-t border-border px-5 py-4 text-sm text-muted-foreground">
				<span>Page <?= $supplier_return_history_page ?> of <?= max(1, $supplier_return_history_pages) ?></span>
				<div class="flex items-center gap-2">
					<a href="<?= $purchase_tab_link('returns', array('return_page' => max(1, $supplier_return_history_page - 1))) ?>"
					   class="inline-flex h-9 items-center justify-center rounded-lg border border-border px-3 font-semibold transition <?= $supplier_return_history_page <= 1 ? 'pointer-events-none opacity-40' : 'hover:bg-muted' ?>">
						<?= lang('previous') ?>
					</a>
					<a href="<?= $purchase_tab_link('returns', array('return_page' => min($supplier_return_history_pages, $supplier_return_history_page + 1))) ?>"
					   class="inline-flex h-9 items-center justify-center rounded-lg border border-border px-3 font-semibold transition <?= $supplier_return_history_page >= $supplier_return_history_pages ? 'pointer-events-none opacity-40' : 'hover:bg-muted' ?>">
						<?= lang('next') ?>
					</a>
				</div>
			</div>
		</div>
	<?php } ?>
</div>

<script>
	window.purchasePdfPrintHtml = <?= json_encode(isset($purchase_pdf_print_html) ? $purchase_pdf_print_html : '', JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;

	if (typeof window.print_sales_details !== 'function') {
		window.print_sales_details = function(salesId) {
			var content = document.getElementById(salesId);
			var printHtml = window.purchasePdfPrintHtml || (content ? content.outerHTML : '');
			if (!printHtml) return;

			var printWindow = window.open('', 'PRINT', 'height=900,width=1200');
			if (!printWindow) {
				if (typeof window.erpNativePrint === 'function') {
					window.erpNativePrint();
				} else if (typeof window.print === 'function') {
					window.print();
				}
				return;
			}

			var styles = '';
			document.querySelectorAll('link[rel="stylesheet"], style').forEach(function(node) {
				styles += node.outerHTML;
			});
			styles += '<style>' +
				'@page{size:A4;margin:14mm;}' +
				'html,body{background:#fff!important;color:#0f172a!important;-webkit-print-color-adjust:exact;print-color-adjust:exact;}' +
				'body{margin:0!important;padding:0!important;}' +
				'table{border-collapse:collapse;}' +
				'thead{display:table-header-group!important;}' +
				'tr,img{break-inside:avoid!important;page-break-inside:avoid!important;}' +
				'img{max-width:100%!important;}' +
				'</style>';

			printWindow.document.open();
			printWindow.document.write('<!doctype html><html><head><meta charset="utf-8"><title>' + document.title + '</title>' + styles + '</head><body>' + printHtml + '</body></html>');
			printWindow.document.close();

			var printed = false;
			var doPrint = function() {
				if (printed || printWindow.closed) {
					return;
				}
				printed = true;
				printWindow.focus();
				if (typeof printWindow.print === 'function') {
					printWindow.print();
				}
				printWindow.close();
			};

			printWindow.onload = function() {
				printWindow.setTimeout(doPrint, 350);
			};
			printWindow.setTimeout(doPrint, 1000);
		};
	}
</script>
