<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<?php
$is_income = (!empty($expense_info) && $expense_info->type == 'Income');
$currency = $this->transactions_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
$account_info = $this->transactions_model->check_by(array('account_id' => $expense_info->account_id), 'tbl_accounts');

$category = lang('undefined_category');
if ($is_income) {
	$category_info = get_row('tbl_income_category', array('income_category_id' => $expense_info->category_id));
	if (!empty($category_info)) {
		$category = $category_info->income_category;
	}
} else {
	$category_info = get_row('tbl_expense_category', array('expense_category_id' => $expense_info->category_id));
	if (!empty($category_info)) {
		$category = $category_info->expense_category;
	}
}

$client_name = $this->db->where('client_id', $expense_info->paid_by)->get('tbl_client')->row();
$payment_methods = !empty($expense_info->payment_methods_id)
	? $this->db->where('payment_methods_id', $expense_info->payment_methods_id)->get('tbl_payment_methods')->row()
	: null;
$project_info = !empty($expense_info->project_id)
	? $this->db->where('project_id', $expense_info->project_id)->get('tbl_project')->row()
	: null;

$can_edit = $this->transactions_model->can_action('tbl_transactions', 'edit', array('transactions_id' => $expense_info->transactions_id));
$edited = can_action($is_income ? '30' : '31', 'edited');

$status_label = '';
$status_tone = 'bg-slate-100 text-slate-700';
$status_title = '';
$status_link = '';

if (!$is_income) {
	$status = $expense_info->status;
	$label = 'success';
	$title = '';
	$e_action = '';
	if ($expense_info->project_id != 0) {
		if ($expense_info->billable == 'No') {
			$status = 'not_billable';
			$label = 'primary';
			$title = lang('not_billable');
		} else {
			$status = 'billable';
			$label = 'success';
			$title = lang('billable');
		}
	} else {
		if ($expense_info->status == 'non_approved') {
			$label = 'danger';
			$title = lang('get_approved');
			$e_action = 'approved';
		} elseif ($expense_info->status == 'unpaid') {
			$label = 'warning';
			$title = lang('get_paid');
			$e_action = 'paid';
		}
	}
	$status_map = array(
		'success' => 'bg-emerald-100 text-emerald-700',
		'warning' => 'bg-amber-100 text-amber-700',
		'danger' => 'bg-rose-100 text-rose-700',
		'primary' => 'bg-sky-100 text-sky-700',
		'default' => 'bg-slate-100 text-slate-700',
	);
	$status_tone = isset($status_map[$label]) ? $status_map[$label] : $status_map['default'];
	$status_label = lang($status);
	$status_title = $title;
	$check_head = $this->db->where('department_head_id', $this->session->userdata('user_id'))->get('tbl_departments')->row();
	$role = $this->session->userdata('user_type');
	if ($role == 1 || !empty($check_head)) {
		$status_link = !empty($e_action) ? base_url() . 'admin/transactions/set_status/' . $e_action . '/' . $expense_info->transactions_id : '';
	}
}

$recurring_blocks = array();
if (!$is_income && ($expense_info->recurring == 'Yes' || $expense_info->recurring_from != null)) {
	$show_recurring_expense_info = true;
	$recurring_from = $expense_info;
	$recurring_from->recurring = 1;
	if ($expense_info->recurring_from != null) {
		$recurring_from = get_row('tbl_transactions', array('transactions_id' => $expense_info->transactions_id));
		if ($recurring_from->recurring == 'No') {
			$show_recurring_expense_info = false;
		} else {
			$next_recurring_date_compare = $recurring_from->last_recurring_date;
		}
	} else {
		$next_recurring_date_compare = $recurring_from->date;
		if ($recurring_from->last_recurring_date) {
			$next_recurring_date_compare = $recurring_from->last_recurring_date;
		}
	}
	if ($show_recurring_expense_info) {
		$next_date = date('Y-m-d', safe_strtotime('+' . $recurring_from->recurring . ' ' . strtoupper($recurring_from->recurring_type), safe_strtotime($next_recurring_date_compare)));
	}
	$remaining = ($recurring_from->total_cycles == 0) ? lang('infinity') : ($recurring_from->total_cycles - $recurring_from->done_cycles);
	$recurring_blocks[] = array('label' => lang('recurring'), 'value' => lang('yes'));
	$recurring_blocks[] = array('label' => lang('cycles_remaining'), 'value' => $remaining);
	if (!empty($next_date) && ($recurring_from->total_cycles == 0 || $recurring_from->total_cycles != $recurring_from->done_cycles)) {
		$recurring_blocks[] = array('label' => lang('next_date'), 'value' => display_date($next_date));
	}
	if ($expense_info->recurring_from != null) {
		$recurring_blocks[] = array(
			'label' => lang('source'),
			'html' => '<a class="text-primary font-medium hover:underline" href="' . base_url('admin/transactions/view_details/' . $expense_info->recurring_from) . '">' . html_escape($recurring_from->name) . (!empty($recurring_from->reference) ? ' (#' . html_escape($recurring_from->reference) . ')' : '') . '</a>',
		);
	}
}

$invoice_blocks = array();
if (!empty($expense_info->invoices_id)) {
	$payment_status = $this->invoice_model->get_payment_status($expense_info->invoices_id);
	$invoice_info = $this->db->where('invoices_id', $expense_info->invoices_id)->get('tbl_invoices')->row();
	$paid_amount = $this->invoice_model->calculate_to('paid_amount', $expense_info->invoices_id);
	$invoice_blocks[] = array(
		'label' => lang('reference_no'),
		'html' => '<a class="text-primary font-medium hover:underline" href="' . base_url() . 'admin/invoice/manage_invoice/invoice_details/' . $expense_info->invoices_id . '">' . html_escape($invoice_info->reference_no) . '</a>',
	);
	$invoice_blocks[] = array('label' => lang('payment_status'), 'value' => $payment_status);
	if ($paid_amount > 0) {
		$invoice_blocks[] = array('label' => lang('paid_amount'), 'value' => display_money($paid_amount, $currency->symbol));
	}
}

$journal_blocks = array();
if (!empty($expense_info->journal_id)) {
	$journal_info = $this->db->where('journal_id', $expense_info->journal_id)->get('tbl_journals')->row();
	if (!empty($journal_info)) {
		$journal_blocks[] = array(
			'label' => lang('journal_entry'),
			'html' => '<a class="text-primary font-medium hover:underline" href="' . base_url('admin/accounting/view_journal_entry/' . $journal_info->journal_id) . '">' . html_escape($journal_info->reference_no) . '</a>',
		);
		$journal_blocks[] = array(
			'label' => lang('status'),
			'value' => !empty($journal_info->status) ? $journal_info->status : lang('posted'),
		);
	}
}

$uploaded_file = !empty($expense_info->attachement) ? json_decode($expense_info->attachement) : array();
$attachments_html = '';
if (!empty($uploaded_file)) {
	$items = '';
	foreach ($uploaded_file as $fKey => $v_files) {
		if (empty($v_files)) {
			continue;
		}
		$icon = !empty($v_files->is_image) ? 'image' : 'file-text';
		$items .= '<div class="flex items-center justify-between gap-3 rounded-xl border border-border bg-background/60 px-4 py-3">'
			. '<div class="flex items-center gap-3">'
			. '<span class="inline-flex h-10 w-10 items-center justify-center rounded-xl border border-border bg-card"><i data-lucide="' . $icon . '" class="h-4 w-4 text-muted-foreground"></i></span>'
			. '<div><div class="text-sm font-medium text-foreground">' . html_escape($v_files->fileName) . '</div><div class="text-xs text-muted-foreground">' . lang('attachment') . '</div></div>'
			. '</div>'
			. '<a class="inline-flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted" href="' . base_url() . 'admin/transactions/download/' . $expense_info->transactions_id . '/' . $fKey . '"><i data-lucide="download" class="h-4 w-4"></i>' . lang('download') . '</a>'
			. '</div>';
	}
	$attachments_html = '<div class="space-y-3">' . $items . '</div>';
}

$detail_fields = array(
	array('label' => ($is_income ? lang('deposit') : lang('expense')) . ' ' . lang('prefix'), 'value' => (!empty($expense_info->transaction_prefix) ? $expense_info->transaction_prefix : '-')),
	array('label' => lang('reference'), 'value' => (!empty($expense_info->reference) ? $expense_info->reference : '-')),
	array('label' => lang('date'), 'value' => display_date($expense_info->date)),
	array('label' => lang('account'), 'value' => (!empty($account_info->account_name) ? $account_info->account_name : '-')),
	array('label' => lang('categories'), 'value' => $category),
	array('label' => lang('payment_method'), 'value' => (!empty($payment_methods) ? $payment_methods->method_name : '-')),
	array('label' => lang('paid_by'), 'value' => (!empty($client_name->name) ? $client_name->name : '-')),
	array('label' => lang('project_name'), 'value' => (!empty($project_info->project_name) ? $project_info->project_name : '-')),
	array('label' => lang('tags'), 'html' => get_tags($expense_info->tags, true), 'show_empty' => true),
);

$view = $is_income ? 1 : 2;
$show_custom_fields = custom_form_label($view, $expense_info->transactions_id);
if (!empty($show_custom_fields)) {
	foreach ($show_custom_fields as $c_label => $v_fields) {
		if (!empty($v_fields)) {
			$detail_fields[] = array('label' => $c_label, 'html' => $v_fields, 'show_empty' => true);
		}
	}
}
?>

<div class="space-y-6">
	<div class="rounded-3xl border border-border bg-gradient-to-br from-card via-card to-muted/30 shadow-sm">
		<div class="flex flex-col gap-5 p-6 lg:flex-row lg:items-start lg:justify-between">
			<div class="space-y-4">
				<div class="flex flex-wrap items-center gap-2">
					<span class="inline-flex items-center gap-2 rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.28em] text-primary">
						<i data-lucide="<?= $is_income ? 'arrow-down-left' : 'arrow-up-right' ?>" class="h-3.5 w-3.5"></i>
						<?= $is_income ? lang('deposit') : lang('expense') ?>
					</span>
					<?php if (!$is_income && !empty($status_label)) { ?>
						<?php if (!empty($status_link)) { ?>
							<a href="<?= $status_link ?>" title="<?= html_escape($status_title) ?>" class="inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold <?= $status_tone ?>">
								<?= $status_label ?>
							</a>
						<?php } else { ?>
							<span class="inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold <?= $status_tone ?>">
								<?= $status_label ?>
							</span>
						<?php } ?>
					<?php } ?>
					<?php if (!empty($expense_info->reference)) { ?>
						<span class="inline-flex items-center rounded-full border border-border bg-background/70 px-3 py-1 text-xs font-semibold text-muted-foreground">
							#<?= html_escape($expense_info->reference) ?>
						</span>
					<?php } ?>
				</div>
				<div>
					<h2 class="text-2xl font-semibold tracking-tight text-foreground"><?= html_escape($expense_info->name); ?></h2>
					<p class="mt-1 text-sm text-muted-foreground">
						<?= (!empty($account_info->account_name) ? html_escape($account_info->account_name) : '-') ?>
						<span class="mx-2 text-border">•</span>
						<?= html_escape($category) ?>
						<?php if (!empty($client_name->name)) { ?>
							<span class="mx-2 text-border">•</span>
							<?= html_escape($client_name->name) ?>
						<?php } ?>
					</p>
				</div>
			</div>
		</div>
		<div class="grid gap-3 border-t border-border p-6 md:grid-cols-2 xl:grid-cols-4">
			<div class="rounded-2xl border border-border bg-background/60 p-4">
				<div class="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground"><?= lang('amount') ?></div>
				<div class="mt-2 text-2xl font-semibold text-foreground"><?= display_money($expense_info->amount, $currency->symbol) ?></div>
			</div>
			<div class="rounded-2xl border border-border bg-background/60 p-4">
				<div class="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground"><?= lang('date') ?></div>
				<div class="mt-2 text-lg font-semibold text-foreground"><?= display_date($expense_info->date) ?></div>
			</div>
			<div class="rounded-2xl border border-border bg-background/60 p-4">
				<div class="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground"><?= lang('account') ?></div>
				<div class="mt-2 text-lg font-semibold text-foreground"><?= !empty($account_info->account_name) ? html_escape($account_info->account_name) : '-' ?></div>
			</div>
			<div class="rounded-2xl border border-border bg-background/60 p-4">
				<div class="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground"><?= lang('payment_method') ?></div>
				<div class="mt-2 text-lg font-semibold text-foreground"><?= !empty($payment_methods) ? html_escape($payment_methods->method_name) : '-' ?></div>
			</div>
		</div>
	</div>

	<div class="grid gap-6 xl:grid-cols-[1.25fr_0.75fr]">
		<div class="space-y-6">
			<?= $this->load->view('admin/common/details_grid', array(
				'title' => lang('details'),
				'fields' => $detail_fields,
				'actions' => '',
			), true); ?>

			<?php if (!empty($attachments_html)) { ?>
				<div class="rounded-2xl border border-border bg-card p-5 shadow-sm space-y-4">
					<div class="flex items-center gap-3">
						<span class="inline-flex h-10 w-10 items-center justify-center rounded-xl border border-border bg-background/60">
							<i data-lucide="paperclip" class="h-4 w-4 text-muted-foreground"></i>
						</span>
						<div>
							<h3 class="text-sm font-semibold text-foreground"><?= lang('attachment'); ?></h3>
							<p class="text-xs text-muted-foreground"><?= lang('download') ?> <?= lang('files') ?></p>
						</div>
					</div>
					<?= $attachments_html; ?>
				</div>
			<?php } ?>

			<?php if (!empty($expense_info->notes)) { ?>
				<div class="rounded-2xl border border-border bg-card p-5 shadow-sm space-y-4">
					<div class="flex items-center gap-3">
						<span class="inline-flex h-10 w-10 items-center justify-center rounded-xl border border-border bg-background/60">
							<i data-lucide="sticky-note" class="h-4 w-4 text-muted-foreground"></i>
						</span>
						<div>
							<h3 class="text-sm font-semibold text-foreground"><?= lang('notes'); ?></h3>
							<p class="text-xs text-muted-foreground"><?= $is_income ? lang('deposit') : lang('expense') ?> <?= lang('summary') ?></p>
						</div>
					</div>
					<div class="rounded-xl border border-border bg-background/50 px-4 py-4 text-sm leading-7 text-foreground whitespace-pre-line break-words">
						<?= $expense_info->notes; ?>
					</div>
				</div>
			<?php } ?>
		</div>

		<div class="space-y-6">
			<div class="rounded-2xl border border-border bg-card p-5 shadow-sm">
				<h3 class="text-sm font-semibold text-foreground"><?= lang('transaction') ?> <?= lang('overview') ?></h3>
				<div class="mt-4 space-y-3">
					<div class="rounded-xl border border-border bg-background/50 px-4 py-3">
						<div class="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground"><?= lang('type') ?></div>
						<div class="mt-1 text-sm font-semibold text-foreground"><?= $is_income ? lang('deposit') : lang('expense') ?></div>
					</div>
					<div class="rounded-xl border border-border bg-background/50 px-4 py-3">
						<div class="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground"><?= lang('categories') ?></div>
						<div class="mt-1 text-sm font-semibold text-foreground"><?= html_escape($category) ?></div>
					</div>
					<div class="rounded-xl border border-border bg-background/50 px-4 py-3">
						<div class="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground"><?= lang('paid_by') ?></div>
						<div class="mt-1 text-sm font-semibold text-foreground"><?= !empty($client_name->name) ? html_escape($client_name->name) : '-' ?></div>
					</div>
					<?php if (!empty($project_info->project_name)) { ?>
						<div class="rounded-xl border border-border bg-background/50 px-4 py-3">
							<div class="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground"><?= lang('project_name') ?></div>
							<div class="mt-1 text-sm font-semibold text-foreground"><?= html_escape($project_info->project_name) ?></div>
						</div>
					<?php } ?>
				</div>
			</div>

			<?php if (!empty($recurring_blocks)) { ?>
				<div class="rounded-2xl border border-border bg-card p-5 shadow-sm">
					<h3 class="text-sm font-semibold text-foreground"><?= lang('recurring') ?></h3>
					<div class="mt-4 space-y-3">
						<?php foreach ($recurring_blocks as $block) { ?>
							<div class="rounded-xl border border-border bg-background/50 px-4 py-3">
								<div class="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground"><?= html_escape($block['label']) ?></div>
								<div class="mt-1 text-sm font-semibold text-foreground">
									<?= isset($block['html']) ? $block['html'] : html_escape($block['value']) ?>
								</div>
							</div>
						<?php } ?>
					</div>
				</div>
			<?php } ?>

			<?php if (!empty($invoice_blocks)) { ?>
				<div class="rounded-2xl border border-border bg-card p-5 shadow-sm">
					<h3 class="text-sm font-semibold text-foreground"><?= lang('invoice') ?></h3>
					<div class="mt-4 space-y-3">
						<?php foreach ($invoice_blocks as $block) { ?>
							<div class="rounded-xl border border-border bg-background/50 px-4 py-3">
								<div class="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground"><?= html_escape($block['label']) ?></div>
								<div class="mt-1 text-sm font-semibold text-foreground">
									<?= isset($block['html']) ? $block['html'] : html_escape($block['value']) ?>
								</div>
							</div>
						<?php } ?>
					</div>
				</div>
			<?php } ?>

			<?php if (!empty($journal_blocks)) { ?>
				<div class="rounded-2xl border border-border bg-card p-5 shadow-sm">
					<h3 class="text-sm font-semibold text-foreground"><?= lang('journal_entry') ?></h3>
					<div class="mt-4 space-y-3">
						<?php foreach ($journal_blocks as $block) { ?>
							<div class="rounded-xl border border-border bg-background/50 px-4 py-3">
								<div class="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground"><?= html_escape($block['label']) ?></div>
								<div class="mt-1 text-sm font-semibold text-foreground">
									<?= isset($block['html']) ? $block['html'] : html_escape($block['value']) ?>
								</div>
							</div>
						<?php } ?>
					</div>
				</div>
			<?php } ?>
		</div>
	</div>
</div>
