<?php echo message_box('success'); ?>
<?php echo message_box('error'); ?>

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

$task_id = !empty($task_info->task_id) ? $task_info->task_id : null;

$category_selected = !empty($task_info->category_id) ? $task_info->category_id : '';
$category_options = !empty($all_customer_group) ? $all_customer_group : [];

$project_selected = !empty($task_info->project_id) ? $task_info->project_id : (!empty($project_id) ? $project_id : '');
$opportunities_selected = !empty($task_info->opportunities_id) ? $task_info->opportunities_id : (!empty($opportunities_id) ? $opportunities_id : '');
$leads_selected = !empty($task_info->leads_id) ? $task_info->leads_id : (!empty($leads_id) ? $leads_id : '');
$bug_selected = !empty($task_info->bug_id) ? $task_info->bug_id : (!empty($bug_id) ? $bug_id : '');
$goal_selected = !empty($task_info->goal_tracking_id) ? $task_info->goal_tracking_id : (!empty($goal_tracking_id) ? $goal_tracking_id : '');
$subtask_selected = !empty($task_info->sub_task_id) ? $task_info->sub_task_id : (!empty($sub_task_id) ? $sub_task_id : '');
$expense_selected = !empty($task_info->transactions_id) ? $task_info->transactions_id : (!empty($transactions_id) ? $transactions_id : '');
$deals_selected = !empty($task_info->module) && $task_info->module === 'deals' ? $task_info->module_field_id : (!empty($deals_id) ? $deals_id : '');

$related_selected = [
	'project' => $project_selected,
	'opportunities' => $opportunities_selected,
	'leads' => $leads_selected,
	'bug' => $bug_selected,
	'goal' => $goal_selected,
	'sub_task' => $subtask_selected,
	'expenses' => $expense_selected,
	'milestones_id' => !empty($task_info->milestones_id) ? $task_info->milestones_id : '',
];

$task_hour_value = '';
if (!empty($task_info->task_hour)) {
	$result = explode(':', $task_info->task_hour);
	$result1 = empty($result[1]) ? 0 : $result[1];
	$task_hour_value = $result[0] . '.' . $result1;
}

$progress_value = !empty($task_info) ? $this->tasks_model->get_task_progress($task_info->task_id) : 0;
$progress_calc = !empty($task_info->calculate_progress) ? $task_info->calculate_progress : '';

$billable_value = !empty($task_info) && $task_info->billable == 'Yes' ? 'Yes' : 'No';
$client_visible_value = !empty($task_info) && $task_info->client_visible == 'Yes' ? 'Yes' : 'No';

$status_options = [
	'not_started' => lang('not_started'),
	'in_progress' => lang('in_progress'),
	'completed' => lang('completed'),
	'deferred' => lang('deferred'),
	'waiting_for_someone' => lang('waiting_for_someone'),
];
$status_selected = !empty($task_info->task_status) ? $task_info->task_status : 'not_started';
$status_styles = [
	'completed' => 'bg-emerald-50 text-emerald-700 border-emerald-200',
	'in_progress' => 'bg-blue-50 text-blue-700 border-blue-200',
	'deferred' => 'bg-rose-50 text-rose-700 border-rose-200',
	'waiting_for_someone' => 'bg-amber-50 text-amber-700 border-amber-200',
	'not_started' => 'bg-slate-100 text-slate-700 border-slate-200',
];
$status_style = isset($status_styles[$status_selected]) ? $status_styles[$status_selected] : $status_styles['not_started'];
$task_form_action = !empty($form_action) ? $form_action : base_url() . 'admin/tasks/save_task/' . (!empty($task_info->task_id) ? $task_info->task_id : '');
$task_back_url = !empty($back_url) ? $back_url : base_url('admin/tasks/all_task');
$task_back_label = !empty($back_label) ? $back_label : lang('all_task');
$task_context = !empty($task_context) ? $task_context : null;
$new_task_url = !empty($new_task_url) ? $new_task_url : base_url('admin/tasks/create');
$context_module = '';
$context_module_id = '';
$context_label = '';
if (!empty($task_context['module']) && !empty($task_context['id'])) {
	$context_module = $task_context['module'];
	$context_module_id = $task_context['id'];
	$context_label = !empty($task_context['label']) ? $task_context['label'] : lang($context_module);
} elseif (!empty($task_info->module) && !empty($task_info->module_field_id)) {
	$context_module = $task_info->module;
	$context_module_id = $task_info->module_field_id;
	$context_label = lang($context_module);
}
$has_locked_context = !empty($context_module) && !empty($context_module_id);


?>

<div class="space-y-6">
	<?php if (!empty($task_context)) { ?>
		<div class="rounded-2xl border border-border bg-card p-5 shadow-sm">
			<div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
				<div>
					<p class="text-[11px] uppercase tracking-[0.22em] text-muted-foreground"><?= !empty($task_context['label']) ? $task_context['label'] : lang($task_context['module']) ?></p>
					<h2 class="mt-2 text-lg font-semibold text-foreground"><?= lang('task') . ' ' . lang('workspace') ?></h2>
					<p class="mt-1 text-sm text-muted-foreground"><?= html_escape($task_context['title']) ?></p>
				</div>
				<a href="<?= $task_context['url'] ?>" class="inline-flex items-center gap-2 rounded-lg border border-border bg-background px-3 py-2 text-sm font-medium text-foreground hover:bg-muted">
					<i data-lucide="folder-open" class="h-4 w-4"></i>
					<?= lang('back_to') . ' ' . (!empty($task_context['label']) ? $task_context['label'] : lang($task_context['module'])) ?>
				</a>
			</div>
		</div>
	<?php } ?>

	<?php
	if (!empty($task_info->task_id)) {
		$summary_due_date = !empty($task_info->due_date) ? display_date($task_info->due_date) : '-';
		$summary_start_date = !empty($task_info->task_start_date) ? display_date($task_info->task_start_date) : '-';
		$summary_estimate = !empty($task_info->task_hour) ? $task_info->task_hour : '-';
		$summary_rate = !empty($task_info->hourly_rate) ? $task_info->hourly_rate : '-';
		$summary_billable_label = ($billable_value === 'Yes') ? lang('yes') : lang('no');
		$summary_billable_class = ($billable_value === 'Yes') ? 'text-emerald-600' : 'text-muted-foreground';
		$can_edit = $this->tasks_model->can_action('tbl_task', 'edit', array('task_id' => $task_info->task_id));
		$participants = array();
		if ($task_info->permission != 'all') {
			$permission = json_decode($task_info->permission);
			$permission_ids = array_keys((array) $permission);
			if (!empty($permission_ids)) {
				$participants = $this->db
					->select('tbl_users.user_id, tbl_users.role_id, tbl_account_details.fullname, tbl_account_details.avatar')
					->from('tbl_users')
					->join('tbl_account_details', 'tbl_account_details.user_id = tbl_users.user_id', 'left')
					->where_in('tbl_users.user_id', $permission_ids)
					->get()->result();
			}
		}
	?>
		<div class="rounded-2xl border border-border bg-card p-6">
			<div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
				<div class="space-y-2">
					<p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('tasks'); ?></p>
					<div class="flex flex-wrap items-center gap-3">
						<h1 class="text-2xl font-semibold text-foreground"><?= !empty($task_info) ? lang('edit') . ' ' . lang('task') : lang('assign_task'); ?></h1>
						<span class="inline-flex items-center rounded-full border px-3 py-1 text-xs font-semibold <?= $status_style ?>">
							<?= lang($status_selected) ?>
						</span>
						<?php if (!empty($task_id)) { ?>
							<span class="inline-flex items-center rounded-full border border-border px-2.5 py-1 text-xs font-semibold text-muted-foreground">
								#<?= $task_id ?>
							</span>
						<?php } ?>
					</div>
				</div>
				<div class="flex flex-wrap items-center gap-2">
					<a href="<?= $task_back_url ?>"
						class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium text-foreground hover:bg-muted">
						<i data-lucide="list" class="h-4 w-4"></i>
						<?= $task_back_label ?>
					</a>
					<?php if (!empty($task_info)) { ?>
						<a href="<?= $new_task_url ?>"
							class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium text-foreground hover:bg-muted">
							<i data-lucide="plus" class="h-4 w-4"></i>
							<?= lang('new') . ' ' . lang('task') ?>
						</a>
					<?php } ?>
				</div>
			</div>

			<div class="mt-4 flex flex-wrap gap-2 text-xs text-muted-foreground">
				<span class="inline-flex items-center gap-2 rounded-full border border-border px-2.5 py-1">
					<i data-lucide="calendar" class="h-3.5 w-3.5"></i>
					<?= lang('start_date') ?>: <?= $summary_start_date ?>
				</span>
				<span class="inline-flex items-center gap-2 rounded-full border border-border px-2.5 py-1">
					<i data-lucide="calendar-clock" class="h-3.5 w-3.5"></i>
					<?= lang('due_date') ?>: <?= $summary_due_date ?>
				</span>
				<span class="inline-flex items-center gap-2 rounded-full border border-border px-2.5 py-1">
					<i data-lucide="timer" class="h-3.5 w-3.5"></i>
					<?= lang('estimated_hour') ?>: <?= $summary_estimate ?>
				</span>
				<span class="inline-flex items-center gap-2 rounded-full border border-border px-2.5 py-1">
					<i data-lucide="coins" class="h-3.5 w-3.5"></i>
					<?= lang('project_hourly_rate') ?>: <?= $summary_rate ?>
				</span>
				<span class="inline-flex items-center gap-2 rounded-full border border-border px-2.5 py-1">
					<i data-lucide="receipt" class="h-3.5 w-3.5"></i>
					<?= lang('billable') ?>: <?= $summary_billable_label ?>
				</span>
				<div class="pl-8 border-l border-slate-200 dark:border-gray-700">
					<div class="flex -space-x-3"> <?php if (!empty($participants)) { ?>
							<?php foreach ($participants as $member) { ?>
								<img class="relative inline-block h-10 w-10 rounded-full object-cover ring-2 ring-white transition-transform hover:z-10 hover:scale-105 dark:ring-gray-800"
									src="<?= base_url() . $member->avatar ?>"
									alt="<?= html_escape($member->fullname); ?>"
									title="<?= html_escape($member->fullname); ?>">
							<?php } ?>
						<?php } else { ?>
							<span data-tooltip="<?= lang('everyone') ?>"
								class="relative flex h-10 w-10 items-center justify-center rounded-full bg-slate-100 ring-2 ring-white text-xs font-bold text-slate-600 dark:bg-gray-700 dark:text-gray-300 dark:ring-gray-800">
								<?= lang('all') ?>
							</span>
						<?php } ?>

						<?php if (!empty($can_edit) && !empty($edited)) { ?>
							<?= btn_modal(
								'admin/tasks/update_users/' . $task_info->task_id,
								'',
								lang('add') . ' ' . lang('participants'),
								'lg',
								'plus',
								array('class' => 'relative flex h-10 w-10 items-center justify-center rounded-full bg-dashed border-2 border-transparent bg-slate-100 text-slate-500 ring-2 ring-white transition-colors hover:bg-slate-200 hover:z-10 dark:bg-gray-700 dark:text-gray-400 dark:ring-gray-800 dark:hover:bg-gray-600')
							); ?>
						<?php } ?>

					</div>
				</div>
			</div>

			<div class="mt-5">
				<div class="flex items-center justify-between text-xs font-semibold text-muted-foreground">
					<span><?= lang('progress') ?></span>
					<span><?= $progress_value ?>%</span>
				</div>
				<div class="mt-2 h-1.5 rounded-full bg-muted">
					<div class="h-1.5 rounded-full bg-indigo-600" style="width: <?= $progress_value ?>%"></div>
				</div>
			</div>
		</div>
	<?php } ?>

	<?= form_open($task_form_action, array('class' => 'space-y-6', 'enctype' => 'multipart/form-data', 'data-parsley-validate' => '', 'novalidate' => '')); ?>

	<?php
	if (!empty($task_info->project_id)) {
		$project_id = $task_info->project_id;
	} elseif (!empty($project_id)) {
		$project_id = $project_id; ?>
		<input type="hidden" name="un_project_id" value="<?php echo $project_id ?>" />
	<?php }
	if (!empty($task_info->opportunities_id)) {
		$opportunities_id = $task_info->opportunities_id;
	} elseif (!empty($opportunities_id)) {
		$opportunities_id = $opportunities_id; ?>
		<input type="hidden" name="un_opportunities_id" value="<?php echo $opportunities_id ?>" />
	<?php }
	if (!empty($task_info->leads_id)) {
		$leads_id = $task_info->leads_id;
	} elseif (!empty($leads_id)) {
		$leads_id = $leads_id; ?>
		<input type="hidden" name="un_leads_id" value="<?php echo $leads_id ?>" />
	<?php }
	if (!empty($task_info->bug_id)) {
		$bug_id = $task_info->bug_id;
	} elseif (!empty($bug_id)) {
		$bug_id = $bug_id; ?>
		<input type="hidden" name="un_bug_id" value="<?php echo $bug_id ?>" />
	<?php }
	if (!empty($task_info->goal_tracking_id)) {
		$goal_tracking_id = $task_info->goal_tracking_id;
	} elseif (!empty($goal_tracking_id)) {
		$goal_tracking_id = $goal_tracking_id; ?>
		<input type="hidden" name="un_goal_tracking_id" value="<?php echo $goal_tracking_id ?>" />
	<?php }
	if (!empty($task_info->sub_task_id)) {
		$sub_task_id = $task_info->sub_task_id;
	} elseif (!empty($sub_task_id)) {
		$sub_task_id = $sub_task_id; ?>
		<input type="hidden" name="un_sub_task_id" value="<?php echo $sub_task_id ?>" />
	<?php }
	if (!empty($task_info->transactions_id)) {
		$transactions_id = $task_info->transactions_id;
	} elseif (!empty($transactions_id)) {
		$transactions_id = $transactions_id; ?>
		<input type="hidden" name="un_transactions_id" value="<?php echo $transactions_id ?>" />
	<?php } ?>
	<?php if ($has_locked_context) { ?>
		<input type="hidden" name="module" value="<?= html_escape($context_module) ?>" />
		<input type="hidden" name="module_field_id" value="<?= html_escape($context_module_id) ?>" />
	<?php } ?>

		<div class="grid grid-cols-1 gap-6 xl:grid-cols-12">
			<div class="min-w-0 space-y-6 xl:col-span-8">
				<div class="min-w-0 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-slate-200 pb-3 dark:border-slate-700">
					<div class="flex items-center gap-2 ">
						<i data-lucide="info" class="h-5 w-5"></i>
						<h2 class="text-base font-semibold text-foreground"><?= lang('task') . ' ' . lang('details') ?></h2>
					</div>
					<?php if (!empty($task_info->task_name)) { ?>
						<span class="inline-flex items-center rounded-full border px-3 py-1 text-xs font-semibold <?= $status_style ?>">
							<?= lang($status_selected) ?>
						</span>
					<?php } ?>
				</div>

				<div class="grid grid-cols-1 gap-5 sm:grid-cols-2">
					<?= form_input_group('task_name', lang('task_name'), !empty($task_info->task_name) ? $task_info->task_name : '', 'text', true, ['placeholder' => lang('task_name')]); ?>

					<?php
					$new_category_link = '';
					$category_created = can_action('125', 'created');
					if (!empty($category_created)) {
						$new_category_link = form_select_add_link('category_id', base_url('admin/tasks/new_category'), lang('new') . ' ' . lang('categories'), 'sm');
					}
					?>
					<?= form_select_group('category_id', lang('categories'), $category_options, $category_selected, false, ['class' => 'select_box', 'data-live-search' => 'true'], '', $new_category_link); ?>


					<?= form_datepicker('task_start_date', lang('start_date'), !empty($task_info->task_start_date) ? $task_info->task_start_date : '', false, ['id' => 'task-start-date', 'data-max' => '#task-end-date', 'data-auto-close' => 'true']); ?>
					<?= form_datepicker('due_date', lang('due_date'), !empty($task_info->due_date) ? $task_info->due_date : '', true, ['id' => 'task-end-date', 'data-min' => '#task-start-date', 'data-auto-close' => 'true']); ?>
					<?= form_input_group('task_hour', lang('estimated_hour'), $task_hour_value, 'number', false, ['step' => '0.01']); ?>
					<?= form_input_group('hourly_rate', lang('project_hourly_rate'), !empty($task_info->hourly_rate) ? $task_info->hourly_rate : '', 'number', false, ['step' => '0.01']); ?>
				</div>
			</div>
			<?= form_editor('task_description', lang('task_description'), !empty($task_info->task_description) ? $task_info->task_description : '', false); ?>
		</div>

		<aside class="min-w-0 space-y-6 xl:col-span-4">
			<div class="min-w-0 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 text-slate-900 mb-3 border-b border-slate-200 pb-2 dark:text-slate-100 dark:border-slate-700">
					<i data-lucide="info" class="h-5 w-5"></i>
					<h2 class="text-base font-semibold text-foreground"><?= lang('additional_info') ?></h2>
				</div>
				<div class="grid grid-cols-1 gap-5 sm:grid-cols-2 xl:grid-cols-1">
					<?= form_select_group('task_status', lang('task_status'), $status_options, $status_selected, true); ?>
					<div class="md:col-span-2 space-y-2">
						<?php if ($has_locked_context) { ?>
							<div class="rounded-xl border border-sky-200/60 bg-sky-50/60 p-4 dark:border-sky-900/40 dark:bg-sky-950/20">
								<p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground"><?= lang('related_to') ?></p>
								<div class="mt-2 inline-flex items-center gap-2 rounded-full border border-sky-200 bg-white px-3 py-1.5 text-sm font-medium text-sky-700 dark:border-sky-900/50 dark:bg-sky-950/30 dark:text-sky-300">
									<i data-lucide="folder-open" class="h-4 w-4"></i>
									<?= html_escape($context_label) ?>
									<span class="text-sky-500">#<?= html_escape($context_module_id) ?></span>
								</div>
							</div>
						<?php } else {
							echo form_related_to_block_auto([
								'selected' => $related_selected,
							]);
						} ?>
					</div>
				</div>


				<div class="space-y-3">
					<?= form_progress_slider('task_progress', lang('progress'), $progress_value, 0, 100, ['id' => 'task_progress_slider']); ?>
					<div class="flex flex-wrap gap-3 text-xs text-muted-foreground">
						<label class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2">
							<input class="select_one" type="checkbox" name="calculate_progress" value="through_sub_tasks" id="through_sub_tasks" <?= $progress_calc == 'through_sub_tasks' ? 'checked' : '' ?>>
							<span><?= lang('through_sub_tasks'); ?></span>
						</label>
						<label class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2">
							<input class="select_one" type="checkbox" name="calculate_progress" value="through_tasks_hours" id="through_tasks_hours" <?= $progress_calc == 'through_tasks_hours' ? 'checked' : '' ?>>
							<span><?= lang('through_tasks_hours'); ?></span>
						</label>
					</div>
				</div>
				<?= form_tags_group(!empty($task_info->tags) ? $task_info->tags : ''); ?>
				<div class="flex items-center gap-5">
					<?= form_switch_radio('billable', lang('billable'), $billable_value, true, [], 'stacked', ['Yes' => lang('yes'), 'No' => lang('no')]); ?>

					<?php if (empty($project_id)) { ?>
						<?= form_switch_radio('client_visible', lang('visible_to_client'), $client_visible_value, true, [], 'stacked', ['Yes' => lang('yes'), 'No' => lang('no')]); ?>
					<?php } ?>
				</div>
			</div>


			<?php
			$permissionL = !empty($task_info->permission) ? $task_info->permission : null;
			echo form_permission_modern($assign_user, $permissionL, lang('assined_to'));
			?>

			<div class="rounded-2xl border border-border bg-card p-6 space-y-4">
				<h2 class="text-base font-semibold text-foreground"><?= lang('custom_fields') ?></h2>
				<?= custom_form_Fields(3, $task_id); ?>
			</div>
		</aside>
	</div>

	<div class="sticky bottom-4 z-20">
		<div class="flex flex-wrap justify-end gap-3 rounded-2xl border border-border bg-card px-4 py-3 shadow-sm">
			<?php if (!empty($task_info)) { ?>
				<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="save" class="h-4 w-4"></i>
					<?= lang('updates') ?>
				</button>
				<button type="button" onclick="goBack()" 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="x" class="h-4 w-4"></i>
					<?= lang('cancel') ?>
				</button>
			<?php } else { ?>
				<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="save" class="h-4 w-4"></i>
					<?= lang('save') ?>
				</button>
			<?php } ?>
		</div>
	</div>
	<?= form_close(); ?>
</div>

<script>
	(function() {
		const range = document.getElementById('task_progress_slider');
		const hidden = document.getElementById('task_progress_slider_hidden');
		const calcInputs = document.querySelectorAll('.select_one');

		const sync = () => {
			if (hidden && range) {
				hidden.value = range.value;
			}
		};

		if (range) {
			range.addEventListener('input', sync);
			sync();
		}

		const toggleRange = () => {
			const checked = Array.from(calcInputs).some((el) => el.checked);
			if (range) range.disabled = checked;
		};

		calcInputs.forEach((el) => {
			el.addEventListener('change', toggleRange);
		});

		toggleRange();
	})();

	document.addEventListener('DOMContentLoaded', () => {
		const rel = document.getElementById('check_related');
		const container = document.getElementById('related_to');
		if (rel && rel.value && rel.value !== '0' && container && !container.children.length) {
			get_related_moduleName(rel.value, null, 4);
		}
	});
</script>
