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

$task_title = !empty($task_details->task_name) ? $task_details->task_name : lang('timesheet');
$task_code = !empty($task_details->task_id) ? 'T-' . $task_details->task_id : '';
$task_project_label = !empty($task_details->project_id) ? lang('project') : lang('task');

$running_timer = !empty($task_details->timer_status) && $task_details->timer_status === 'on';
$running_seconds = (!empty($task_details->start_time) && $running_timer) ? max(0, time() - (int) $task_details->start_time) : 0;
$running_time_label = $this->tasks_model->get_time_spent_pain_result($running_seconds);
$timer_toggle_url = $running_timer
	? base_url('admin/tasks/tasks_timer/off/' . $task_details->task_id)
	: base_url('admin/tasks/tasks_timer/on/' . $task_details->task_id);
$timer_toggle_icon = $running_timer ? 'circle-stop' : 'play';
$timer_toggle_title = $running_timer ? lang('stop_timer') : lang('start_timer');
$timer_toggle_class = $running_timer
	? 'bg-rose-600 hover:bg-rose-500 dark:bg-rose-500 dark:hover:bg-rose-400'
	: 'bg-indigo-600 hover:bg-indigo-500 dark:bg-indigo-500 dark:hover:bg-indigo-400';

$timer_rows = get_result('tbl_tasks_timer', array(
	'task_id' => $task_details->task_id,
	'start_time !=' => 0,
	'end_time !=' => 0,
));
$timer_rows = !empty($timer_rows) ? $timer_rows : array();
usort($timer_rows, function ($a, $b) {
	return (int) $b->start_time <=> (int) $a->start_time;
});

$grouped_timers = array();
$total_all_seconds = 0;
foreach ($timer_rows as $timer_row) {
	if (empty($timer_row->start_time) || empty($timer_row->end_time)) {
		continue;
	}
	$day_key = date('Y-m-d', (int) $timer_row->start_time);
	if (!isset($grouped_timers[$day_key])) {
		$grouped_timers[$day_key] = array(
			'label' => ($day_key === date('Y-m-d'))
				? strtoupper(lang('today') . ', ' . date('F j'))
				: strtoupper(date('F j, Y', (int) $timer_row->start_time)),
			'rows' => array(),
			'total' => 0,
		);
	}
	$seconds = max(0, (int) $timer_row->end_time - (int) $timer_row->start_time);
	$grouped_timers[$day_key]['rows'][] = $timer_row;
	$grouped_timers[$day_key]['total'] += $seconds;
	$total_all_seconds += $seconds;
}
krsort($grouped_timers);

if (!function_exists('task_timesheet_initials')) {
	function task_timesheet_initials($name)
	{
		$name = trim((string) $name);
		if ($name === '') {
			return 'T';
		}
		$parts = preg_split('/\s+/', $name);
		$initials = '';
		foreach ($parts as $part) {
			if ($part === '') {
				continue;
			}
			$initials .= strtoupper(substr($part, 0, 1));
			if (strlen($initials) >= 2) {
				break;
			}
		}
		return $initials !== '' ? $initials : 'T';
	}
}

$avatar_classes = array(
	'bg-blue-100 text-blue-700 dark:bg-blue-500/15 dark:text-blue-300',
	'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300',
	'bg-violet-100 text-violet-700 dark:bg-violet-500/15 dark:text-violet-300',
	'bg-amber-100 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300',
	'bg-rose-100 text-rose-700 dark:bg-rose-500/15 dark:text-rose-300',
);

if (!function_exists('task_timesheet_compact_time')) {
	function task_timesheet_compact_time($seconds)
	{
		$total = max(0, (int) round($seconds));
		$hours = intdiv($total, 3600);
		$minutes = intdiv($total % 3600, 60);
		$remaining = $total % 60;
		return $hours . ':' . str_pad((string) $minutes, 2, '0', STR_PAD_LEFT) . ':' . str_pad((string) $remaining, 2, '0', STR_PAD_LEFT);
	}
}
?>

<div class="space-y-6">
	<section class="rounded-2xl border border-border bg-card shadow-sm">
		<div class="flex flex-col gap-3 p-4 sm:p-5 xl:flex-row xl:items-center xl:justify-between">
			<a href="<?= base_url('admin/tasks/new_timesheet/' . $task_details->task_id) ?>"
			   data-modal-url="<?= base_url('admin/tasks/new_timesheet/' . $task_details->task_id) ?>"
			   data-modal-title="<?= lang('timesheet') ?>"
			   data-modal-size="lg"
			   class="flex min-w-0 flex-1 items-center gap-3 rounded-2xl border border-border bg-background px-4 py-3 shadow-sm transition hover:border-primary/30 hover:bg-muted/30">
				<div class="hidden h-10 w-10 items-center justify-center rounded-xl bg-indigo-600/10 text-indigo-600 sm:flex dark:bg-indigo-500/15 dark:text-indigo-300">
					<i data-lucide="clock-3" class="h-5 w-5"></i>
				</div>
				<div class="min-w-0 flex-1">
					<p class="truncate text-base font-semibold text-foreground sm:text-lg"><?= html_escape($task_title) ?></p>
					<div class="mt-1.5 flex flex-wrap items-center gap-2">
						<span class="inline-flex items-center gap-1 rounded-full border border-border bg-muted/50 px-2 py-0.5 text-[11px] font-semibold text-muted-foreground">
							<i data-lucide="briefcase-business" class="h-3.5 w-3.5"></i>
							<?= html_escape($task_project_label) ?>
						</span>
						<?php if (!empty($task_code)) { ?>
							<span class="inline-flex items-center rounded-full border border-border bg-background px-2 py-0.5 font-mono text-[11px] font-semibold text-foreground">
								<?= html_escape($task_code) ?>
							</span>
						<?php } ?>
						<span class="text-[11px] text-muted-foreground">What are you working on?</span>
					</div>
				</div>
			</a>

			<div class="flex items-center gap-3">
				<div class="flex min-w-[148px] items-center gap-2.5 rounded-2xl border border-border bg-background px-3 py-2 shadow-sm">
					<div class="flex h-9 w-9 items-center justify-center rounded-full bg-muted text-muted-foreground">
						<i data-lucide="timer" class="h-4 w-4"></i>
					</div>
					<div class="min-w-0">
						<p class="text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">Timer</p>
						<p class="mt-0.5 font-mono text-lg font-bold tracking-[0.12em] text-foreground"><?= html_escape(task_timesheet_compact_time($running_seconds)) ?></p>
					</div>
				</div>
				<a href="<?= $timer_toggle_url ?>"
				   data-act="ajax-request"
				   data-action-url="<?= html_escape($timer_toggle_url) ?>"
				   data-reload-page="1"
				   class="inline-flex h-12 w-12 items-center justify-center rounded-2xl text-white shadow-sm transition <?= $timer_toggle_class ?>"
				   title="<?= html_escape($timer_toggle_title) ?>">
					<?php if ($running_timer) { ?>
						<svg viewBox="0 0 24 24" fill="none" class="h-5 w-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
							<circle cx="12" cy="12" r="10"></circle>
							<rect x="9" y="8" width="6" height="8" rx="1"></rect>
						</svg>
					<?php } else { ?>
						<svg viewBox="0 0 24 24" fill="none" class="h-5 w-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
							<polygon points="10,8 16,12 10,16"></polygon>
						</svg>
					<?php } ?>
				</a>
			</div>
		</div>
	</section>

	<section class="space-y-4">
		<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
			<div class="flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
				<i data-lucide="calendar-days" class="h-3.5 w-3.5"></i>
				<span><?= lang('timesheets') ?></span>
			</div>
			<div class="flex flex-wrap items-center gap-2 sm:justify-end">
				<div class="relative w-full sm:w-72">
					<span class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" aria-hidden="true">
						<svg viewBox="0 0 24 24" fill="none" class="h-4 w-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
							<circle cx="11" cy="11" r="7"></circle>
							<path d="M20 20l-3.5-3.5"></path>
						</svg>
					</span>
					<input id="timesheetSearch" type="search" autocomplete="off" placeholder="Search timesheets"
						class="w-full rounded-2xl border border-border bg-background py-2.5 pl-11 pr-4 text-sm text-foreground placeholder:text-muted-foreground shadow-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/20 dark:bg-slate-950/55">
				</div>
				<span class="inline-flex items-center rounded-full border border-border bg-muted/50 px-3 py-1.5 text-[11px] font-semibold text-foreground shadow-sm">
					<?= lang('total') ?>: <?= html_escape(task_timesheet_compact_time($total_all_seconds)) ?>
				</span>
			</div>
		</div>

		<?php if (!empty($grouped_timers)) { ?>
			<?php
			$group_index = 0;
			foreach ($grouped_timers as $group) {
				?>
				<div class="space-y-3" data-timesheet-group="<?= html_escape($group['label']) ?>">
					<div class="flex items-center justify-between gap-3">
						<div class="flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
							<i data-lucide="calendar-days" class="h-3.5 w-3.5"></i>
							<span><?= html_escape($group['label']) ?></span>
						</div>
						<span class="inline-flex items-center rounded-full bg-muted px-2.5 py-1 text-[11px] font-semibold text-foreground">
							<?= lang('total') ?>: <?= html_escape(task_timesheet_compact_time($group['total'])) ?>
						</span>
					</div>

					<div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
						<?php foreach ($group['rows'] as $row_index => $v_timer) {
							$profile_info = $this->db
								->select('fullname, avatar')
								->where('user_id', $v_timer->user_id)
								->get('tbl_account_details')
								->row();
							$fullname = !empty($profile_info->fullname) ? $profile_info->fullname : lang('member');
							$initials = task_timesheet_initials($fullname);
							$avatar_class = $avatar_classes[($group_index + $row_index) % count($avatar_classes)];
							$start_label = display_time($v_timer->start_time, true);
							$end_label = display_time($v_timer->end_time, true);
							$duration_label = $this->tasks_model->get_time_spent_pain_result(max(0, (int) $v_timer->end_time - (int) $v_timer->start_time));
							$reason_label = !empty($v_timer->reason) ? $v_timer->reason : lang('timesheet');
							$edit_url = base_url('admin/tasks/new_timesheet/' . $task_details->task_id . '/' . $v_timer->tasks_timer_id);
							$delete_url = base_url('admin/tasks/update_tasks_timer/' . $v_timer->tasks_timer_id . '/delete_task_timmer');
							?>
							<div id="table-timesheet-<?= $v_timer->tasks_timer_id ?>"
								 data-timesheet-card="1"
								 data-timesheet-search="<?= html_escape(strtolower(trim($task_title . ' ' . $fullname . ' ' . $reason_label . ' ' . $start_label . ' ' . $end_label))) ?>"
								 class="min-w-0 rounded-xl border border-border bg-background p-2.5 shadow-sm transition hover:border-primary/30 hover:bg-muted/20">
								<div class="flex items-start justify-between gap-2.5">
									<div class="flex min-w-0 items-start gap-2">
										<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold uppercase <?= $avatar_class ?>">
											<?= html_escape($initials) ?>
										</div>
										<div class="min-w-0">
											<div class="flex flex-wrap items-center gap-1.5">
												<h4 class="truncate text-xs font-semibold text-foreground"><?= html_escape($task_title) ?></h4>
												<span class="inline-flex items-center rounded-full border border-border bg-muted/50 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">
													<?= html_escape($reason_label) ?>
												</span>
											</div>
											<div class="mt-0.5 flex items-center gap-1 text-[10px] text-muted-foreground">
												<i data-lucide="user" class="h-3 w-3"></i>
												<span><?= html_escape($fullname) ?></span>
											</div>
										</div>
									</div>
									<div class="flex items-center gap-1">
										<?php if (!empty($edited)) { ?>
											<a href="<?= html_escape($edit_url) ?>"
											   data-modal-url="<?= html_escape($edit_url) ?>"
											   data-modal-title="<?= lang('edit') . ' ' . lang('timesheet') ?>"
											   data-modal-size="lg"
											   class="inline-flex h-7 w-7 items-center justify-center rounded-lg border border-border bg-background text-muted-foreground transition hover:border-primary/30 hover:text-foreground">
												<i data-lucide="square-pen" class="h-3.5 w-3.5"></i>
											</a>
										<?php } ?>
										<?php if (!empty($deleted)) { ?>
											<a href="<?= html_escape($delete_url) ?>"
											   data-act="ajax-request"
											   data-action-url="<?= html_escape($delete_url) ?>"
											   data-confirm-message="<?= html_escape(lang('delete_alert')) ?>"
											   data-fade-out-on-success="#table-timesheet-<?= $v_timer->tasks_timer_id ?>"
											   class="inline-flex h-7 w-7 items-center justify-center rounded-lg border border-rose-200 bg-rose-50 text-rose-600 transition hover:bg-rose-100 dark:border-rose-500/30 dark:bg-rose-500/10 dark:text-rose-300 dark:hover:bg-rose-500/20"
											   title="<?= html_escape(lang('delete')) ?>">
												<svg viewBox="0 0 24 24" fill="none" class="h-3.5 w-3.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
													<polyline points="3 6 5 6 21 6"></polyline>
													<path d="M8 6V4h8v2"></path>
													<path d="M6 6l1 14h10l1-14"></path>
													<path d="M10 11v4"></path>
													<path d="M14 11v4"></path>
												</svg>
											</a>
										<?php } ?>
									</div>
								</div>

								<div class="mt-2 flex items-center justify-between gap-2">
									<span class="inline-flex items-center rounded-lg border border-border bg-card px-2 py-1 text-[10px] font-semibold text-foreground">
										<?= html_escape($start_label) ?>
										<span class="mx-1 text-muted-foreground">-</span>
										<?= html_escape($end_label) ?>
									</span>
									<span class="font-mono text-sm font-bold tracking-[0.12em] text-foreground">
										<?= html_escape(task_timesheet_compact_time((int) $v_timer->end_time - (int) $v_timer->start_time)) ?>
									</span>
								</div>
							</div>
							<?php
						} ?>
					</div>
				</div>
				<?php
				$group_index++;
			}
			?>
		<?php } else { ?>
			<div class="rounded-2xl border border-dashed border-border bg-card px-6 py-12 text-center shadow-sm">
				<div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-muted text-muted-foreground">
					<i data-lucide="calendar-x-2" class="h-6 w-6"></i>
				</div>
				<h4 class="mt-4 text-base font-semibold text-foreground"><?= lang('no_data_found') ?></h4>
				<p class="mt-1 text-sm text-muted-foreground"><?= lang('timesheet') ?> <?= lang('not_found') ?></p>
			</div>
		<?php } ?>
	</section>
</div>

<script>
(function () {
	const input = document.getElementById('timesheetSearch');
	if (!input) return;

	const cards = Array.from(document.querySelectorAll('[data-timesheet-card="1"]'));
	const groups = Array.from(document.querySelectorAll('[data-timesheet-group]'));

	const applyFilter = () => {
		const term = (input.value || '').trim().toLowerCase();
		let visibleGroups = 0;

		groups.forEach((group) => {
			let groupVisible = false;
			const cardsInGroup = Array.from(group.querySelectorAll('[data-timesheet-card="1"]'));

			cardsInGroup.forEach((card) => {
				const haystack = (card.dataset.timesheetSearch || '').toLowerCase();
				const visible = !term || haystack.includes(term);
				card.classList.toggle('hidden', !visible);
				if (visible) groupVisible = true;
			});

			group.classList.toggle('hidden', !groupVisible);
			if (groupVisible) visibleGroups++;
		});

		if (!term) {
			groups.forEach((group) => group.classList.remove('hidden'));
			cards.forEach((card) => card.classList.remove('hidden'));
		}
	};

	input.addEventListener('input', applyFilter);
})();
</script>
