<?php
$edited = can_action('13', 'edited');
$can_edit = $this->invoice_model->can_action('tbl_invoices', 'edit', array('invoices_id' => $payments_info->invoices_id));
$client_info = $this->invoice_model->check_by(array('client_id' => $payments_info->paid_by), 'tbl_client');

if (is_numeric($payments_info->payment_method)) {
	$payment_methods = $this->invoice_model->check_by(array('payment_methods_id' => $payments_info->payment_method), 'tbl_payment_methods');
} else {
	$payment_methods = $payments_info->payment_method;
}

if (!empty($client_info)) {
	$client_name = $client_info->name;
	$currency = $this->invoice_model->client_currency_symbol($payments_info->paid_by);
} else {
	$client_name = '-';
	$currency = $this->invoice_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
}

$invoice_info = $this->invoice_model->check_by(array('invoices_id' => $payments_info->invoices_id), 'tbl_invoices');
if (empty($invoice_info)) {
	$invoice_info = new stdClass();
	$invoice_info->date_saved = date('Y-m-d');
	$invoice_info->reference_no = '-';
}

$invoice_due = (float) $this->invoice_model->calculate_to('invoice_due', $payments_info->invoices_id);
$amount_received = (float) $payments_info->amount;
$currency_symbol = !empty($currency->symbol) ? $currency->symbol : default_currency();
$payment_method_value = !empty($payments_info->payment_method) ? $payments_info->payment_method : '';
?>

<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/invoice/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">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 transaction details and review invoice allocations.</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/invoice/send_payment/<?= $payments_info->payments_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/invoice/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="credit-card" class="h-5 w-5"></i>
						</div>
						<h2 class="text-base font-semibold tracking-tight text-foreground">Payment Details</h2>
					</div>

					<?php echo form_open(base_url() . 'admin/invoice/update_payemnt/' . $payments_info->payments_id, array('class' => 'space-y-6', 'data-parsley-validate' => 'true', 'novalidate' => '')); ?>

					<div>
						<label class="mb-2 block text-xs font-semibold uppercase tracking-[0.12em] text-muted-foreground" for="payment-amount">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">$</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>

					<?php do_action('multicurrency_edit_payment', $payments_info); ?>

					<div>
						<label class="mb-2 block text-xs font-semibold uppercase tracking-[0.12em] text-muted-foreground" for="payment-method">Payment Method *</label>
						<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">
								<option value="0"><?= lang('select_payment_method') ?></option>
								<?php
								$selected_payment_method = (string) $payments_info->payment_method;
								$selected_payment_label = '';
								$apayment_methods = $this->db->order_by('payment_methods_id', 'DESC')->get('tbl_payment_methods')->result();
								if (!empty($apayment_methods)) {
									foreach ($apayment_methods as $p_method) {
										if ($selected_payment_method !== '' && (string) $p_method->payment_methods_id === $selected_payment_method) {
											$selected_payment_label = $p_method->method_name;
										}
									}
								}
								if ($selected_payment_method !== '' && $selected_payment_label === '' && !is_numeric($selected_payment_method)) {
								?>
									<option value="<?= html_escape($selected_payment_method) ?>" selected><?= html_escape($selected_payment_method) ?></option>
								<?php
								}
								if (!empty($apayment_methods)) {
									foreach ($apayment_methods as $p_method) {
								?>
									<option value="<?= $p_method->payment_methods_id ?>" <?php if ($selected_payment_method !== '' && (string) $p_method->payment_methods_id === $selected_payment_method) { echo 'selected'; } ?>>
										<?= html_escape($p_method->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>

					<div>
						<label class="mb-2 block text-xs font-semibold uppercase tracking-[0.12em] text-muted-foreground" for="payment-date">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">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>
							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="user" class="h-4 w-4"></i>
							<span class="text-xs font-semibold uppercase tracking-[0.12em]">Received From</span>
						</div>
						<div class="mt-3 text-sm font-semibold text-foreground"><?= html_escape($client_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]">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">Amount Received</div>
						<div class="mt-3 text-sm font-semibold text-foreground" data-payment-amount-display><?= display_money($amount_received, $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">Payment Allocation</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]">Payment For</th>
									<th class="px-4 py-3 text-xs font-semibold uppercase tracking-[0.12em]">Invoice Date</th>
									<th class="px-4 py-3 text-xs font-semibold uppercase tracking-[0.12em]">Invoice Amount</th>
									<th class="px-4 py-3 text-right text-xs font-semibold uppercase tracking-[0.12em]">Paid Amount</th>
								</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="file-text" class="h-4 w-4"></i>
											</div>
											<div>
													<a href="<?= base_url() ?>admin/invoice/manage_invoice/invoice_details/<?= $payments_info->invoices_id ?>" class="text-sm font-semibold text-foreground transition hover:text-primary">
													<?= html_escape($invoice_info->reference_no) ?>
												</a>
											</div>
										</div>
									</td>
									<td class="px-4 py-4 text-sm text-muted-foreground"><?= display_date($invoice_info->date_saved) ?></td>
									<td class="px-4 py-4 text-sm font-semibold text-foreground"><?= display_money($this->invoice_model->calculate_to('total', $payments_info->invoices_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_received, $currency_symbol) ?></td>
								</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">Total Applied</div>
						<div class="text-sm font-semibold text-emerald-500" data-total-applied><?= display_money($amount_received, $currency_symbol) ?></div>
					</div>
				</div>
			</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 invoiceDue = <?php echo json_encode($invoice_due); ?>;
		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 syncAmounts() {
			if (!amountInput) return;
			const value = Number(amountInput.value || 0);
			if (amountDisplay) amountDisplay.textContent = formatMoney(value);
			if (paidAmountCell) paidAmountCell.textContent = formatMoney(value);
			if (totalApplied) totalApplied.textContent = formatMoney(value);
		}

		if (amountInput) {
			amountInput.addEventListener('input', syncAmounts);
			syncAmounts();
		}

		if (window.lucide && typeof window.lucide.createIcons === 'function') {
			window.lucide.createIcons();
		}
	})();
</script>
