<?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');

$kanban = $this->session->userdata('task_kanban');
$uri_segment = $this->uri->segment(4);
if (!empty($kanban)) {
	$tasks = 'kanban';
} elseif ($uri_segment == 'kanban') {
	$tasks = 'kanban';
} else {
	$tasks = 'list';
}

if ($tasks == 'kanban') {
	$text = 'list';
} else {
	$text = 'kanban';
}

$task_kpis = isset($task_kpis) ? $task_kpis : null;
$total_tasks = !empty($task_kpis->total_tasks) ? (int) $task_kpis->total_tasks : 0;
$active_tasks = !empty($task_kpis->active_tasks) ? (int) $task_kpis->active_tasks : 0;
$completed_tasks = !empty($task_kpis->completed_tasks) ? (int) $task_kpis->completed_tasks : 0;
$overdue_tasks = !empty($task_kpis->overdue_tasks) ? (int) $task_kpis->overdue_tasks : 0;
$due_today_tasks = !empty($task_kpis->due_today_tasks) ? (int) $task_kpis->due_today_tasks : 0;
$due_soon_tasks = !empty($task_kpis->due_soon_tasks) ? (int) $task_kpis->due_soon_tasks : 0;
$assigned_to_me_tasks = !empty($task_kpis->assigned_to_me_tasks) ? (int) $task_kpis->assigned_to_me_tasks : 0;

$statuses = array(
	'all' => lang('all'),
	'not_started' => lang('not_started'),
	'in_progress' => lang('in_progress'),
	'completed' => lang('completed'),
	'deferred' => lang('deferred'),
	'waiting_for_someone' => lang('waiting_for_someone'),
	'billable' => lang('billable'),
	'non_billable' => lang('non_billable'),
	'assigned_to_me' => lang('assigned_to_me'),
);

$current_filter = (!empty($active) && $active !== 1) ? $active : 'all';
$kanban_columns = array();
$kanban_items = array();
$page_size = 6;
$load_label = lang('load_more');
if ($load_label === 'load_more') {
	$load_label = 'Load more';
}

$status_map = array(
	'1' => 'not_started',
	'2' => 'in_progress',
	'3' => 'completed',
	'4' => 'deferred',
	'5' => 'waiting_for_someone',
);
$status_tones = array(
	'1' => 'slate',
	'2' => 'blue',
	'3' => 'emerald',
	'4' => 'amber',
	'5' => 'rose',
);

if ($tasks == 'kanban') {
	$status_counts = array();
	$count_query = $this->db
		->select('task_status, COUNT(*) AS total', false)
		->from('tbl_task')
		->group_by('task_status');

	if (!empty($this->tasks_model)) {
		$this->tasks_model->staff_query('tbl_task');
	}

	$count_rows = $count_query->get()->result();
	if (!empty($count_rows)) {
		foreach ($count_rows as $row) {
			$status_counts[$row->task_status] = (int) $row->total;
		}
	}

	foreach ($status_map as $status_id => $status_key) {
		$kanban_columns[] = array(
			'id' => (string) $status_id,
			'label' => lang($status_key),
			'tone' => $status_tones[$status_id] ?? 'slate',
			'total' => $status_counts[$status_key] ?? 0,
		);
	}

	foreach ($status_map as $status_id => $status_key) {
		$tasks_query = $this->db
			->select('tbl_task.task_id, tbl_task.task_name, tbl_task.task_status, tbl_task.task_progress, tbl_task.task_start_date, tbl_task.due_date')
			->select('COALESCE(task_comments.comment_count, 0) AS comment_count', false)
			->select('COALESCE(task_attachments.attachment_count, 0) AS attachment_count', false)
			->from('tbl_task')
			->join('(SELECT module_field_id, COUNT(*) AS comment_count FROM tbl_task_comment WHERE module="tasks" GROUP BY module_field_id) AS task_comments', 'task_comments.module_field_id = tbl_task.task_id', 'left')
			->join('(SELECT module_field_id, COUNT(*) AS attachment_count FROM tbl_attachments WHERE module="tasks" GROUP BY module_field_id) AS task_attachments', 'task_attachments.module_field_id = tbl_task.task_id', 'left')
			->where('tbl_task.task_status', $status_key)
			->order_by('tbl_task.index_no', 'asc')
			->order_by('tbl_task.task_id', 'desc')
			->limit($page_size);

		if (!empty($this->tasks_model)) {
			$this->tasks_model->staff_query('tbl_task');
		}

		$status_tasks = $tasks_query->get()->result();
		if (!empty($status_tasks)) {
			foreach ($status_tasks as $task) {
				$progress = (int) $task->task_progress;
				if ($task->task_status === 'completed') {
					$progress = 100;
				}
				if ($progress > 100) {
					$progress = 100;
				}

				$subtitle_parts = array();
				if (!empty($task->task_start_date)) {
					$subtitle_parts[] = display_date($task->task_start_date);
				}
				if (!empty($task->due_date)) {
					$subtitle_parts[] = display_date($task->due_date);
				}

				$kanban_items[] = array(
					'id' => (int) $task->task_id,
					'title' => $task->task_name,
					'subtitle' => !empty($subtitle_parts) ? implode(' • ', $subtitle_parts) : '',
					'progress' => $progress,
					'status' => (string) $status_id,
					'status_label' => lang($status_key),
					'status_tone' => $status_tones[$status_id] ?? 'slate',
					'link' => base_url('admin/tasks/details/' . $task->task_id),
					'comments' => (int) $task->comment_count,
					'attachments' => (int) $task->attachment_count,
				);
			}
		}
	}
}

$page_meta = $this->load->view('admin/common/erp/badge', array(
	'label' => lang('tasks'),
	'tone' => 'primary',
	'icon' => 'list-checks',
), true);

$task_tabs = array();
foreach ($statuses as $key => $label) {
	$count_key = $key === 'all' ? null : $key . '_tasks';
	$tab_count = $key === 'all' ? $total_tasks : (!empty($task_kpis) && isset($task_kpis->{$count_key}) ? (int) $task_kpis->{$count_key} : 0);
	$task_tabs[] = array(
		'label' => $label,
		'count' => $tab_count,
		'active' => $current_filter === $key,
		'attrs' => array(
			'data-task-filter' => $key === 'all' ? '' : $key,
			'data-task-tab' => $key,
			'aria-pressed' => $current_filter === $key ? 'true' : 'false',
		),
	);
}
?>

<div class="erp-page">


	<div class="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-6">
		<?= $this->load->view('admin/common/erp/stat_card', array(
			'label' => lang('total') . ' ' . lang('tasks'),
			'value' => $total_tasks,
			'hint' => lang('all_time'),
			'icon' => 'list-checks',
			'tone' => 'neutral',
		), true); ?>
		<?= $this->load->view('admin/common/erp/stat_card', array(
			'label' => lang('active') . ' ' . lang('tasks'),
			'value' => $active_tasks,
			'hint' => 'Open queue',
			'icon' => 'activity',
			'tone' => 'primary',
		), true); ?>
		<?= $this->load->view('admin/common/erp/stat_card', array(
			'label' => lang('overdue'),
			'value' => $overdue_tasks,
			'hint' => 'Past due',
			'icon' => 'triangle-alert',
			'tone' => 'danger',
		), true); ?>
		<?= $this->load->view('admin/common/erp/stat_card', array(
			'label' => lang('due_date'),
			'value_html' => '<span class="inline-flex items-end gap-2"><span>' . $due_today_tasks . '</span><span class="text-sm font-medium text-muted-foreground">' . $due_soon_tasks . ' / 7d</span></span>',
			'hint' => 'Today / this week',
			'icon' => 'calendar-range',
			'tone' => 'warning',
		), true); ?>
		<?= $this->load->view('admin/common/erp/stat_card', array(
			'label' => lang('completed'),
			'value' => $completed_tasks,
			'hint' => 'Closed tasks',
			'icon' => 'check-circle-2',
			'tone' => 'success',
		), true); ?>
		<?= $this->load->view('admin/common/erp/stat_card', array(
			'label' => lang('assigned_to_me'),
			'value' => $assigned_to_me_tasks,
			'hint' => 'My queue',
			'icon' => 'user-check',
			'tone' => 'neutral',
		), true); ?>
	</div>

	<?php if ($tasks == 'kanban') { ?>
		<link rel="stylesheet" href="<?= base_url() ?>assets/plugins/kanban/kanban.css" />
		<section class="erp-panel">
			<div class="erp-section-header">
				<div>
					<p class="erp-section-title"><?= lang('kanban') ?></p>
					<p class="erp-section-subtitle">Status-based board with compact column counts.</p>
				</div>
			</div>
			<div class="erp-panel-body">
				<div class="kanban" data-kanban
					data-sort-url-base="<?= base_url('admin/tasks/change_tasks_status/') ?>"
					data-load-url-base="<?= base_url('admin/tasks/load_status_tasks/') ?>"
					data-page-size="<?= (int) $page_size ?>"
					data-load-label="<?= html_escape($load_label) ?>"
					data-columns='<?= html_escape(json_encode($kanban_columns)) ?>'
					data-items='<?= html_escape(json_encode($kanban_items)) ?>'>
					<div class="kanban-board"></div>
				</div>
			</div>
		</section>
		<script src="<?= base_url() ?>assets/plugins/kanban/kanban.js"></script>
	<?php } else { ?>
		<?php
		$task_bulk_actions = '';
		if (!empty($edited)) {
			$task_bulk_actions .= '<button type="button" class="hidden inline-flex items-center gap-2 whitespace-nowrap rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-xs font-semibold text-emerald-700 shadow-sm transition hover:bg-emerald-100 dark:border-emerald-800/60 dark:bg-emerald-900/30 dark:text-emerald-300 dark:hover:bg-emerald-900/40" id="taskBulkComplete"><i data-lucide="check" class="h-4 w-4"></i><span>' . lang('complete') . '</span></button>';
		}
		$task_filter_toolbar = '';
		ob_start();
		?>
		<table class="min-w-full text-xs bulk_table DataTables" id="DataTables" cellspacing="0" width="100%">
			<thead class="bg-slate-50 text-slate-500 dark:bg-slate-800 dark:text-slate-300">
				<tr>
					<?php if (!empty($deleted) || !empty($edited)) { ?>
						<th class="px-3 py-2.5 text-left w-10" data-orderable="false">
							<label class="inline-flex h-4 w-4 items-center justify-center">
								<input id="select_all" type="checkbox" class="h-4 w-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20">
							</label>
						</th>
					<?php } ?>
					<th class="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide"><?= lang('task_name') ?></th>
					<th class="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide"><?= lang('status') ?></th>
					<th class="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide"><?= lang('due_date') ?></th>
					<th class="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide"><?= lang('project') . ' / ' . lang('categories') ?></th>
					<th class="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide"><?= lang('assigned_to') ?></th>
					<th class="col-options no-sort px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide"><?= lang('action') ?></th>
				</tr>
			</thead>
			<tbody></tbody>
		</table>
		<?php
		$table_markup = ob_get_clean();

		echo $this->load->view('admin/common/erp/table_shell', array(
			'class' => '',
			'header' => '',
			'toolbar' => $task_filter_toolbar,
			'table' => $table_markup,
		), true);
		?>

		<script type="text/javascript">
			list = base_url + "admin/tasks/tasksList";
			window.erpDatatablePreload = window.erpDatatablePreload || {};
			window.erpDatatablePreload.DataTables = window.erpDatatablePreload.DataTables || {};
			<?php if (!empty($datatable_preload)) { ?>
			window.erpDatatablePreload.DataTables["list"] = <?= json_encode($datatable_preload, JSON_UNESCAPED_SLASHES) ?>;
			<?php } ?>
			bulk_url = base_url + "admin/tasks/bulk_delete";

			(function($) {
				let currentTaskFilter = "";
				let currentTaskSearchType = "";

				function getTaskTable() {
					if (!$.fn.dataTable || !$.fn.dataTable.isDataTable('#DataTables')) {
						return null;
					}
					return $('#DataTables').DataTable();
				}

				function buildTasksUrl(filterBy, searchType) {
					let url = base_url + "admin/tasks/tasksList";
					if (!filterBy || filterBy === "all") {
						return url;
					}
					url += "/" + encodeURIComponent(filterBy);
					if (searchType) {
						url += "/" + encodeURIComponent(searchType);
					}
					return url;
				}

				function setTaskSummary(text) {
					const summary = document.getElementById('taskFilterSummary');
					if (summary) {
						summary.textContent = text;
					}
				}

				function setActiveTaskTab(tabKey) {
					document.querySelectorAll('[data-task-tab]').forEach((tab) => {
						const isActive = tabKey && tab.getAttribute('data-task-tab') === tabKey;
						tab.classList.toggle('erp-tab--active', !!isActive);
						tab.setAttribute('aria-pressed', isActive ? 'true' : 'false');
					});
				}

				function applyTaskFilter(filterBy, searchType, summaryLabel, tabKey) {
					currentTaskFilter = filterBy || "";
					currentTaskSearchType = searchType || "";
					setTaskSummary(summaryLabel || "All tasks");
					setActiveTaskTab(tabKey || (searchType ? null : (filterBy || 'all')));

					const url = buildTasksUrl(currentTaskFilter, currentTaskSearchType);
					if (typeof table_url === "function" && getTaskTable()) {
						table_url(url);
					} else {
						list = url;
					}
				}

				function mountTaskToolbar() {
					const wrapper = document.getElementById('DataTables_wrapper');
					if (!wrapper) {
						return;
					}
					

					const searchSlot = document.getElementById('taskTableSearchSlot');
					const lengthEl = wrapper.querySelector('.dataTables_length');
					const searchEl = wrapper.querySelector('.dt-search-box');
					const infoEl = wrapper.querySelector('.dataTables_info');

					if (lengthEl) {
						const infoParent = infoEl ? infoEl.parentNode : null;
						if (infoParent) {
							infoParent.classList.add('flex', 'flex-wrap', 'items-center', 'justify-between', 'gap-3');
						}
						lengthEl.classList.add('order-2', 'ml-auto', 'mt-0');
						if (infoEl) {
							infoEl.classList.add('order-1');
						}
						if (infoParent && lengthEl.parentNode !== infoParent) {
							infoParent.appendChild(lengthEl);
						}
					}
					
					if (searchSlot && searchEl && searchEl.parentNode !== searchSlot) {
						searchSlot.innerHTML = '';
						searchSlot.appendChild(searchEl);
					}

					if (lengthEl) {
						const lengthLabel = lengthEl.querySelector('label');
						const lengthSelect = lengthEl.querySelector('select');
						if (lengthSelect) {
							lengthSelect.classList.add('rounded-md', 'border-0', 'bg-transparent', 'px-1', 'text-xs', 'font-semibold', 'text-foreground', 'outline-none');
						}
					}

					if (searchEl) {
						const searchInput = searchEl.querySelector('input[type="search"]');
						searchEl.classList.add('relative');
						if (searchInput) {
							searchInput.classList.add('h-9', 'w-full', 'min-w-[220px]', 'rounded-lg', 'border', 'border-border', 'bg-white', 'px-3', 'text-sm', 'text-foreground', 'placeholder:text-muted-foreground', 'outline-none', 'focus:border-primary', 'focus:ring-2', 'focus:ring-primary/20', 'dark:border-slate-700', 'dark:bg-slate-900');
							if (!searchInput.getAttribute('placeholder')) {
								searchInput.setAttribute('placeholder', 'Search tasks...');
							}
						}
					}

					if (window.lucide && typeof window.lucide.createIcons === 'function') {
						window.lucide.createIcons();
					}
				}

				function getSelectedTaskIds() {
					return $('#DataTables tbody .js-task-row-check:checked').map(function() {
						return $(this).val();
					}).get();
				}

				function updateTaskSelectionState() {
					const ids = getSelectedTaskIds();
					const bulkBtn = document.getElementById('taskBulkDelete');
					const completeBtn = document.getElementById('taskBulkComplete');
					const meta = document.getElementById('taskBulkMeta');
					const rowChecks = $('#DataTables tbody .js-task-row-check');
					const allChecked = rowChecks.length > 0 && rowChecks.length === ids.length;

					$('#select_all').prop('checked', allChecked);

					if (bulkBtn) {
						bulkBtn.classList.toggle('hidden', ids.length === 0);
					}
					if (completeBtn) {
						completeBtn.classList.toggle('hidden', ids.length === 0);
					}
					if (meta) {
						meta.textContent = ids.length ? ids.length + ' selected' : '';
						meta.classList.toggle('hidden', ids.length === 0);
					}
				}

				window.taskProjectFilter = function(id) {
					applyTaskFilter(id, "by_project", "Filtered by project", null);
				};

				window.taskStaffFilter = function(id) {
					applyTaskFilter(id, "by_staff", "Filtered by staff", null);
				};

				window.taskCategoryFilter = function(id) {
					applyTaskFilter(id, "by_category", "Filtered by category", null);
				};

				$(document).on('click', '[data-task-filter]', function(e) {
					e.preventDefault();
					const filterBy = $(this).data('task-filter') || '';
					const tabKey = $(this).data('task-tab') || 'all';
					const label = $(this).find('span').first().text() || 'All tasks';
					applyTaskFilter(filterBy, '', label, tabKey);
				});

				$(document).on('click', '[data-task-header-filter-action]', function(e) {
					e.preventDefault();
					const $item = $(this);
					const $dropdown = $item.closest('details');
					$dropdown.find('[data-header-filter-item]').removeClass('bg-indigo-50 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300');
					$dropdown.find('[data-header-filter-item]').addClass('text-slate-700 hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800');
					$item.addClass('bg-indigo-50 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300');
					$item.removeClass('text-slate-700 hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800');
					$dropdown.find('[data-header-filter-selected]').text($item.data('task-filter-label') || 'All tasks');
					$dropdown.prop('open', false);
					const filterBy = $item.data('task-filter') || '';
					const searchType = $item.data('task-search') || '';
					const tabKey = $item.data('task-tab') || 'all';
					const label = $item.data('task-filter-label') || 'All tasks';
					applyTaskFilter(filterBy, searchType === 'status' ? '' : searchType, label, tabKey);
				});

				$(document).on('change', '#select_all', function() {
					$('#DataTables tbody .js-task-row-check').prop('checked', this.checked);
					updateTaskSelectionState();
				});

				$(document).on('change', '#DataTables tbody .js-task-row-check', function() {
					updateTaskSelectionState();
				});

				$(document).on('click', '#clearTaskFilters', function() {
					const table = getTaskTable();
					currentTaskFilter = "";
					currentTaskSearchType = "";
					setTaskSummary("All tasks");
					setActiveTaskTab('all');

					if (table) {
						table.search('').draw();
					}
					const searchInput = document.querySelector('#taskTableSearchSlot input[type="search"]');
					if (searchInput) {
						searchInput.value = '';
					}
					applyTaskFilter('', '', 'All tasks', 'all');
				});

				$(document).on('click', '#taskBulkDelete', function() {
					const ids = getSelectedTaskIds();
					if (!ids.length) {
						return;
					}
					if (!window.confirm(<?= json_encode(lang('delete_alert')) ?>)) {
						return;
					}

					$.ajax({
						url: bulk_url,
						type: 'POST',
						dataType: 'json',
						data: {
							ids: ids,
							csrf_token: typeof getCookie === 'function' ? getCookie('csrf_cookie') : ''
						}
					}).always(function() {
						const table = getTaskTable();
						if (table) {
							table.ajax.reload(null, false);
						}
						$('#select_all').prop('checked', false);
						updateTaskSelectionState();
					});
				});

				$(document).on('click', '#taskBulkComplete', function() {
					const ids = getSelectedTaskIds();
					if (!ids.length) {
						return;
					}
					if (!window.confirm(<?= json_encode(lang('complete') . ' ' . lang('selected')) ?>)) {
						return;
					}

					const requests = ids.map(function(taskId) {
						return $.ajax({
							url: base_url + 'admin/tasks/completed_tasks/' + taskId,
							type: 'POST',
							dataType: 'json',
							data: {
								task_progress: 100,
								task_status: 'completed',
								csrf_token: typeof getCookie === 'function' ? getCookie('csrf_cookie') : ''
							}
						});
					});

					$.when.apply($, requests).always(function() {
						const table = getTaskTable();
						if (table) {
							table.ajax.reload(null, false);
						}
						$('#select_all').prop('checked', false);
						updateTaskSelectionState();
					});
				});

				$(document).on('draw.dt', '#DataTables', function() {
					// mountTaskToolbar();
					// updateTaskSelectionState();
				});

				$(function() {
					setActiveTaskTab(<?= json_encode($current_filter) ?>);
					setTaskSummary(<?= json_encode($current_filter === 'all' ? 'All tasks' : ($statuses[$current_filter] ?? 'All tasks')) ?>);
					setTimeout(mountTaskToolbar, 120);
					setTimeout(mountTaskToolbar, 320);
				});
			})(jQuery);
		</script>
	<?php } ?>
</div>
