<?php
$edited = can_action('152', 'edited');
$can_edit = $this->purchase_model->can_action('tbl_purchases', 'edit', array('purchase_id' => $payments_info->purchase_id));
$supplier_info = $this->purchase_model->check_by(array('supplier_id' => $payments_info->paid_to), 'tbl_suppliers');

if (is_numeric($payments_info->payment_method)) {
	$payment_method = get_row('tbl_payment_methods', array('payment_methods_id' => $payments_info->payment_method));
} else {
	$payment_method = (object) array('method_name' => $payments_info->payment_method);
}

$currency = $this->purchase_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
$currency_symbol = !empty($currency->symbol) ? $currency->symbol : default_currency();
$supplier_name = !empty($supplier_info) ? $supplier_info->name : '-';
$payments_id = !empty($payments_info) ? $payments_info->payments_id : null;
$purchase_due = (float) $this->purchase_model->calculate_to('purchase_due', $payments_info->purchase_id);
$purchase_info = $this->purchase_model->check_by(array('purchase_id' => $payments_info->purchase_id), 'tbl_purchases');
if (empty($purchase_info)) {
	$purchase_info = new stdClass();
	$purchase_info->purchase_date = date('Y-m-d');
	$purchase_info->reference_no = '-';
}

$payment_methods = $this->db->order_by('payment_methods_id', 'DESC')->get('tbl_payment_methods')->result();
$payment_method_options = array('0' => lang('select_payment_method'));
if (!empty($payment_methods)) {
	foreach ($payment_methods as $p_method) {
		$payment_method_options[$p_method->payment_methods_id] = $p_method->method_name;
	}
}

$payment_method_selected = is_numeric($payments_info->payment_method) ? $payments_info->payment_method : '0';
$payment_method_add = form_select_add_link('payment_methods_id', base_url('admin/settings/inline_payment_method'), lang('new') . ' ' . lang('payment_method'), 'md');
$amount_paid = (float) $payments_info->amount;
?>

<div class="min-h-screen bg-background text-foreground">
	<div class="mx-auto max-w-[1500px] px-4 py-4 sm:px-6 lg:px-8 lg:py-6">
		<div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
			<div class="flex items-start gap-3">
				<a href="<?= base_url('admin/purchase/all_payments'); ?>" class="mt-0.5 inline-flex h-9 w-9 flex-none items-center justify-center rounded-full border border-border bg-card text-muted-foreground transition hover:border-primary hover:text-primary">
					<i data-lucide="arrow-left" class="h-5 w-5"></i>
				</a>
				<div>
					<div class="flex flex-wrap items-center gap-2 sm:gap-3">
						<h1 class="text-xl font-semibold tracking-tight text-foreground sm:text-2xl"><?= lang('edit_payment') ?></h1>
						<span class="inline-flex items-center rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-[11px] font-semibold tracking-[0.14em] text-primary">
							<?= html_escape($payments_info->trans_id); ?>
						</span>
					</div>
					<p class="mt-2 max-w-3xl text-sm text-muted-foreground">Update payment details and review the linked purchase allocation in one clean workspace.</p>
				</div>
			</div>

			<div class="flex flex-wrap items-center gap-3 lg:justify-end">
				<?php if (!empty($can_edit) && !empty($edited)) { ?>
					<a href="<?= base_url('admin/purchase/send_payment/' . $payments_info->purchase_id . '/' . $payments_info->amount) ?>" class="inline-flex items-center gap-2 rounded-xl border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground shadow-sm transition hover:border-primary hover:bg-muted">
						<i data-lucide="send" class="h-4 w-4 text-muted-foreground"></i>
						Email Receipt
					</a>
					<a href="<?= base_url('admin/purchase/payments_pdf/' . $payments_info->payments_id) ?>" class="inline-flex items-center gap-2 rounded-xl border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground shadow-sm transition hover:border-primary hover:bg-muted">
						<i data-lucide="download" class="h-4 w-4 text-muted-foreground"></i>
						Download PDF
					</a>
				<?php } ?>
			</div>
		</div>

		<div class="mt-6 grid gap-5 xl:grid-cols-12">
			<div class="xl:col-span-4">
				<div class="rounded-2xl border border-border bg-card p-4 shadow-sm sm:p-5">
					<div class="mb-4 flex items-center gap-3">
						<div class="flex h-10 w-10 items-center justify-center rounded-xl border border-primary/20 bg-primary/10 text-primary">
							<i data-lucide="wallet-cards" class="h-5 w-5"></i>
						</div>
						<h2 class="text-base font-semibold tracking-tight text-foreground"><?= lang('payment_details') ?></h2>
					</div>

					<?php echo form_open(base_url('admin/purchase/update_payemnt/' . $payments_id), array('class' => 'space-y-6', 'enctype' => 'multipart/form-data', 'data-parsley-validate' => '', 'role' => 'form', 'novalidate' => '')); ?>

					<div>
						<label class="mb-2 block text-xs font-semibold uppercase tracking-[0.12em] text-muted-foreground" for="payment-amount"><?= lang('amount') ?> *</label>
						<div class="relative">
							<span class="pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 text-sm font-semibold text-muted-foreground"><?= html_escape($currency_symbol) ?></span>
							<input
								id="payment-amount"
								type="text"
								data-parsley-type="number"
								required=""
								name="amount"
								value="<?= html_escape($payments_info->amount) ?>"
								class="w-full rounded-xl border border-border bg-input pl-10 pr-4 py-2.5 text-sm font-medium text-foreground outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/20">
						</div>
					</div>

					<div>
						<label class="mb-2 block text-xs font-semibold uppercase tracking-[0.12em] text-muted-foreground" for="payment-method"><?= lang('payment_method') ?> *</label>
						<div class="space-y-2">
							<div class="relative">
								<select
									id="payment-method"
									name="payment_methods_id"
									class="select_box w-full appearance-none rounded-xl border border-border bg-input px-4 py-2.5 pr-10 text-sm font-medium text-foreground outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/20"
									data-live-search="true">
									<?php foreach ($payment_method_options as $method_id => $method_name) { ?>
										<option value="<?= html_escape($method_id) ?>" <?= (string) $payment_method_selected === (string) $method_id ? 'selected' : '' ?>>
											<?= html_escape($method_name) ?>
										</option>
									<?php } ?>
								</select>
								<i data-lucide="chevron-down" class="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"></i>
							</div>
							<div class="text-right"><?= $payment_method_add; ?></div>
						</div>
					</div>

					<div>
						<label class="mb-2 block text-xs font-semibold uppercase tracking-[0.12em] text-muted-foreground" for="payment-date"><?= lang('payment_date') ?> *</label>
						<div class="relative">
							<i data-lucide="calendar" class="pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"></i>
							<input
								id="payment-date"
								type="text"
								required=""
								name="payment_date"
								class="datepicker w-full rounded-xl border border-border bg-input pl-10 pr-10 py-2.5 text-sm font-medium text-foreground outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/20"
								value="<?php echo !empty($payments_info->payment_date) ? $payments_info->payment_date : date('Y-m-d'); ?>"
								data-date-format="<?= config_item('date_picker_format'); ?>">
							<i data-lucide="calendar-days" class="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"></i>
						</div>
					</div>

					<div>
						<label class="mb-2 block text-xs font-semibold uppercase tracking-[0.12em] text-muted-foreground" for="payment-notes"><?= lang('notes') ?></label>
						<textarea
							id="payment-notes"
							name="notes"
							rows="6"
							class="w-full rounded-xl border border-border bg-input px-4 py-3 text-sm text-foreground outline-none transition placeholder:text-muted-foreground focus:border-primary focus:ring-2 focus:ring-primary/20"><?= html_escape($payments_info->notes) ?></textarea>
					</div>

					<div class="pt-2">
						<button type="submit" class="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-primary px-5 py-3 text-sm font-semibold text-primary-foreground shadow-sm transition hover:bg-primary/90">
							<i data-lucide="save" class="h-4 w-4"></i>
							<?= lang('save_changes') ?>
						</button>
					</div>

					<?php echo form_close(); ?>
				</div>
			</div>

			<div class="space-y-6 xl:col-span-8">
				<div class="grid gap-4 md:grid-cols-3">
					<div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
						<div class="flex items-center gap-2 text-muted-foreground">
							<i data-lucide="building-2" class="h-4 w-4"></i>
							<span class="text-xs font-semibold uppercase tracking-[0.12em]"><?= lang('paid') . ' ' . lang('to') ?></span>
						</div>
						<div class="mt-3 text-sm font-semibold text-foreground"><?= html_escape($supplier_name) ?></div>
					</div>

					<div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
						<div class="flex items-center gap-2 text-muted-foreground">
							<i data-lucide="hash" class="h-4 w-4"></i>
							<span class="text-xs font-semibold uppercase tracking-[0.12em]"><?= lang('transaction_id') ?></span>
						</div>
						<div class="mt-3 text-sm font-semibold text-foreground"><?= html_escape($payments_info->trans_id) ?></div>
					</div>

					<div class="rounded-2xl border border-primary/20 bg-card p-4 shadow-sm">
						<div class="text-xs font-semibold uppercase tracking-[0.12em] text-primary"><?= lang('amount_paid') ?></div>
						<div class="mt-3 text-sm font-semibold text-foreground" data-payment-amount-display><?= display_money($amount_paid, $currency_symbol) ?></div>
					</div>
				</div>

				<div class="overflow-hidden rounded-2xl border border-border bg-card shadow-sm">
					<div class="border-b border-border px-4 py-4">
						<div class="flex items-center gap-3">
							<i data-lucide="receipt" class="h-4 w-4 text-muted-foreground"></i>
							<h2 class="text-base font-semibold tracking-tight text-foreground"><?= lang('payment_for') ?></h2>
						</div>
					</div>

					<div class="overflow-x-auto">
						<table class="min-w-full text-left text-sm">
							<thead>
								<tr class="border-b border-border bg-muted/40 text-muted-foreground">
									<th class="px-4 py-3 text-xs font-semibold uppercase tracking-[0.12em]"><?= lang('reference_no') ?></th>
									<th class="px-4 py-3 text-xs font-semibold uppercase tracking-[0.12em]"><?= lang('purchase_date') ?></th>
									<th class="px-4 py-3 text-xs font-semibold uppercase tracking-[0.12em]"><?= lang('purchase') . ' ' . lang('amount') ?></th>
									<th class="px-4 py-3 text-right text-xs font-semibold uppercase tracking-[0.12em]"><?= lang('paid_amount') ?></th>
									<?php if ($purchase_due > 0) { ?>
									<th class="px-4 py-3 text-right text-xs font-semibold uppercase tracking-[0.12em]"><?= lang('due_amount') ?></th>
									<?php } ?>
								</tr>
							</thead>
							<tbody>
								<tr class="border-b border-border bg-card">
									<td class="px-4 py-4">
										<div class="flex items-center gap-3 sm:gap-4">
											<div class="flex h-9 w-9 items-center justify-center rounded-lg border border-border bg-background text-muted-foreground">
												<i data-lucide="shopping-cart" class="h-4 w-4"></i>
											</div>
											<div>
												<a href="<?= base_url('admin/purchase/purchase_details/' . $payments_info->purchase_id) ?>" class="text-sm font-semibold text-foreground transition hover:text-primary">
													<?= html_escape($purchase_info->reference_no) ?>
												</a>
											</div>
										</div>
									</td>
									<td class="px-4 py-4 text-sm text-muted-foreground"><?= display_date($purchase_info->purchase_date) ?></td>
									<td class="px-4 py-4 text-sm font-semibold text-foreground"><?= display_money($this->purchase_model->calculate_to('total', $purchase_info->purchase_id), $currency_symbol) ?></td>
									<td class="px-4 py-4 text-right text-sm font-semibold text-emerald-500" data-paid-amount-cell><?= display_money($amount_paid, $currency_symbol) ?></td>
									<?php if ($purchase_due > 0) { ?>
									<td class="px-4 py-4 text-right text-sm font-semibold text-rose-500" data-due-amount-cell><?= display_money($purchase_due, $currency_symbol) ?></td>
									<?php } ?>
								</tr>
							</tbody>
						</table>
					</div>

					<div class="flex items-center justify-between gap-4 border-t border-border bg-muted/30 px-4 py-3">
						<div class="text-xs font-semibold uppercase tracking-[0.12em] text-muted-foreground"><?= lang('paid_amount') ?></div>
						<div class="text-sm font-semibold text-emerald-500" data-total-applied><?= display_money($amount_paid, $currency_symbol) ?></div>
					</div>
				</div>

				<div class="grid gap-4 md:grid-cols-2">
					<?php
					$role = $this->session->userdata('user_type');
					if ($role == 1 && $payments_info->account_id != 0) {
						$account_info = $this->purchase_model->check_by(array('account_id' => $payments_info->account_id), 'tbl_accounts');
						if (!empty($account_info)) {
					?>
					<div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
						<div class="flex items-center gap-2 text-muted-foreground">
							<i data-lucide="landmark" class="h-4 w-4"></i>
							<span class="text-xs font-semibold uppercase tracking-[0.12em]"><?= lang('deduct_from') ?></span>
						</div>
						<div class="mt-3 text-sm font-semibold text-foreground"><?= html_escape($account_info->account_name) ?></div>
					</div>
					<?php } } ?>

					<div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
						<div class="flex items-center gap-2 text-muted-foreground">
							<i data-lucide="credit-card" class="h-4 w-4"></i>
							<span class="text-xs font-semibold uppercase tracking-[0.12em]"><?= lang('payment_mode') ?></span>
						</div>
						<div class="mt-3 text-sm font-semibold text-foreground"><?= !empty($payment_method->method_name) ? html_escape($payment_method->method_name) : '-' ?></div>
					</div>
				</div>

				<?php if (!empty($payments_info->notes)) { ?>
				<div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
					<div class="flex items-center gap-2 text-muted-foreground">
						<i data-lucide="sticky-note" class="h-4 w-4"></i>
						<span class="text-xs font-semibold uppercase tracking-[0.12em]"><?= lang('notes') ?></span>
					</div>
					<div class="mt-3 whitespace-pre-line text-sm leading-6 text-foreground"><?= html_escape($payments_info->notes) ?></div>
				</div>
				<?php } ?>

				<?php if (config_item('amount_to_words') == 'Yes') { ?>
				<div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
					<div class="flex items-center gap-2 text-muted-foreground">
						<i data-lucide="badge-dollar-sign" class="h-4 w-4"></i>
						<span class="text-xs font-semibold uppercase tracking-[0.12em]"><?= lang('num_word') ?></span>
					</div>
					<div class="mt-3 text-sm leading-6 text-foreground"><?= number_to_word('', $payments_info->amount); ?></div>
				</div>
				<?php } ?>
			</div>
		</div>
	</div>
</div>

<script>
	(function () {
		const amountInput = document.getElementById('payment-amount');
		const amountDisplay = document.querySelector('[data-payment-amount-display]');
		const paidAmountCell = document.querySelector('[data-paid-amount-cell]');
		const totalApplied = document.querySelector('[data-total-applied]');
		const currencySymbol = <?php echo json_encode($currency_symbol); ?>;

		function formatMoney(value) {
			const amount = Number(value) || 0;
			const formatted = amount.toLocaleString(undefined, {
				minimumFractionDigits: 2,
				maximumFractionDigits: 2,
			});
			return currencySymbol + formatted;
		}

		function updatePreview() {
			if (!amountInput) return;
			const nextValue = amountInput.value.replace(/[^0-9.]/g, '');
			const formatted = formatMoney(nextValue);

			if (amountDisplay) amountDisplay.textContent = formatted;
			if (paidAmountCell) paidAmountCell.textContent = formatted;
			if (totalApplied) totalApplied.textContent = formatted;
		}

		if (amountInput) {
			amountInput.addEventListener('input', updatePreview);
		}
	})();
</script>
