<div class="invoice-modern">
<?php echo message_box('success'); ?>
<?php echo message_box('error'); ?>

<?php
$created = can_action('13', 'created');
$edited = can_action('13', 'edited');
$deleted = can_action('13', 'deleted');

$invoice_info = isset($invoice_info) ? $invoice_info : null;
$project_info = isset($project_info) ? $project_info : null;

$invoice_id = !empty($invoice_info) && !empty($invoice_info->invoices_id) ? $invoice_info->invoices_id : null;

$client_id = isset($client_id) ? $client_id : '';
if (empty($client_id)) {
	if (!empty($project_info) && !empty($project_info->client_id)) {
		$client_id = $project_info->client_id;
	} elseif (!empty($invoice_info) && !empty($invoice_info->client_id)) {
		$client_id = $invoice_info->client_id;
	} elseif (!empty($c_id)) {
		$client_id = $c_id;
	}
}

$client_label = isset($client_label) ? $client_label : '';

$project_id = isset($project_id) ? $project_id : '';
if (empty($project_id)) {
	if (!empty($project_info) && !empty($project_info->project_id)) {
		$project_id = $project_info->project_id;
	} elseif (!empty($invoice_info) && !empty($invoice_info->project_id)) {
		$project_id = $invoice_info->project_id;
	}
}

$project_label = isset($project_label) ? $project_label : '';

$reference_no = '';
if (!empty($invoice_info) && !empty($invoice_info->reference_no)) {
	$reference_no = $invoice_info->reference_no;
} else {
	if (empty(config_item('invoice_number_format'))) {
		$reference_no .= config_item('invoice_prefix');
	}
	if (config_item('increment_invoice_number') == 'FALSE') {
		$this->load->helper('string');
		$reference_no .= random_string('nozero', 6);
	} else {
		$reference_no .= $this->invoice_model->generate_invoice_number();
	}
}

$invoice_date = !empty($invoice_info) && !empty($invoice_info->invoice_date) ? $invoice_info->invoice_date : date('Y-m-d');
$due_date = !empty($invoice_info) && !empty($invoice_info->due_date) ? $invoice_info->due_date : date('Y-m-d', safe_strtotime('+' . config_item('invoices_due_after') . ' days'));

$recurring_enabled = !empty($invoice_info) && $invoice_info->recurring == 'Yes';
if ($recurring_enabled) {
	$recur_start_date = date('Y-m-d', safe_strtotime($invoice_info->recur_start_date));
	$recur_end_date = date('Y-m-d', safe_strtotime($invoice_info->recur_end_date));
} else {
	$recur_start_date = date('Y-m-d');
	$recur_end_date = date('Y-m-d');
}

$warehouse_list = isset($warehouse_list) ? $warehouse_list : array();
$tax_rates = isset($tax_rates) ? $tax_rates : array();
$items = !empty($invoice_info) ? $this->invoice_model->ordered_items_by_id($invoice_info->invoices_id) : array();

$show_quantity_as = !empty($invoice_info) && !empty($invoice_info->show_quantity_as) ? $invoice_info->show_quantity_as : 'qty';
$discount_percent = !empty($invoice_info) && !empty($invoice_info->discount_percent) ? $invoice_info->discount_percent : 0;
$adjustment = !empty($invoice_info) && !empty($invoice_info->adjustment) ? $invoice_info->adjustment : 0;
$discount_type = !empty($invoice_info) && !empty($invoice_info->discount_type) ? $invoice_info->discount_type : '';

$currency = isset($default_currency_info) ? $default_currency_info : $this->invoice_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
$currency_symbol = !empty($currency->symbol) ? $currency->symbol : '';
$warehouse_selected = !empty($invoice_info) && !empty($invoice_info->warehouse_id) ? $invoice_info->warehouse_id : '';

$agent_options = isset($agent_options) ? $agent_options : array('' => lang('select') . ' ' . lang('sales') . ' ' . lang('agent'));
$selected_agent = !empty($invoice_info) && !empty($invoice_info->user_id) ? $invoice_info->user_id : $this->session->userdata('user_id');

$permissionL = !empty($invoice_info) && !empty($invoice_info->permission) ? $invoice_info->permission : null;

$client_created = can_action('4', 'created');
$new_client_link = '';
if (!empty($client_created)) {
	$new_client_link = form_lookup_add_link('client_id', base_url('admin/client/new_client'), lang('new') . ' ' . lang('client'), 'md');
}
?>

<div class="space-y-6">
	<?php if (!empty($created) || !empty($edited)) { ?>
		

		<?php if (!empty($invoice_info) && !empty($invoices_to_merge)) { ?>
			<div class="rounded-2xl border border-border bg-card p-6 shadow-sm" id="invoice_top_info">
				<?php $this->load->view('admin/invoice/merge_invoice', array('invoices_to_merge' => $invoices_to_merge)); ?>
			</div>
		<?php } ?>

		<?= form_open(base_url('admin/invoice/save_invoice/' . $invoice_id), array('class' => 'space-y-6', 'data-parsley-validate' => '', 'novalidate' => '', 'enctype' => 'multipart/form-data')); ?>
		<div class="grid grid-cols-1 gap-6 xl:grid-cols-12">
			<div class="min-w-0 space-y-6 xl:col-span-9">
				<div class="rounded-xl border border-border bg-card p-6 space-y-5">
					<div class="flex flex-wrap items-center justify-between gap-3 border-b border-border pb-3">
						<div class="flex items-center gap-2 text-sm font-semibold text-foreground">
							<i data-lucide="file-text" class="h-5 w-5"></i>
							<h2 class="text-base font-semibold text-foreground"><?= lang('invoice') . ' ' . lang('details') ?></h2>
						</div>
						<button type="button" id="toggle_recurring" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted">
							<i data-lucide="repeat" class="h-4 w-4"></i>
							<?= lang('recurring') ?>
						</button>
					</div>

					<div class="grid grid-cols-1 gap-5 sm:grid-cols-2">
						<?= form_input_group('reference_no', lang('reference_no'), $reference_no, 'text', true, array('placeholder' => lang('reference_no'))); ?>


						<?= form_datepicker('invoice_date', lang('invoice_date'), $invoice_date, true,['data-max' => '#due_date', 'data-auto-close' => 'true']); ?>

						<?= form_datepicker('due_date', lang('due_date'), $due_date, true,['data-min' => '#invoice_date', 'data-auto-close' => 'true']); ?>

						<?php
						$project_lookup = form_lookup_group(
							'project_id',
							lang('project'),
							$project_id,
							$project_label,
							false,
							array('placeholder' => lang('select') . ' ' . lang('project')),
							'md:col-span-1',
							array(
								'type' => 'project',
								'depends' => 'client_id',
							)
						);
						$client_lookup = form_lookup_group(
							'client_id',
							lang('client'),
							$client_id,
							$client_label,
							true,
							array('placeholder' => lang('select') . ' ' . lang('client')),
							'md:col-span-1',
							array(
								'type' => 'client',
								'append' => $new_client_link,
							)
						);
						?>
						<?= $client_lookup ?>
						<?= $project_lookup ?>

						<?php if (!empty($warehouse_list)) { ?>
							<?php
							$warehouse_options = array('' => lang('select') . ' ' . lang('warehouse'));
							foreach ($warehouse_list as $warehouse) {
								$warehouse_options[$warehouse->warehouse_id] = $warehouse->warehouse_name;
							}
							?>
							<?= form_select_group('warehouse_id', lang('warehouse'), $warehouse_options, $warehouse_selected, false); ?>
						<?php } ?>
					</div>

					<div id="recurring_fields" class="rounded-xl border border-dashed border-border p-4 space-y-4 <?= $recurring_enabled ? '' : 'hidden' ?>">
						<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
							<?= form_select_group(
								'recuring_frequency',
								lang('recur_frequency'),
								array(
									'none' => lang('none'),
									'7D' => lang('week'),
									'1M' => lang('month'),
									'3M' => lang('quarter'),
									'6M' => lang('six_months'),
									'1Y' => lang('1year'),
									'2Y' => lang('2year'),
									'3Y' => lang('3year'),
								),
								!empty($invoice_info) && !empty($invoice_info->recur_frequency) ? $invoice_info->recur_frequency : 'none'
							); ?>
							<?= form_datepicker('recur_start_date', lang('start_date'), $recur_start_date, false, array('data-format' => config_item('date_picker_format'))); ?>
							<?= form_datepicker('recur_end_date', lang('end_date'), $recur_end_date, false, array('data-format' => config_item('date_picker_format'))); ?>
						</div>
					</div>

					<?php
					$this->load->view('admin/common/sales_items_editor', array(
						'items' => $items,
						'tax_rates' => $tax_rates,
						'show_quantity_as' => $show_quantity_as,
						'discount_percent' => $discount_percent,
						'discount_type' => $discount_type,
						'adjustment' => $adjustment,
						'currency_symbol' => $currency_symbol,
						'itemType' => 'invoice',
					));
					?>
				</div>

				<div class="rounded-xl border border-border bg-card p-6">
					<?= form_editor('notes', lang('notes'), !empty($invoice_info) && !empty($invoice_info->notes) ? $invoice_info->notes : $this->config->item('default_terms'), false); ?>
				</div>
			</div>

			<aside class="min-w-0 space-y-6 xl:col-span-3">
				<div class="rounded-xl border border-border bg-card p-6 space-y-5">
					<div class="flex items-center gap-2 text-sm font-semibold text-foreground border-b border-border pb-2">
						<i data-lucide="settings" class="h-5 w-5"></i>
						<h2 class="text-base font-semibold text-foreground"><?= lang('settings') ?></h2>
					</div>
					<div class="grid grid-cols-1 gap-4">
						<?= form_select_group('user_id', lang('sales') . ' ' . lang('agent'), $agent_options, $selected_agent, true); ?>
						<?= form_tags_group(!empty($invoice_info) && !empty($invoice_info->tags) ? $invoice_info->tags : ''); ?>

						<?php if (!empty($project_id)) { ?>
							<?= form_switch_radio('client_visible', lang('visible_to_client'), !empty($invoice_info) && !empty($invoice_info->client_visible) ? $invoice_info->client_visible : 'No'); ?>
						<?php } ?>

						<?php
						$all_payment = get_result('tbl_online_payment');
						if (!empty($all_payment)) {
							foreach ($all_payment as $payment) {
								$allow_gateway = 'allow_' . slug_it(strtolower($payment->gateway_name));
								$gateway_status = slug_it(strtolower($payment->gateway_name)) . '_status';
								if (config_item($gateway_status) == 'active') { ?>
									<label class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground">
										<input type="checkbox" name="<?= $allow_gateway ?>" value="Yes" <?= (!empty($invoice_info) && $invoice_info->$allow_gateway == 'Yes') ? 'checked' : '' ?>>
										<span><?= lang($allow_gateway) ?></span>
									</label>
						<?php }
							}
						}
						?>
					</div>
				</div>
				<?= form_permission_modern($permission_user, $permissionL); ?>

				<div class="rounded-xl border border-border bg-card p-6 space-y-4">
					<div class="flex items-center gap-2 text-sm font-semibold text-foreground border-b border-border pb-2">
						<i data-lucide="list" class="h-5 w-5"></i>
						<h2 class="text-base font-semibold text-foreground"><?= lang('custom_field') ?></h2>
					</div>
					<?= custom_form_Fields(9, $invoice_id); ?>
				</div>
			</aside>
		</div>

		<div class="flex flex-wrap justify-end gap-3">
			<button type="submit" name="save_as_draft" value="1" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-semibold text-foreground hover:bg-muted">
				<i data-lucide="file" class="h-4 w-4"></i>
				<?= lang('save_as_draft') ?>
			</button>
			<button type="submit" class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500">
				<i data-lucide="check" class="h-4 w-4"></i>
				<?= lang('save') . ' ' . lang('invoice') ?>
			</button>
		</div>
		<?= form_close(); ?>
	<?php } else { ?>
		<div class="rounded-2xl border border-border bg-card p-6 text-sm text-muted-foreground">
			<?= lang('you_dont_have_permission') ?>
		</div>
	<?php } ?>
</div>

<script>
	document.addEventListener("DOMContentLoaded", function() {
		var toggle = document.getElementById("toggle_recurring");
		var recurring = document.getElementById("recurring_fields");
		if (toggle && recurring) {
			toggle.addEventListener("click", function() {
				recurring.classList.toggle("hidden");
			});
		}
	});
</script>

</div>
