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

<?php
$reporter_info = $this->db->where(array('user_id' => $tickets_info->reporter))->get('tbl_account_details')->row();
$department_info = $this->db->where(array('departments_id' => $tickets_info->departments_id))->get('tbl_departments')->row();
$project_info = $tickets_info->project_id != '0'
	? $this->db->where('project_id', $tickets_info->project_id)->get('tbl_project')->row()
	: 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';
}

$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' => '<span class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold ' . $status_tone . '">' . $status_label . '</span>'),
	array('label' => lang('created'), 'value' => display_date($tickets_info->created)),
);

$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">
					<span class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold <?= $status_tone; ?>"><?= $status_label; ?></span>
					<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('client/projects/project_details/' . $project_info->project_id); ?>">
							<?= html_escape($project_info->project_name); ?>
						</a>
					<?php } ?>
				</div>
			</div>
			<button class="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-border text-foreground hover:bg-muted" id="tab_collapse" type="button">
				<i data-lucide="chevron-left"></i>
			</button>
		</div>
	</div>

	<div class="grid gap-6 lg:grid-cols-12">
		<aside id="list_tab" class="hidden lg:col-span-4">
			<div class="rounded-2xl border border-border bg-card shadow-sm">
				<div class="border-b border-border px-4 py-3">
					<h3 class="text-sm font-semibold text-foreground"><?= lang('all_tickets') ?></h3>
				</div>
				<div class="slim-scroll max-h-[70vh] overflow-y-auto" data-height="auto" data-disable-fade-out="true" data-distance="0" data-size="5px" data-color="#333333">
					<?php
					if (!empty($all_tickets_info)) :
						foreach ($all_tickets_info as $v_tickets_info) :
							if ($v_tickets_info->status == 'open') {
								$status_badge = 'bg-rose-50 text-rose-700';
							} elseif ($v_tickets_info->status == 'closed') {
								$status_badge = 'bg-emerald-50 text-emerald-700';
							} else {
								$status_badge = 'bg-slate-100 text-slate-700';
							}
							$is_active = $v_tickets_info->tickets_id == $this->uri->segment(5);
							$status = $v_tickets_info->status == 'in_progress' ? 'In Progress' : $v_tickets_info->status;
							$user_info = $this->db->where(array('user_id' => $v_tickets_info->reporter))->get('tbl_users')->row();
							?>
							<a
								href="<?= base_url() ?>client/tickets/index/tickets_details/<?= $v_tickets_info->tickets_id ?>"
								class="block border-b border-border px-4 py-3 text-sm transition hover:bg-muted/40 <?= $is_active ? 'bg-muted/60' : ''; ?>">
								<div class="flex items-center justify-between gap-2">
									<span class="font-semibold text-foreground"><?= $v_tickets_info->ticket_code ?></span>
									<span class="inline-flex rounded-full px-2 py-0.5 text-[11px] font-semibold uppercase tracking-wide <?= $status_badge ?>">
										<?= ucfirst($status) ?>
									</span>
								</div>
								<p class="mt-1 text-xs text-muted-foreground">
									<?= ucfirst($user_info->username) ?> | <?= display_date($v_tickets_info->created); ?>
								</p>
							</a>
						<?php endforeach; ?>
					<?php endif; ?>
				</div>
			</div>
		</aside>

		<section id="tab" class="lg:col-span-8">
			<div class="space-y-6">
				<div class="grid gap-6 lg:grid-cols-12">
					<div id="meta_panel" class="lg:col-span-4 space-y-4">
						<?php $this->load->view('admin/common/details_grid', array(
							'title' => lang('ticket_details'),
							'fields' => $fields,
						)); ?>
					</div>

					<div class="lg:col-span-8 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 = [];
							if (!empty($tickets_info->upload_file) && is_string($tickets_info->upload_file)) {
								$uploaded_file = json_decode($tickets_info->upload_file);
								if (!is_array($uploaded_file) && !is_object($uploaded_file)) {
									$uploaded_file = [];
								}
							}
							if (!empty($uploaded_file)):
								?>
								<div class="mt-5">
									<p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('attachments') ?></p>
									<div class="mt-3 grid gap-3 sm:grid-cols-2">
										<?php foreach ($uploaded_file as $fkey => $v_files):
											if (!empty($v_files)) { ?>
												<a href="<?= base_url() ?>client/tickets/index/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 class="<?= $v_files->is_image == 1 ? 'fa-file-image-o' : ' ' ?>" data-lucide="file-text"></i>
														</span>

														<span class="truncate font-medium text-foreground dark:text-gray-200">
															<?= $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>

						<?php if ($tickets_info->status != 'closed') { ?>
							<div class="rounded-2xl border border-border bg-card p-5 shadow-sm">
								<h3 class="text-sm font-semibold text-foreground mb-3"><?= lang('reply_ticket'); ?></h3>
								<?php echo form_open(base_url("client/tickets/save_reply/" . $tickets_info->tickets_id), array(
									"id" => "tickets-comment-form",
									"class" => "space-y-4",
									"enctype" => "multipart/form-data",
									"role" => "form",
									"data-ticket-reply-form" => "true"
								)); ?>
								<div class="hidden rounded-lg border px-3 py-2 text-sm" data-ticket-reply-alert></div>
								<textarea
									name="body"
									rows="5"
									class="reply-body w-full rounded-lg border border-border bg-input px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-secondary/30"
									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">
									<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-primary">
										<i data-lucide="send"></i>
										<span><?= lang('reply'); ?></span>
									</button>
								</div>
								<?php echo form_close(); ?>
							</div>
						<?php } ?>

						<div class="space-y-4">
							<h4 class="text-sm font-semibold text-foreground"><?= lang('replies') ?></h4>
							<div class="space-y-4" data-ticket-replies-list>
							<?php
							$ticket_replies = $this->db->where(array('tickets_id' => $tickets_info->tickets_id))->get('tbl_tickets_replies')->result();
							if (!empty($ticket_replies)) :
								foreach ($ticket_replies as $v_replies) :
									$this->load->view('client/tickets/_reply_item', array('v_replies' => $v_replies));
								endforeach; ?>
							<?php else: ?>
								<p class="text-sm text-muted-foreground" data-ticket-replies-empty><?= lang('no_data_found'); ?></p>
							<?php endif; ?>
							</div>
						</div>
					</div>
				</div>
			</div>
		</section>
	</div>
</div>

<script type="text/javascript">
	$(document).ready(function () {
		var $listTab = $('#list_tab');
		var $tab = $('#tab');

		function syncLayout() {
			if ($listTab.hasClass('hidden')) {
				$tab.addClass('lg:col-span-12').removeClass('lg:col-span-8');
			} else {
				$tab.addClass('lg:col-span-8').removeClass('lg:col-span-12');
			}
		}

		syncLayout();
		$('#tab_collapse').on("click", function () {
			$listTab.toggleClass('hidden');
			syncLayout();
		});

		var $replyForm = $('[data-ticket-reply-form]');
		var $replyList = $('[data-ticket-replies-list]');
		var $emptyState = $('[data-ticket-replies-empty]');
		var $alert = $('[data-ticket-reply-alert]');

		function showReplyMessage(type, message) {
			if (!$alert.length) {
				return;
			}
			var success = type === 'success';
			$alert
				.removeClass('hidden border-emerald-200 bg-emerald-50 text-emerald-700 border-rose-200 bg-rose-50 text-rose-700')
				.addClass(success ? 'border-emerald-200 bg-emerald-50 text-emerald-700' : 'border-rose-200 bg-rose-50 text-rose-700')
				.text(message);
		}

		$replyForm.on('submit', function (event) {
			event.preventDefault();

			var form = this;
			var $form = $(form);
			var $submit = $form.find('[type="submit"]');
			var originalHtml = $submit.html();
			var hasAttachment = $form.find('input[type="hidden"][name="files[]"]').length > 0;
			var body = $.trim($form.find('[name="body"]').val());

			if (!body && !hasAttachment) {
				showReplyMessage('error', 'Please write a reply or attach a file.');
				return;
			}

			$submit.prop('disabled', true).addClass('opacity-70 cursor-not-allowed');
			$submit.html('<span>Saving...</span>');

			$.ajax({
				url: $form.attr('action'),
				type: 'POST',
				data: new FormData(form),
				processData: false,
				contentType: false,
				dataType: 'json',
				headers: {
					'X-Requested-With': 'XMLHttpRequest'
				},
				success: function (response) {
					if (response && response.status === 'success') {
						if (response.data) {
							$replyList.append(response.data);
							$emptyState.remove();
						}
						form.reset();
						$('#ticket-reply-list').empty();
						showReplyMessage('success', response.message || 'Reply saved.');
						if (window.lucide && typeof window.lucide.createIcons === 'function') {
							window.lucide.createIcons();
						}
					} else {
						showReplyMessage('error', (response && response.message) ? response.message : 'Could not save reply.');
					}
				},
				error: function () {
					showReplyMessage('error', 'Could not save reply. Please try again.');
				},
				complete: function () {
					$submit.prop('disabled', false).removeClass('opacity-70 cursor-not-allowed').html(originalHtml);
				}
			});
		});
	});
</script>


