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

<?php
$module = isset($module) ? $module : '';
$module_id = isset($module_id) ? $module_id : (isset($id) ? $id : null);
$table = isset($table) ? $table : null;
$table_field = isset($table_field) ? $table_field : null;
$table_row_field = isset($table_row_field) ? $table_row_field : null;

$module_defaults = array(
	'client' => array(
		'perm' => '4',
		'notes_table' => 'tbl_notes',
		'notes_field' => 'user_id',
		'notes_where' => array('is_client' => 'Yes'),
		'author_field' => 'added_by',
		'time_field' => 'last_update',
		'parent_table' => 'tbl_client',
		'parent_field' => 'client_id',
		'save' => 'admin/client/new_notes',
		'delete' => 'admin/client/delete_notes',
	),
	'default' => array(
		'notes_table' => 'tbl_leads_notes',
		'notes_field' => 'module_field_id',
		'notes_where' => array(),
		'author_field' => 'user_id',
		'time_field' => 'created_time',
		'parent_table' => $table,
		'parent_field' => $table_row_field,
		'save' => 'admin/common/save_all_notes/' . $module_id,
		'delete' => 'admin/common/delete_notes',
	),
);

$module_config = isset($module_defaults[$module]) ? $module_defaults[$module] : $module_defaults['default'];

$notes_table = !empty($table) && $this->db->field_exists('notes_id', $table) ? $table : $module_config['notes_table'];
$notes_field = !empty($table_field) && $this->db->field_exists($table_field, $notes_table)
	? $table_field
	: $module_config['notes_field'];
$notes_where = isset($module_config['notes_where']) ? $module_config['notes_where'] : array();
$author_field = isset($module_config['author_field']) ? $module_config['author_field'] : 'user_id';
$time_field = isset($module_config['time_field']) ? $module_config['time_field'] : 'created_time';
$parent_table = !empty($table) ? $table : $module_config['parent_table'];

if (empty($table_row_field) || (empty($parent_table) || !$this->db->field_exists($table_row_field, $parent_table))) {
	$table_field_candidates = array('leads_id', 'task_id', 'project_id', 'bug_id', 'opportunities_id', 'client_id', 'user_id', 'module_field_id');
	$table_row_field = isset($module_config['parent_field']) ? $module_config['parent_field'] : null;
	if (empty($table_row_field) || (empty($parent_table) || !$this->db->field_exists($table_row_field, $parent_table))) {
		$table_row_field = null;
		if (!empty($parent_table)) {
			foreach ($table_field_candidates as $candidate) {
				if ($this->db->field_exists($candidate, $parent_table)) {
					$table_row_field = $candidate;
					break;
				}
			}
		}
	}
}

$config_map = array(
	$module => array(
		'perm' => !empty($perm) ? $perm : $module_config['perm'],
		'table' => $notes_table,
		'field' => $notes_field,
		'where' => $notes_where,
		'author_field' => $author_field,
		'time_field' => $time_field,
		'save' => $module_config['save'],
		'delete' => $module_config['delete'],
	),
);

if (empty($module) || empty($module_id) || !isset($config_map[$module])) {
	echo '<div class="text-sm text-muted-foreground">' . lang('there_in_no_value') . '</div>';
	return;
}

$config = $config_map[$module];
$edited = can_action($config['perm'], 'edited');
$deleted = can_action($config['perm'], 'deleted');

$notes_where = array_merge($config['where'], array($config['field'] => $module_id));
$notes = get_result($config['table'], $notes_where);

$user_map = array();
if (!empty($notes)) {
	$user_ids = array();
	foreach ($notes as $note) {
		$author_id = isset($note->{$config['author_field']}) ? $note->{$config['author_field']} : null;
		if (!empty($author_id)) {
			$user_ids[] = $author_id;
		}
	}
	$user_ids = array_values(array_unique($user_ids));
	if (!empty($user_ids)) {
		$user_rows = $this->db
			->select('tbl_users.user_id, tbl_users.username, tbl_account_details.fullname, tbl_account_details.avatar')
			->from('tbl_users')
			->join('tbl_account_details', 'tbl_account_details.user_id = tbl_users.user_id', 'left')
			->where_in('tbl_users.user_id', $user_ids)
			->get()->result();
		foreach ($user_rows as $user) {
			$user_map[$user->user_id] = array(
				'name' => !empty($user->fullname) ? $user->fullname : $user->username,
				'avatar' => !empty($user->avatar) ? $user->avatar : 'uploads/default_avatar.jpg',
			);
		}
	}
}

if (!empty($last_contact) && !empty($parent_table) && !empty($table_row_field) && $this->db->field_exists('last_contact', $parent_table)) {
	$lead_info = $this->db->select('last_contact')->where($table_row_field, $module_id)->get($parent_table)->row();
	$last_contact_value = !empty($lead_info->last_contact) ? $lead_info->last_contact : date('Y-m-d H:i');
}

$form_action = base_url($config['save']);
?>

<div class="space-y-6">
	<div class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm dark:border-slate-700 dark:bg-slate-800">
		<div class="flex items-center justify-between border-b border-slate-200 pb-3 dark:border-slate-700">
			<h3 class="text-sm font-semibold text-slate-900 dark:text-slate-100"><?= lang('notes') ?></h3>
			<span class="text-xs text-muted-foreground"><?= !empty($notes) ? count($notes) : 0; ?> <?= lang('records') ?></span>
		</div>

		<?php if (!empty($edited)) { ?>
			<form action="<?= $form_action; ?>" method="post" class="mt-4 space-y-4">
				<?= form_editor('notes', lang('notes'), '', false, array('data-height' => '150px')); ?>
				<input type="hidden" name="redirect" value="<?= $redirect; ?>">
				<input type="hidden" name="module" value="<?= $module; ?>">
				<?php if ($module === 'client') { ?>
					<input type="hidden" name="client_id" value="<?= $module_id; ?>">
				<?php } ?>
				<?php
				if (!empty($last_contact_value)) {
				?>
					<div class="grid grid-cols-1 gap-3 rounded-xl border border-slate-200 bg-slate-50 p-3 md:grid-cols-2 dark:border-slate-700 dark:bg-slate-900/40">
						<?= form_radio('contacted_indicator', lang('i_got_touch_with_leads'), 'touch_with_leads', false, false, array('data-contacted' => 'show', 'class' => 'mt-0.5')); ?>
						<?= form_radio('contacted_indicator', lang('i_have_not_contacted'), 'not_contacted', true, false, array('data-contacted' => 'hide', 'class' => 'mt-0.5')); ?>
					</div>
					<div id="notes_contacted_date" class="hidden">
						<?= form_datepicker('last_contact', lang('date_contacted'), $last_contact_value, false, array('data-type' => 'datetime', 'data-format' => 'Y-m-d H:i')); ?>
					</div>
				<?php } ?>
				<div class="flex justify-end">
					<button type="submit" class="rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white hover:bg-slate-800 dark:bg-slate-700 dark:hover:bg-slate-600">
						<?= lang('updates'); ?>
					</button>
				</div>
			</form>
		<?php } ?>

		<div class="mt-6 space-y-3">
			<?php if (!empty($notes)) { ?>
				<?php foreach ($notes as $note) { ?>
					<div class="flex gap-3 rounded-xl border border-slate-200 bg-slate-50/60 p-4 dark:border-slate-700 dark:bg-slate-900/40" id="note-row-<?= $note->notes_id; ?>">
						<?php
						$author_id = isset($note->{$config['author_field']}) ? $note->{$config['author_field']} : null;
						$avatar = !empty($author_id) && isset($user_map[$author_id]) ? $user_map[$author_id]['avatar'] : 'uploads/default_avatar.jpg';
						$name = !empty($author_id) && isset($user_map[$author_id]) ? $user_map[$author_id]['name'] : lang('unknown');
						$note_time = isset($note->{$config['time_field']}) ? $note->{$config['time_field']} : null;
						?>
						<img alt="Avatar" src="<?= base_url($avatar); ?>" class="h-10 w-10 rounded-full border border-slate-200 object-cover dark:border-slate-700">
						<div class="flex-1">
							<div class="flex items-start justify-between gap-3">
								<div>
									<a href="<?= !empty($author_id) ? base_url('admin/user/user_details/' . $author_id) : '#'; ?>" class="text-sm font-semibold text-slate-900 hover:underline dark:text-slate-100">
										<?= html_escape($name); ?>
									</a>
									<div class="text-xs text-slate-500 dark:text-slate-400"><?= !empty($note_time) ? time_ago($note_time) : '-'; ?></div>
								</div>
								<div class="flex items-center gap-2">
									<?php if (!empty($note->last_contact)) { ?>
										<span class="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-1 text-xs text-emerald-600 dark:bg-emerald-900/40 dark:text-emerald-300" data-tooltip="<?= $note->last_contact; ?>">
											<i data-lucide="phone-call" class="h-3.5 w-3.5"></i>
											<?= lang('contacted_today'); ?>
										</span>
									<?php } ?>
									<?php if (!empty($deleted)) { ?>
										<?php
										$delete_url = $module === 'client'
											? $config['delete'] . '/' . $note->notes_id . '/' . $module_id
											: $config['delete'] . '/' . $note->notes_id . '/' . $module_id . '/' . $redirect;
										?>
										<?= ajax_anchor(base_url($delete_url), "", array("class" => "inline-flex items-center justify-center rounded-lg border border-rose-200 bg-rose-50 p-2 text-rose-600 hover:bg-rose-100 dark:border-rose-800 dark:bg-rose-900/30 dark:text-rose-300 dark:hover:bg-rose-900/50", "title" => lang('delete'), "data-fade-out-on-success" => "#note-row-" . $note->notes_id)); ?>
									<?php } ?>
								</div>
							</div>
							<div class="mt-2 text-sm text-slate-700 dark:text-slate-200">
								<?php if (!empty($note->notes)) echo $note->notes; ?>
							</div>
						</div>
					</div>
				<?php } ?>
			<?php } else { ?>
				<div class="rounded-xl border border-dashed border-slate-300 p-6 text-center text-sm text-slate-500 dark:border-slate-600 dark:text-slate-400"><?= lang('nothing_to_display') ?></div>
			<?php } ?>
		</div>
	</div>
</div>

<script>
	(function() {
		const wrap = document.currentScript && document.currentScript.parentElement;
		if (!wrap) return;
		const radios = wrap.querySelectorAll('input[name="contacted_indicator"]');
		const dateWrap = wrap.querySelector('#notes_contacted_date');
		if (!radios.length || !dateWrap) return;

		function sync() {
			let show = false;
			radios.forEach((radio) => {
				if (radio.checked && radio.value === 'touch_with_leads') {
					show = true;
				}
			});
			dateWrap.classList.toggle('hidden', !show);
		}

		radios.forEach((radio) => radio.addEventListener('change', sync));
		sync();
	})();
</script>
