<?php
$attach_list = $this->session->userdata($module . '_media_view');
if (empty($attach_list)) {
	$attach_list = 'list_view';
}

$file_exists = function ($file) {
	if (!empty($file->uploaded_path) && is_file($file->uploaded_path)) {
		return true;
	}
	if (!empty($file->files)) {
		$relative = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, ltrim($file->files, '/\\'));
		$full = getcwd() . DIRECTORY_SEPARATOR . $relative;
		if (is_file($full)) {
			return true;
		}
	}
	if (!empty($file->file_name)) {
		$fallback = getcwd() . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $file->file_name;
		if (is_file($fallback)) {
			return true;
		}
	}
	return false;
};

$attachment_sets = $this->db->where(array('module' => $module, 'module_field_id' => $id))
	->order_by('attachments_id', 'DESC')
	->get('tbl_attachments')
	->result();

$grouped_files = array();
$attachment_groups_count = !empty($attachment_sets) ? count($attachment_sets) : 0;
$attachment_files_count = 0;
$has_any_file = false;

if (!empty($attachment_sets)) {
	$attachment_ids = array();
	foreach ($attachment_sets as $set) {
		if (!empty($set->attachments_id)) {
			$attachment_ids[] = $set->attachments_id;
			$grouped_files[$set->attachments_id] = array();
		}
	}

	if (!empty($attachment_ids)) {
		$attachment_files = $this->db->where_in('attachments_id', $attachment_ids)
			->order_by('uploaded_files_id', 'DESC')
			->get('tbl_attachments_files')
			->result();

		if (!empty($attachment_files)) {
			foreach ($attachment_files as $file_row) {
				$set = null;
				foreach ($attachment_sets as $attachment_set) {
					if (!empty($attachment_set->attachments_id) && (string) $attachment_set->attachments_id === (string) $file_row->attachments_id) {
						$set = $attachment_set;
						break;
					}
				}

				if (!empty($set)) {
					if (empty($file_row->title) && !empty($set->title)) {
						$file_row->title = $set->title;
					}
					if (empty($file_row->user_id) && !empty($set->user_id)) {
						$file_row->user_id = $set->user_id;
					}
					if (empty($file_row->fullname) && !empty($set->fullname)) {
						$file_row->fullname = $set->fullname;
					}
					if (empty($file_row->upload_time) && !empty($set->upload_time)) {
						$file_row->upload_time = $set->upload_time;
					}
				}

				$attachment_files_count++;
				$grouped_files[$file_row->attachments_id][] = $file_row;
				if (!$has_any_file && $file_exists($file_row)) {
					$has_any_file = true;
				}
			}
		}
	}
}

$files_info = $grouped_files;
?>

<div class="project-overview-shell min-w-0 space-y-4">
	<div class="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
		<div class="project-kpi-card rounded-xl border border-border bg-card p-4 shadow-sm">
			<div class="flex items-center gap-3">
				<div class="rounded-xl bg-blue-50 p-2.5 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400">
					<i data-lucide="folder" class="h-5 w-5"></i>
				</div>
				<div>
					<div class="text-2xl font-bold text-foreground"><?= (int) $attachment_groups_count ?></div>
					<div class="text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground">Attachment Sets</div>
				</div>
			</div>
		</div>
		<div class="project-kpi-card rounded-xl border border-border bg-card p-4 shadow-sm">
			<div class="flex items-center gap-3">
				<div class="rounded-xl bg-violet-50 p-2.5 text-violet-600 dark:bg-violet-900/30 dark:text-violet-400">
					<i data-lucide="file" class="h-5 w-5"></i>
				</div>
				<div>
					<div class="text-2xl font-bold text-foreground"><?= (int) $attachment_files_count ?></div>
					<div class="text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground"><?= lang('files') ?></div>
				</div>
			</div>
		</div>
		<div class="project-kpi-card rounded-xl border border-border bg-card p-4 shadow-sm">
			<div class="flex items-center gap-3">
				<div class="rounded-xl bg-emerald-50 p-2.5 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400">
					<i data-lucide="layout-grid" class="h-5 w-5"></i>
				</div>
				<div>
					<div class="text-2xl font-bold text-foreground"><?= $attach_list == 'media_view' ? 'Grid' : 'List' ?></div>
					<div class="text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground">View Mode</div>
				</div>
			</div>
		</div>
		<div class="project-kpi-card rounded-xl border border-border bg-card p-4 shadow-sm">
			<div class="flex items-center gap-3">
				<div class="rounded-xl bg-amber-50 p-2.5 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400">
					<i data-lucide="download" class="h-5 w-5"></i>
				</div>
				<div>
					<div class="text-2xl font-bold text-foreground"><?= $has_any_file ? 'Ready' : 'Empty' ?></div>
					<div class="text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground">Export State</div>
				</div>
			</div>
		</div>
	</div>

	<div class="project-section-card rounded-2xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-800">
		<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
			<div>
				<h3 class="text-base font-semibold text-slate-900 dark:text-slate-100"><?= lang('attach_file_list') ?></h3>
				<p class="text-sm text-slate-500 dark:text-slate-400"><?= lang('attachment') ?> manager and project asset library</p>
			</div>
			<div class="flex flex-wrap items-center gap-2 sm:justify-end">
				<?php if ($has_any_file) { ?>
					<a data-tooltip="<?= lang('download') . ' ' . lang('all') . ' ' . lang('attachment') ?>"
						href="<?= base_url('admin/common/download_all_attachment/' . $module . '/' . $id) ?>"
						class="project-action-btn inline-flex items-center gap-2 px-3 py-2 text-xs font-semibold text-slate-700 transition-colors hover:bg-slate-50 hover:text-slate-900 dark:text-slate-200 dark:hover:bg-slate-700 dark:hover:text-white">
						<i data-lucide="download" class="h-4 w-4"></i>
						<?= lang('download') ?>
					</a>
				<?php } ?>

				<button type="button" data-attachment-view="media_view"
					class="project-action-btn inline-flex items-center gap-2 px-3 py-2 text-xs font-semibold text-slate-700 transition-colors hover:bg-slate-50 hover:text-slate-900 dark:text-slate-200 dark:hover:bg-slate-700 dark:hover:text-white <?= $attach_list == 'media_view' ? 'hidden' : '' ?>">
					<i data-lucide="grid" class="h-4 w-4"></i>
					<?= lang('media_view') ?>
				</button>

				<button type="button" data-attachment-view="list_view"
					class="project-action-btn inline-flex items-center gap-2 px-3 py-2 text-xs font-semibold text-slate-700 transition-colors hover:bg-slate-50 hover:text-slate-900 dark:text-slate-200 dark:hover:bg-slate-700 dark:hover:text-white <?= $attach_list == 'list_view' ? 'hidden' : '' ?>">
					<i data-lucide="list" class="h-4 w-4"></i>
					<?= lang('list_view') ?>
				</button>

				<?= btn_modal(
					'admin/common/new_attachment/' . $module . '/' . $id,
					lang('new') . ' ' . lang('attachment'),
					lang('new') . ' ' . lang('attachment'),
					'lg',
					'plus',
					array('class' => 'inline-flex items-center gap-2 rounded-2xl bg-slate-900 px-3.5 py-2 text-xs font-semibold text-white shadow-sm transition-colors hover:bg-slate-800 dark:bg-slate-100 dark:text-slate-900 dark:hover:bg-white')
				) ?>
			</div>
		</div>
	</div>

	<?php $this->load->helper('file'); ?>
	<div class="media-view-container <?= $attach_list == 'media_view' ? '' : 'hidden' ?>">
		<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
			<?php $this->load->view('admin/common/attachment_list', array('module' => $module, 'files_info' => $files_info)); ?>
		</div>
	</div>

	<div class="media-list-container space-y-4 <?= $attach_list == 'list_view' ? '' : 'hidden' ?>">
		<?php if (!empty($attachment_sets)) { ?>
			<?php foreach ($attachment_sets as $set) {
				$set_files = !empty($grouped_files[$set->attachments_id]) ? $grouped_files[$set->attachments_id] : array();
				$group_has_file = false;
				foreach ($set_files as $entry) {
					if ($file_exists($entry)) {
						$group_has_file = true;
						break;
					}
				}
				$uploaded_by = $this->db->where('user_id', $set->user_id)->get('tbl_account_details')->row();
			?>
				<div class="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-800/90" id="media_list_container-<?= $set->attachments_id ?>">
					<div class="h-px bg-slate-200 dark:bg-slate-700"></div>
					<div class="flex flex-col gap-2 border-b border-slate-200 px-4 py-3 sm:flex-row sm:items-center sm:justify-between dark:border-slate-700">
						<div>
							<div class="text-sm font-semibold text-slate-900 dark:text-slate-100"><?= html_escape($set->title) ?></div>
							<div class="text-xs text-slate-500 dark:text-slate-400">
								<?= !empty($uploaded_by->fullname) ? html_escape($uploaded_by->fullname) : '-' ?>
								&bull; <?= count($set_files) . ' ' . lang('attachment') ?>
							</div>
						</div>
						<div class="flex flex-wrap items-center gap-2">
							<?php if ($group_has_file) { ?>
								<a class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50 dark:border-slate-700 mb-1 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-700"
									href="<?= base_url() ?>admin/common/download_all_files/<?= $set->attachments_id ?>">
									<i data-lucide="download" class="h-4 w-4"></i>
									<?= lang('download') ?>
								</a>
							<?php } ?>
							<?php if ($set->user_id == $this->session->userdata('user_id')) { ?>
								<?php echo ajax_anchor(base_url("admin/common/delete_task_files/" . $set->attachments_id), "", array("class" => "inline-flex items-center rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-1.5 text-xs font-semibold text-rose-600 hover:bg-rose-100 dark:border-rose-900/60 dark:bg-rose-950/30 dark:text-rose-300 dark:hover:bg-rose-900/40", "title" => lang('delete'), "data-fade-out-on-success" => "#media_list_container-" . $set->attachments_id)); ?>
							<?php } ?>
						</div>
					</div>
					<?php if (!empty($set_files)) { ?>
						<div class="overflow-x-auto">
							<table class="min-w-full text-sm">
								<thead class="bg-slate-50 text-slate-500 dark:bg-slate-900/60 dark:text-slate-400">
									<tr>
										<th class="px-4 py-3 text-left"><?= lang('files') ?></th>
										<th class="px-4 py-3 text-left"><?= lang('size') ?></th>
										<th class="px-4 py-3 text-left"><?= lang('date') ?></th>
										<th class="px-4 py-3 text-left"><?= lang('total') . ' ' . lang('comments') ?></th>
										<th class="px-4 py-3 text-left"><?= lang('uploaded_by') ?></th>
										<th class="px-4 py-3 text-left"><?= lang('action') ?></th>
									</tr>
								</thead>
								<tbody class="divide-y divide-slate-100 dark:divide-slate-700">
									<?php foreach ($set_files as $file_row) {
										$total_file_comment = total_rows('tbl_task_comment', array('uploaded_files_id' => $file_row->uploaded_files_id));
										$single_file_exists = $file_exists($file_row);
										$file_uploaded_time = !empty($file_row->upload_time) ? $file_row->upload_time : (!empty($set->upload_time) ? $set->upload_time : null);
									?>
										<tr class="file-item text-slate-700 dark:text-slate-200">
											<td class="px-4 py-3">
												<?= btn_modal(
													'admin/common/attachment_details/r/' . $file_row->attachments_id . '/' . $file_row->uploaded_files_id,
													html_escape($file_row->file_name),
													html_escape($file_row->file_name),
													'2xl',
													'',
													array(
														'class' => 'font-medium text-primary hover:underline',
													)
												) ?>
											</td>
											<td class="px-4 py-3"><?= $file_row->size ?>Kb</td>
											<td class="px-4 py-3">
												<?= !empty($file_uploaded_time) ? date('Y-m-d' . "<br/> h:m A", safe_strtotime($file_uploaded_time)) : '-' ?>
											</td>
											<td class="px-4 py-3"><?= $total_file_comment ?></td>
											<td class="px-4 py-3"><?= !empty($file_row->fullname) ? html_escape($file_row->fullname) : '-' ?></td>
											<td class="px-4 py-3">
												<?php if ($single_file_exists) { ?>
													<a class="inline-flex items-center gap-1 rounded-lg border border-slate-200 bg-white px-2 py-1 text-xs font-semibold text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-700"
														href="<?= base_url() ?>admin/common/download_files/<?= $file_row->uploaded_files_id ?>">
														<i data-lucide="download" class="h-4 w-4"></i>
														<?= lang('download') ?>
													</a>
												<?php } ?>
											</td>
										</tr>
									<?php } ?>
								</tbody>
							</table>
						</div>
					<?php } else { ?>
						<div class="px-4 py-8 text-center text-sm text-slate-500 dark:text-slate-400"><?= lang('nothing_to_display') ?></div>
					<?php } ?>
				</div>
			<?php } ?>
		<?php } else { ?>
			<div class="rounded-xl border border-dashed border-slate-300 bg-slate-50 px-4 py-10 text-center text-sm text-slate-500 dark:border-slate-700 dark:bg-slate-900/40 dark:text-slate-400"><?= lang('nothing_to_display') ?></div>
		<?php } ?>
	</div>
</div>

<script type="text/javascript">
	(function() {
		const toggleButtons = document.querySelectorAll('[data-attachment-view]');
		const mediaView = document.querySelector('.media-view-container');
		const listView = document.querySelector('.media-list-container');
		toggleButtons.forEach((btn) => {
			btn.addEventListener('click', () => {
				const type = btn.getAttribute('data-attachment-view');
				if (type === 'media_view') {
					mediaView.classList.remove('hidden');
					listView.classList.add('hidden');
				} else {
					listView.classList.remove('hidden');
					mediaView.classList.add('hidden');
				}
				toggleButtons.forEach((b) => b.classList.toggle('hidden'));
				fetch('<?= base_url() ?>admin/common/set_media_view/' + type + '/<?= $module ?>');
			});
		});
	})();
</script>
