<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>

<?= message_box('success'); ?>
<?= message_box('error'); ?>
<script src="<?php echo base_url(); ?>assets/plugins/bootstrap-tagsinput/fm.tagator.jquery.js"></script>

<?php
$expense_id = !empty($expense_info) ? $expense_info->transactions_id : null;
$transaction_prefix = !empty($expense_info->transaction_prefix) ? $expense_info->transaction_prefix : ($transaction_prefix_default ?? '');
$expense_name = !empty($expense_info->name) ? $expense_info->name : '';
$selected_account = !empty($expense_info->account_id) ? $expense_info->account_id : '';
$selected_account_label = $selected_account_label ?? '';
$selected_category = !empty($expense_info->category_id) ? $expense_info->category_id : '0';
$selected_payment_method = !empty($expense_info->payment_methods_id) ? $expense_info->payment_methods_id : '0';
$selected_paid_by_id = $selected_paid_by_id ?? '';
$selected_paid_by_label = $selected_paid_by_label ?? '';
$selected_project_id = $selected_project_id ?? '';
$selected_project_label = $selected_project_label ?? '';
$project_client_id = $project_client_id ?? '';
$project_client_label = $project_client_label ?? '';
$expense_date = !empty($expense_info->date) ? $expense_info->date : date('Y-m-d');
$expense_amount = !empty($expense_info->amount) ? $expense_info->amount : '';
$expense_notes = !empty($expense_info->notes) ? $expense_info->notes : '';
$expense_reference = !empty($expense_info->reference) ? $expense_info->reference : '';
$expense_tags = !empty($expense_info->tags) ? $expense_info->tags : '';
$permission_value = !empty($expense_info->permission) ? $expense_info->permission : null;
$disable_account = (!empty($expense_info) && $expense_info->account_id != '0');
$disable_amount = !empty($expense_info);
$billable_checked = (!empty($expense_info) && $expense_info->billable == 'Yes');
$client_visible_checked = (!empty($expense_info) && $expense_info->client_visible == 'Yes');
$page_title = !empty($expense_info) ? (lang('edit') . ' ' . lang('expense')) : lang('new_expense');
$page_subtitle = !empty($transaction_prefix) ? ('#' . $transaction_prefix) : (lang('expense') . ' ' . lang('details'));

$new_account_link = '';
$account_created = can_action('36', 'created');
if (!empty($account_created)) {
	$new_account_link = form_lookup_add_link('account_id', base_url('admin/account/new_account'), lang('new') . ' ' . lang('account'), 'xl');
}

$new_category_link = '';
$category_created = can_action('124', 'created');
if (!empty($category_created)) {
	$new_category_link = form_select_add_link('category_id', base_url('admin/transactions/categories/expense'), lang('new') . ' ' . lang('expense_category'), 'sm');
}

$new_paid_by_link = '';
$paid_by_created = can_action('4', 'created');
if (!empty($paid_by_created)) {
	$new_paid_by_link = form_lookup_add_link('paid_by', base_url('admin/client/new_client'), lang('new') . ' ' . lang('paid_by'), 'xl');
}

$new_payment_link = form_select_add_link('payment_methods_id', base_url('admin/settings/inline_payment_method'), lang('new') . ' ' . lang('payment_method'), 'xl');

$recurring_disabled = !empty($expense_info->recurring_from);
$repeat_every_value = '';
$repeat_every_custom = 1;
$repeat_type_custom = 'month';
if (!empty($expense_info) && $expense_info->recurring == 'Yes') {
	if (!empty($expense_info->custom_recurring)) {
		$repeat_every_value = 'custom';
		$repeat_every_custom = !empty($expense_info->repeat_every) ? $expense_info->repeat_every : 1;
		$repeat_type_custom = !empty($expense_info->recurring_type) ? $expense_info->recurring_type : 'month';
	} else {
		$repeat_every_value = $expense_info->repeat_every . '_' . $expense_info->recurring_type;
	}
}
$cycles_value = isset($expense_info) ? (int) $expense_info->total_cycles : 0;
$page_actions = '<a href="' . base_url('admin/transactions/expense') . '" class="erp-btn"><i data-lucide="list" class="h-4 w-4"></i><span>' . lang('all_expense') . '</span></a>';
$page_meta = $this->load->view('admin/common/erp/badge', array(
	'label' => lang('expense'),
	'tone' => 'danger',
	'icon' => 'arrow-up-right',
), true);
if (!empty($transaction_prefix)) {
	$page_meta .= $this->load->view('admin/common/erp/badge', array(
		'label' => '#' . $transaction_prefix,
		'tone' => 'neutral',
	), true);
}
?>

<?php echo form_open(
	base_url('admin/transactions/save_expense/' . $expense_id),
	array('class' => 'erp-page', 'enctype' => 'multipart/form-data', 'data-parsley-validate' => 'true', 'id' => 'expense-form')
); ?>

<div class="erp-page">
	<?= $this->load->view('admin/common/erp/page_header', array(
		'title' => $page_title,
		'subtitle' => $page_subtitle,
		'actions' => $page_actions,
		'meta' => $page_meta,
	), true); ?>

	<div class="grid gap-4 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]">
		<div class="space-y-4">
			<section class="erp-panel" id="expense-general">
				<?= $this->load->view('admin/common/erp/section_header', array(
					'title' => lang('general'),
					'subtitle' => 'Core expense details used for posting and billing.',
				), true); ?>
				<div class="erp-panel-body grid gap-3 md:grid-cols-2">
					<?= form_input_group('transaction_prefix', lang('expense') . ' ' . lang('prefix'), $transaction_prefix, 'text', true); ?>
					<?= form_input_group('name', lang('name') . '/' . lang('title'), $expense_name, 'text', true, array('placeholder' => lang('enter') . ' ' . lang('name') . '/' . lang('title') . ' ' . lang('for_personal'))); ?>

					<?php if (!empty($selected_project_id)) { ?>
						<?= form_input_group('project_label', lang('project'), $selected_project_label, 'text', false, array('readonly' => 'readonly')); ?>
						<input type="hidden" name="project_id" value="<?= html_escape($selected_project_id); ?>">
					<?php } else { ?>
						<?= form_lookup_group('project_id', lang('project'), '', '', false, array(), '', array('type' => 'project')); ?>
					<?php } ?>

					<?= form_datepicker('date', lang('date'), $expense_date, false, array()); ?>

					<?= form_select_group('category_id', lang('expense_category'), array('0' => lang('none')) + ($expense_category_options ?? array()), $selected_category, false, array('class' => 'select_box'), '', $new_category_link); ?>
					<?php if ($disable_account) { ?>
						<?= form_input_group('account_label', lang('account'), $selected_account_label, 'text', false, array('readonly' => 'readonly')); ?>
						<input type="hidden" name="account_id" value="<?= html_escape($selected_account); ?>">
					<?php } else { ?>
						<?= form_lookup_group('account_id', lang('account'), $selected_account, $selected_account_label, true, array(), '', array('type' => 'account', 'append' => $new_account_link)); ?>
					<?php } ?>

					<?= form_input_group('amount', lang('amount'), $expense_amount, 'text', true, array('data-parsley-type' => 'number', 'disabled' => $disable_amount ? 'disabled' : null)); ?>
				</div>
			</section>

			<section class="erp-panel" id="expense-info">
				<?= $this->load->view('admin/common/erp/section_header', array(
					'title' => lang('additional_info'),
					'subtitle' => 'Payment, client linkage, tags, and references.',
				), true); ?>
				<div class="erp-panel-body grid gap-3 md:grid-cols-2">
					<?= form_select_group('payment_methods_id', lang('payment_method'), array('0' => lang('select_payment_method')) + ($payment_method_options ?? array()), $selected_payment_method, false, array('class' => 'select_box'), '', $new_payment_link); ?>

					<?php if (!empty($project_client_id)) { ?>
						<?= form_input_group('paid_by_label', lang('paid_by'), $project_client_label, 'text', false, array('readonly' => 'readonly')); ?>
						<input type="hidden" name="paid_by" value="<?= html_escape($project_client_id); ?>">
					<?php } else { ?>
						<?= form_lookup_group('paid_by', lang('paid_by'), $selected_paid_by_id, $selected_paid_by_label, false, array(), '', array('type' => 'client', 'append' => $new_paid_by_link)); ?>
					<?php } ?>

					<?= form_tags_group($expense_tags); ?>
					<div class="space-y-1">
						<?= form_input_group('reference', lang('reference'), $expense_reference, 'text', false); ?>
						<p class="text-xs text-muted-foreground"><?= lang('reference_example'); ?></p>
					</div>

					<?= form_textarea_group('notes', lang('notes'), $expense_notes, 4, false, array()); ?>
				</div>
			</section>

			<?php if (!empty($selected_project_id)) { ?>
				<section class="erp-panel">
					<?= $this->load->view('admin/common/erp/section_header', array(
						'title' => lang('billable'),
						'subtitle' => 'Control whether the project expense can be rebilled.',
					), true); ?>
					<div class="erp-panel-body space-y-3">
						<?= form_checkbox('billable', lang('billable'), $billable_checked, false, array('value' => 'Yes')); ?>
						<?= form_checkbox('client_visible', lang('visible_to_client'), $client_visible_checked, false, array('value' => 'Yes')); ?>
					</div>
				</section>
			<?php } ?>

			<section class="erp-panel" id="expense-repeat">
				<?= $this->load->view('admin/common/erp/section_header', array(
					'title' => lang('repeat_every'),
					'subtitle' => 'Keep scheduled expenses predictable without expanding the form.',
				), true); ?>
				<div class="erp-panel-body grid gap-3 md:grid-cols-2">
					<label class="space-y-1 text-sm font-medium text-foreground block">
						<span><?= lang('repeat_every'); ?></span>
						<select name="repeat_every" id="repeat_every" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm" <?= $recurring_disabled ? 'disabled' : ''; ?>>
							<option value="" <?= $repeat_every_value === '' ? 'selected' : ''; ?>><?= lang('no'); ?></option>
							<option value="1_week" <?= $repeat_every_value === '1_week' ? 'selected' : ''; ?>><?= lang('week'); ?></option>
							<option value="2_week" <?= $repeat_every_value === '2_week' ? 'selected' : ''; ?>>2 <?= lang('weeks'); ?></option>
							<option value="1_month" <?= $repeat_every_value === '1_month' ? 'selected' : ''; ?>><?= lang('month'); ?></option>
							<option value="2_month" <?= $repeat_every_value === '2_month' ? 'selected' : ''; ?>>2 <?= lang('months'); ?></option>
							<option value="3_month" <?= $repeat_every_value === '3_month' ? 'selected' : ''; ?>>3 <?= lang('months'); ?></option>
							<option value="6_month" <?= $repeat_every_value === '6_month' ? 'selected' : ''; ?>>6 <?= lang('months'); ?></option>
							<option value="1_year" <?= $repeat_every_value === '1_year' ? 'selected' : ''; ?>><?= lang('year'); ?></option>
							<option value="custom" <?= $repeat_every_value === 'custom' ? 'selected' : ''; ?>><?= lang('custom'); ?></option>
						</select>
					</label>

					<div class="recurring_custom <?= $repeat_every_value === 'custom' ? '' : 'hidden'; ?>">
						<div class="grid gap-3 md:grid-cols-[120px_1fr]">
							<?= form_input_group('repeat_every_custom', lang('custom'), $repeat_every_custom, 'number', false, array('min' => 1)); ?>
							<label class="space-y-1 text-sm font-medium text-foreground block">
								<span><?= lang('repeat_every'); ?></span>
								<select name="repeat_type_custom" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm">
									<option value="day" <?= $repeat_type_custom === 'day' ? 'selected' : ''; ?>><?= lang('days'); ?></option>
									<option value="week" <?= $repeat_type_custom === 'week' ? 'selected' : ''; ?>><?= lang('weeks'); ?></option>
									<option value="month" <?= $repeat_type_custom === 'month' ? 'selected' : ''; ?>><?= lang('months'); ?></option>
									<option value="year" <?= $repeat_type_custom === 'year' ? 'selected' : ''; ?>><?= lang('years'); ?></option>
								</select>
							</label>
						</div>
					</div>

					<div id="cycles_wrapper" class="<?= (!isset($expense_info) || (isset($expense_info) && $expense_info->recurring == 'No')) ? 'hidden' : ''; ?>">
						<label class="space-y-1 text-sm font-medium text-foreground block" for="cycles">
							<span><?= lang('total_cycles'); ?></span>
							<div class="flex items-center gap-2">
								<input type="number" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm" name="total_cycles" id="cycles" value="<?= html_escape($cycles_value); ?>" <?= $cycles_value == 0 ? 'disabled' : ''; ?> <?= (isset($expense_info) && $expense_info->done_cycles > 0) ? 'min="' . (int) $expense_info->done_cycles . '"' : ''; ?>>
								<label class="inline-flex items-center gap-2 text-xs text-muted-foreground">
									<input type="checkbox" id="unlimited_cycles" <?= $cycles_value == 0 ? 'checked' : ''; ?>>
									<?= lang('cycles_infinity'); ?>
								</label>
							</div>
							<?php if (isset($expense_info) && $expense_info->done_cycles > 0) { ?>
								<p class="text-xs text-muted-foreground mt-1"><?= lang('total_cycles_passed', $expense_info->done_cycles); ?></p>
							<?php } ?>
						</label>
					</div>
				</div>
			</section>
		</div>

		<div class="space-y-4">
			<section class="erp-panel" id="expense-attachments">
				<?= $this->load->view('admin/common/erp/section_header', array(
					'title' => lang('attachment'),
					'subtitle' => 'Attach bills, receipts, and vendor documents.',
				), true); ?>
				<div class="erp-panel-body space-y-4">
					<?= form_attachment_group('files[]', lang('attachment'), 'dropzone', array(
						'dropzone_id' => 'expense-files-dropzone',
						'list_id' => 'expense-files-list',
					)); ?>

					<?php
					$uploaded_file = !empty($expense_info->attachement) ? json_decode($expense_info->attachement) : array();
					if (!empty($uploaded_file)) {
					?>
						<div class="space-y-2">
							<p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('existing') . ' ' . lang('attachments'); ?></p>
							<div class="flex flex-wrap gap-3">
								<?php foreach ($uploaded_file as $v_files_image) { ?>
									<div class="group flex min-w-0 max-w-full items-center gap-2 rounded-lg border border-border bg-background px-3 py-2 shadow-sm transition-colors hover:bg-muted/40 dark:bg-slate-900/60 dark:hover:bg-slate-800 sm:max-w-[260px]">
										<div class="flex min-w-0 flex-1 items-center gap-2">
											<span class="flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md border border-border bg-card text-muted-foreground dark:bg-slate-800">
												<i data-lucide="<?= !empty($v_files_image->is_image) ? 'image' : 'file-text'; ?>" class="h-4 w-4"></i>
											</span>
											<span class="min-w-0 truncate text-sm font-medium text-foreground" title="<?= html_escape($v_files_image->fileName); ?>"><?= html_escape($v_files_image->fileName); ?></span>
										</div>
										<button type="button" class="existing_image inline-flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-rose-50 hover:text-rose-600 dark:hover:bg-rose-950/40 dark:hover:text-rose-300" aria-label="<?= lang('delete'); ?>">
											<i data-lucide="x" class="h-4 w-4"></i>
										</button>
										<input type="hidden" name="path[]" value="<?= html_escape($v_files_image->path); ?>">
										<input type="hidden" name="fileName[]" value="<?= html_escape($v_files_image->fileName); ?>">
										<input type="hidden" name="fullPath[]" value="<?= html_escape($v_files_image->fullPath); ?>">
										<input type="hidden" name="size[]" value="<?= html_escape($v_files_image->size); ?>">
										<input type="hidden" name="is_image[]" value="<?= html_escape($v_files_image->is_image); ?>">
									</div>
								<?php } ?>
							</div>
						</div>
					<?php } ?>
				</div>
			</section>

			<?php if (!empty($expense_info)) { ?>
				<input type="hidden" name="amount" value="<?= html_escape($expense_amount); ?>">
				<input type="hidden" name="old_account_id" value="<?= html_escape($selected_account); ?>">
			<?php } ?>

			<section class="erp-panel">
				<?= $this->load->view('admin/common/erp/section_header', array(
					'title' => lang('additional_fields'),
					'subtitle' => 'Custom fields attached to this expense entry.',
				), true); ?>
				<div class="erp-panel-body space-y-4">
					<?php
					$transactions_id = !empty($expense_info) ? $expense_info->transactions_id : null;
					echo custom_form_Fields(2, $transactions_id, true);
					?>
				</div>
			</section>

			<section class="erp-panel" id="expense-permission">
				<?= $this->load->view('admin/common/erp/section_header', array(
					'title' => lang('permission'),
					'subtitle' => 'Restrict access when the expense should stay internal.',
				), true); ?>
				<div class="erp-panel-body space-y-4">
					<?= form_permission_modern($permission_user, $permission_value, lang('assined_to')); ?>
				</div>
			</section>
		</div>
	</div>

	<div class="flex flex-wrap justify-end gap-2 rounded-xl border border-border bg-card px-4 py-3 shadow-sm">
		<?php if (!empty($expense_info)) { ?>
			<?= btn_update('updates', 'sm'); ?>
			<button type="button" onclick="goBack()" class="btn btn-danger btn-sm"><?= lang('cancel'); ?></button>
		<?php } else { ?>
			<?= btn_update('save', 'sm'); ?>
		<?php } ?>
	</div>
</div>

<?php echo form_close(); ?>

<script>
	$(document).ready(function() {
		$(document).on('click', '.existing_image', function() {
			$(this).closest('.rounded-lg').remove();
		});

		function updateRecurring() {
			var repeatVal = $('#repeat_every').val() || '';
			$('.recurring_custom').toggleClass('hidden', repeatVal !== 'custom');
			$('#cycles_wrapper').toggleClass('hidden', repeatVal === '');
		}

		$('#repeat_every').on('change', updateRecurring);
		updateRecurring();

		$('#unlimited_cycles').on('change', function() {
			var isUnlimited = $(this).is(':checked');
			var cyclesInput = $('#cycles');
			if (isUnlimited) {
				cyclesInput.val(0).prop('disabled', true);
			} else {
				cyclesInput.prop('disabled', false);
				if (!cyclesInput.val() || cyclesInput.val() === '0') {
					cyclesInput.val(1);
				}
			}
		});
	});
</script>
