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

<?php
$created = can_action('54', 'created');
$edited = can_action('54', 'edited');
$lead_id = $leads_details->leads_id;

$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',
);

$page_size = 6;
$load_label = lang('load_more');
if ($load_label === 'load_more') {
	$load_label = 'Load more';
}

$total_query = $this->db->from('tbl_task')->where('leads_id', $lead_id);
$this->items_model->staff_query('tbl_task');
$total_tasks = (int) $total_query->count_all_results();

$active_query = $this->db->from('tbl_task')->where('leads_id', $lead_id)->where('task_status !=', 'completed');
$this->items_model->staff_query('tbl_task');
$active_tasks = (int) $active_query->count_all_results();

$completed_query = $this->db->from('tbl_task')->where('leads_id', $lead_id)->where('task_status', 'completed');
$this->items_model->staff_query('tbl_task');
$completed_tasks = (int) $completed_query->count_all_results();

$overdue_query = $this->db->from('tbl_task')
	->where('leads_id', $lead_id)
	->where('task_progress <', 100)
	->where('due_date <', date('Y-m-d'));
$this->items_model->staff_query('tbl_task');
$overdue_tasks = (int) $overdue_query->count_all_results();

$status_counts = array();
$count_query = $this->db
	->select('task_status, COUNT(*) AS total', false)
	->from('tbl_task')
	->where('leads_id', $lead_id)
	->group_by('task_status');
$this->items_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;
	}
}

$kanban_columns = array();
$kanban_items = array();
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)
		->where('tbl_task.leads_id', $lead_id)
		->order_by('tbl_task.index_no', 'asc')
		->order_by('tbl_task.task_id', 'desc')
		->limit($page_size);

	$this->items_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,
			);
		}
	}
}
?>

<link rel="stylesheet" href="<?= base_url() ?>assets/plugins/kanban/kanban.css" />

<div class="space-y-5">
	<div class="flex flex-wrap items-center justify-between gap-3">
		<div>
			<h3 class="text-base font-semibold text-foreground"><?= lang('tasks') ?></h3>
			<p class="text-sm text-muted-foreground"><?= lang('tasks') ?> overview</p>
		</div>
		<?php if (!empty($created) || !empty($edited)) { ?>
			<a href="<?= base_url() ?>admin/tasks/create/leads/<?= $lead_id ?>"
				class="inline-flex items-center gap-2 rounded-lg bg-slate-900 px-3 py-2 text-xs font-semibold text-white hover:bg-slate-800 dark:hover:bg-slate-700">
				<i data-lucide="plus" class="h-4 w-4"></i>
				<?= lang('new_task') ?>
			</a>
		<?php } ?>
	</div>

	<div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
		<div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
			<div class="flex items-center justify-between">
				<p class="text-[11px] uppercase tracking-widest text-muted-foreground"><?= lang('total') . ' ' . lang('tasks'); ?></p>
				<span class="inline-flex h-9 w-9 items-center justify-center rounded-xl bg-indigo-50 text-indigo-600">
					<i data-lucide="list-checks" class="h-4 w-4"></i>
				</span>
			</div>
			<p class="text-3xl font-bold text-foreground mt-3"><?= $total_tasks; ?></p>
			<p class="text-xs text-muted-foreground mt-1"><?= lang('all_time'); ?></p>
		</div>
		<div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
			<div class="flex items-center justify-between">
				<p class="text-[11px] uppercase tracking-widest text-muted-foreground"><?= lang('active') . ' ' . lang('tasks'); ?></p>
				<span class="inline-flex h-9 w-9 items-center justify-center rounded-xl bg-sky-50 text-sky-600">
					<i data-lucide="activity" class="h-4 w-4"></i>
				</span>
			</div>
			<p class="text-3xl font-bold text-foreground mt-3"><?= $active_tasks; ?></p>
			<p class="text-xs text-muted-foreground mt-1"><?= lang('in_progress'); ?></p>
		</div>
		<div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
			<div class="flex items-center justify-between">
				<p class="text-[11px] uppercase tracking-widest text-muted-foreground"><?= lang('completed'); ?></p>
				<span class="inline-flex h-9 w-9 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600">
					<i data-lucide="check-circle" class="h-4 w-4"></i>
				</span>
			</div>
			<p class="text-3xl font-bold text-foreground mt-3"><?= $completed_tasks; ?></p>
			<p class="text-xs text-muted-foreground mt-1"><?= lang('all_time'); ?></p>
		</div>
		<div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
			<div class="flex items-center justify-between">
				<p class="text-[11px] uppercase tracking-widest text-muted-foreground"><?= lang('overdue'); ?></p>
				<span class="inline-flex h-9 w-9 items-center justify-center rounded-xl bg-rose-50 text-rose-600">
					<i data-lucide="alert-triangle" class="h-4 w-4"></i>
				</span>
			</div>
			<p class="text-3xl font-bold text-foreground mt-3"><?= $overdue_tasks; ?></p>
			<p class="text-xs text-muted-foreground mt-1"><?= lang('due_date'); ?></p>
		</div>
	</div>

	<div class="rounded-2xl border border-border bg-card p-5">
		<p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-4"><?= lang('kanban') ?></p>
		<div class="kanban" data-kanban
			data-sort-url-base="<?= base_url('admin/tasks/change_tasks_status/') ?>"
			data-load-url-base="<?= base_url('admin/leads/load_status_tasks/' . $lead_id . '/') ?>"
			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>
</div>

<script src="<?= base_url() ?>assets/plugins/kanban/kanban.js"></script>
