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

<?= message_box('success'); ?>
<?= message_box('error'); ?>

<?php
$can_edit = $this->tickets_model->can_action('tbl_tickets', 'edit', array('tickets_id' => $tickets_info->tickets_id));
$can_delete = $this->tickets_model->can_action('tbl_tickets', 'delete', array('tickets_id' => $tickets_info->tickets_id));
$edited = can_action(6, 'edited');
$deleted = can_action(6, 'deleted');

$pin_where = array('user_id' => $this->session->userdata('user_id'), 'module_id' => $tickets_info->tickets_id, 'module_name' => 'tickets');
$check_existing = $this->tickets_model->check_by($pin_where, 'tbl_pinaction');
if (!empty($check_existing)) {
	$pin_url = 'remove_todo/' . $check_existing->pinaction_id;
	$pin_btn = 'danger';
	$pin_title = lang('remove_todo');
} else {
	$pin_url = 'add_todo_list/tickets/' . $tickets_info->tickets_id;
	$pin_btn = 'warning';
	$pin_title = lang('add_todo_list');
}

$reporter_info = get_row('tbl_account_details', array('user_id' => $tickets_info->reporter));
$department_info = get_row('tbl_departments', array('departments_id' => $tickets_info->departments_id));
$project_info = !empty($tickets_info->project_id) ? get_row('tbl_project', array('project_id' => $tickets_info->project_id)) : null;

$status_value = $tickets_info->status === 'in_progress' ? 'in_progress' : $tickets_info->status;
$status_label = lang($status_value);
$status_tone = 'bg-slate-100 text-slate-700';
if ($tickets_info->status === 'open') {
	$status_tone = 'bg-rose-50 text-rose-700';
} elseif ($tickets_info->status === 'closed') {
	$status_tone = 'bg-emerald-50 text-emerald-700';
} elseif ($tickets_info->status === 'in_progress') {
	$status_tone = 'bg-amber-50 text-amber-700';
} elseif ($tickets_info->status === 'answered') {
	$status_tone = 'bg-blue-50 text-blue-700';
}
$ticket_status_badge = function ($slot) use ($status_tone, $status_label) {
	return '<span data-ticket-status-slot="' . html_escape($slot) . '" class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold ' . $status_tone . '">' . $status_label . '</span>';
};

$reporter_html = '-';
if (!empty($reporter_info)) {
	$reporter_avatar = base_url() . (!empty($reporter_info->avatar) ? $reporter_info->avatar : 'assets/img/user/default_avatar.jpg');
	$reporter_html = '<div class="flex items-center gap-2">'
		. '<img class="h-8 w-8 rounded-full border border-border" src="' . $reporter_avatar . '" alt="' . html_escape($reporter_info->fullname) . '">'
		. '<span>' . html_escape($reporter_info->fullname) . '</span>'
		. '</div>';
}

$fields = array(
	array('label' => lang('ticket_code'), 'value' => $tickets_info->ticket_code),
	array('label' => lang('subject'), 'value' => $tickets_info->subject),
	array('label' => lang('reporter'), 'html' => $reporter_html),
	array('label' => lang('department'), 'value' => !empty($department_info) ? $department_info->deptname : '-'),
	array('label' => lang('priority'), 'value' => $tickets_info->priority),
	array('label' => lang('status'), 'html' => $ticket_status_badge('details')),
	array('label' => lang('tags'), 'html' => get_tags($tickets_info->tags, true)),
	array('label' => lang('created'), 'value' => display_date($tickets_info->created)),
);

if (!empty($tickets_info->last_reply)) {
	$fields[] = array('label' => lang('last_reply'), 'value' => display_datetime($tickets_info->last_reply));
}

$custom_fields = custom_form_label(7, $tickets_info->tickets_id);
if (!empty($custom_fields)) {
	foreach ($custom_fields as $c_label => $v_fields) {
		if (!empty($v_fields)) {
			$fields[] = array('label' => $c_label, 'value' => $v_fields);
		}
	}
}
?>

<div class="space-y-6">
	<div class="rounded-2xl border border-border bg-card p-5 shadow-sm">
		<div class="flex flex-wrap items-start justify-between gap-4">
			<div class="space-y-2">
				<p class="text-xs uppercase tracking-wide text-muted-foreground"><?= lang('tickets'); ?></p>
				<h2 class="text-xl font-semibold text-foreground">[<?= html_escape($tickets_info->ticket_code); ?>] <?= html_escape($tickets_info->subject); ?></h2>
				<div class="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
					<?= $ticket_status_badge('header'); ?>
					<span class="inline-flex rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600"><?= html_escape($tickets_info->priority); ?></span>
					<?php if (!empty($department_info)) { ?>
						<span class="inline-flex rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600"><?= html_escape($department_info->deptname); ?></span>
					<?php } ?>
					<?php if (!empty($project_info)) { ?>
						<a class="text-primary hover:underline" href="<?= base_url('admin/projects/project_details/' . $project_info->project_id); ?>">
							<?= html_escape($project_info->project_name); ?>
						</a>
					<?php } ?>
				</div>
			</div>
			<div class="flex flex-wrap items-center gap-2">
				<?php if (!empty($can_edit) && !empty($edited)) { ?>
					<a href="<?= base_url('admin/tickets/create/edit_tickets/' . $tickets_info->tickets_id); ?>" class="inline-flex items-center gap-2 rounded-lg bg-primary px-3 py-2 text-xs font-semibold text-white hover:bg-primary/90">
						<i data-lucide="square-pen" class="h-4 w-4"></i>
						<?= lang('edit'); ?>
					</a>
					<div class="relative inline-block text-left">
						<!-- Button -->
						<button
							id="statusDropdownBtn"
							type="button"
							class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-semibold text-slate-700 transition hover:bg-slate-50 focus:outline-none dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200 dark:hover:bg-slate-700">
							<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none"
								viewBox="0 0 24 24" stroke="currentColor">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
									d="M4 4v6h6M20 20v-6h-6M4 14a8 8 0 0113.66-5.66M20 10a8 8 0 01-13.66 5.66" />
							</svg>
							<?= lang('change_status'); ?>
							<svg class="h-3 w-3 ml-1" fill="currentColor" viewBox="0 0 20 20">
								<path fill-rule="evenodd"
									d="M5.23 7.21a.75.75 0 011.06.02L10 11.188l3.71-3.96a.75.75 0 111.08 1.04l-4.24 4.52a.75.75 0 01-1.08 0L5.21 8.27a.75.75 0 01.02-1.06z"
									clip-rule="evenodd" />
							</svg>
						</button>

						<!-- Dropdown -->
						<div
							id="statusDropdownMenu"
							class="absolute right-0 z-50 mt-2 hidden w-44 origin-top-right overflow-hidden rounded-lg border border-border bg-card shadow-lg">
							<ul class="py-1 text-sm text-slate-700 dark:text-slate-200">
								<?php
								$status_info = get_result('tbl_status');
								if (!empty($status_info)) {
									foreach ($status_info as $v_status) {
								?>
										<li>
											<?= btn_modal(
												'admin/tickets/change_status/' . $tickets_info->tickets_id . '/' . $v_status->status,
												ucfirst($v_status->status),
												lang('change_status'),
												'md',
												'',
												array('class' => 'block w-full px-4 py-2 text-left text-sm text-foreground transition hover:bg-muted')
											) ?>
										</li>
								<?php
									}
								}
								?>
							</ul>
						</div>
					</div>
				<?php } ?>
				<a data-toggle="tooltip" data-placement="top" title="<?= $pin_title; ?>" href="<?= base_url('admin/projects/' . $pin_url); ?>" 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="pin" class="h-4 w-4"></i>
				</a>
			</div>
		</div>
	</div>

	<div class="grid gap-6 lg:grid-cols-[320px_1fr]">
		<div class="space-y-4">
			<?php $this->load->view('admin/common/details_grid', array(
				'title' => lang('ticket_details'),
				'fields' => $fields,
			)); ?>
		</div>

		<div class="space-y-6">
			<div class="rounded-2xl border border-border bg-card p-5 shadow-sm">
				<h3 class="text-sm font-semibold text-foreground mb-3"><?= lang('ticket_message'); ?></h3>
				<div class="prose max-w-none text-sm text-foreground">
					<?= nl2br($tickets_info->body); ?>
				</div>

				<?php

				$uploaded_file = [];

				// Decode ONLY if value exists and is a string
				if (!empty($tickets_info->upload_file) && is_string($tickets_info->upload_file)) {
					$uploaded_file = json_decode($tickets_info->upload_file);

					// If json is invalid or null, fallback to empty array
					if (!is_array($uploaded_file) && !is_object($uploaded_file)) {
						$uploaded_file = [];
					}
				}

				// Render only if attachments exist
				if (!empty($uploaded_file)) :
				?>
					<div class="mt-4 space-y-3">
						<p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground dark:text-gray-400">
							<?= lang('attachments'); ?>
						</p>

						<div class="grid gap-3 sm:grid-cols-2">
							<?php foreach ($uploaded_file as $fKey => $v_files) :
								if (empty($v_files)) {
									continue;
								}
							?>
								<a href="<?= base_url('admin/tickets/download_file/' . $tickets_info->tickets_id . '/' . $fKey); ?>"
									class="group flex items-center justify-between gap-3 rounded-lg border border-border bg-white px-3 py-2.5 text-sm transition-all hover:border-slate-400 hover:shadow-sm dark:bg-gray-800 dark:border-gray-700 dark:hover:border-gray-500 dark:hover:bg-gray-750">

									<span class="flex items-center gap-3 overflow-hidden">
										<span class="flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-slate-100 text-slate-500 transition-colors group-hover:bg-slate-200 dark:bg-gray-700 dark:text-gray-300 dark:group-hover:bg-gray-600">
											<i data-lucide="<?= !empty($v_files->is_image) ? 'image' : 'file-text'; ?>" class="h-4 w-4"></i>
										</span>

										<span class="truncate font-medium text-foreground dark:text-gray-200">
											<?= html_escape($v_files->fileName); ?>
										</span>
									</span>

									<span class="shrink-0 text-xs text-muted-foreground dark:text-gray-400">
										<?= (int) $v_files->size; ?> <?= lang('kb'); ?>
									</span>
								</a>
							<?php endforeach; ?>
						</div>
					</div>

				<?php endif; ?>
			</div>

			<div class="rounded-xl border border-border bg-card p-5 shadow-sm">
				<div class="mb-4 flex items-center justify-between gap-3">
					<div>
						<h3 class="text-sm font-semibold text-foreground"><?= lang('reply_ticket'); ?></h3>
						<p class="mt-1 text-xs text-muted-foreground">#<?= html_escape($tickets_info->ticket_code); ?></p>
					</div>
					<span class="inline-flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
						<i data-lucide="message-square-reply" class="h-4 w-4"></i>
					</span>
				</div>
				<?php echo form_open(base_url("admin/tickets/save_tickets_reply/" . $tickets_info->tickets_id), array(
					"id" => "tickets-comment-form",
					"class" => "space-y-4",
					"enctype" => "multipart/form-data",
					"role" => "form"
				)); ?>
				<textarea
					name="body"
					rows="5"
					class="reply-body w-full resize-y rounded-lg border border-border bg-input px-3 py-2 text-sm leading-6 text-foreground transition focus:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/20"
					placeholder="<?= lang('tickets') ?> #<?= html_escape($tickets_info->ticket_code); ?> <?= lang('reply'); ?>..."></textarea>
				<?= form_attachment_group('files[]', null, 'dropzone', array(
					'dropzone_id' => 'ticket-reply-dropzone',
					'list_id' => 'ticket-reply-list',
				)); ?>
				<div class="mt-4 flex justify-end border-t border-border pt-4 dark:border-gray-700">
					<button type="submit" id="file-save-button"
						class="inline-flex items-center gap-2 rounded-lg px-5 py-2 text-sm font-medium text-white shadow-sm transition-all btn btn btn-primary">
						<i data-lucide="send" class="h-4 w-4"></i>
						<span><?= lang('reply'); ?></span>
					</button>
				</div>
				<?php echo form_close(); ?>
			</div>

			<div class="rounded-xl border border-border bg-card shadow-sm">
				<div class="flex flex-wrap items-center justify-between gap-3 border-b border-border px-5 py-4">
					<div>
						<h3 class="text-sm font-semibold text-foreground"><?= lang('latest_comments'); ?></h3>
						<p class="mt-1 text-xs text-muted-foreground"><?= lang('reply'); ?> <?= lang('tickets'); ?></p>
					</div>
					<span class="inline-flex items-center gap-2 rounded-full bg-muted px-3 py-1 text-xs font-medium text-muted-foreground">
						<i data-lucide="messages-square" class="h-3.5 w-3.5"></i>
						<span id="ticket-replies-count">
							<?php $ticket_replies_count = $this->db->where(array('tickets_id' => $tickets_info->tickets_id, 'ticket_reply_id' => 0))->count_all_results('tbl_tickets_replies'); ?>
							<?= (int) $ticket_replies_count; ?>
						</span>
					</span>
				</div>
				<div id="ticket-replies-list" class="space-y-4 p-5">
					<?php
					$ticket_replies = $this->db->where(array('tickets_id' => $tickets_info->tickets_id, 'ticket_reply_id' => 0))->order_by('time', 'DESC')->get('tbl_tickets_replies')->result();
					$this->load->view('admin/tickets/tickets_reply', array('ticket_replies' => $ticket_replies));
					?>
				</div>
			</div>
		</div>
	</div>
</div>

<script>
	$(document).ready(function() {
		var saveLabel = <?= json_encode(lang('save')); ?>;
		var replyLabel = <?= json_encode(lang('reply')); ?>;
		var waitLabel = <?= json_encode(lang('please_wait') ?: 'Please wait'); ?>;

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

		function initTicketReplyForms(scope) {
			var $scope = scope ? $(scope) : $(document);

			$scope.find(".ticket-inline-reply-form").each(function() {
				var $form = $(this);
				if ($form.data("ajax-ready")) {
					return;
				}
				$form.data("ajax-ready", true);
				$form.appForm({
					isModal: false,
					onSuccess: function(result) {
						var $submit = $form.find(".ticket-inline-reply-submit");
						$form.find(".reply_comments").val("");
						$submit.removeClass("disabled").html('<i data-lucide="send" class="h-4 w-4"></i><span>' + saveLabel + '</span>');
						$(result.data).insertBefore($form.closest(".ticket-inline-reply"));
						$form.closest(".ticket-inline-reply").slideUp(160);
						refreshTicketIcons();
						toastr[result.status](result.message);
					}
				});
			});
		}

		$(document).on("click", ".ticket-reply-toggle", function() {
			var target = $(this).data("target");
			$(".ticket-inline-reply").not(target).slideUp(120);
			$(target).slideToggle(160);
		});

		$(document).on("click", ".ticket-inline-reply-submit", function() {
			$(this).html(waitLabel + "...").addClass("disabled");
		});

		$("#tickets-comment-form").appForm({
			isModal: false,
			onSuccess: function(result) {
				$(".reply-body").val("");
				$('#file-save-button').removeClass("disabled").html('<i data-lucide="send" class="h-4 w-4"></i><span>' + replyLabel + '</span>');
				var $reply = $(result.data).hide();
				$("#ticket-replies-list").prepend($reply);
				$reply.slideDown(180);
				$("#ticket-replies-count").text(parseInt($("#ticket-replies-count").text(), 10) + 1);
				initTicketReplyForms($reply);
				refreshTicketIcons();
				toastr[result.status](result.message);
			}
		});

		initTicketReplyForms(document);
		refreshTicketIcons();
	});
</script>

<script>
	const btn = document.getElementById('statusDropdownBtn');
	const menu = document.getElementById('statusDropdownMenu');

	if (btn && menu) {
		btn.addEventListener('click', () => {
			menu.classList.toggle('hidden');
		});

		document.addEventListener('click', (e) => {
			if (!btn.contains(e.target) && !menu.contains(e.target)) {
				menu.classList.add('hidden');
			}
		});
	}
</script>
