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

<?php
$module = isset($module) ? $module : '';
$module_id = isset($module_id) ? $module_id : null;
$meeting_id = isset($meeting_id) ? $meeting_id : null;

$config_map = array(
	'leads' => array(
		'save' => 'admin/leads/saved_metting',
	),
	'opportunities' => array(
		'save' => 'admin/opportunities/saved_metting',
	),
	'deals' => array(
		'save' => 'admin/deals/saved_metting',
	),
);

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;
}

$meeting_info = null;
if (!empty($meeting_id)) {
	$meeting_info = get_row('tbl_mettings', array('mettings_id' => $meeting_id));
}

$user_options = array();
$user_map = array();
$user_rows = $this->db
	->select('tbl_users.user_id, tbl_users.username, tbl_account_details.fullname')
	->from('tbl_users')
	->join('tbl_account_details', 'tbl_account_details.user_id = tbl_users.user_id', 'left')
	->where('tbl_users.role_id !=', '2')
	->get()->result();
if (!empty($user_rows)) {
	foreach ($user_rows as $user) {
		$label = !empty($user->fullname) ? $user->fullname : $user->username;
		$user_options[$user->user_id] = $label;
		$user_map[$user->user_id] = $label;
	}
}

$attendees_selected = array();
if (!empty($meeting_info->attendees) && $meeting_info->attendees !== '-') {
	$decoded = @unserialize($meeting_info->attendees);
	if (is_array($decoded) && !empty($decoded['attendees'])) {
		$attendees_selected = $decoded['attendees'];
	}
}
$attendees_selected_items = array();
if (!empty($attendees_selected)) {
	foreach ($attendees_selected as $attendee_id) {
		if (isset($user_map[$attendee_id])) {
			$attendees_selected_items[] = array(
				'id' => $attendee_id,
				'text' => $user_map[$attendee_id],
			);
		}
	}
}

$selected_user_id = !empty($meeting_info->user_id) ? $meeting_info->user_id : '';
$selected_user_label = !empty($selected_user_id) && isset($user_map[$selected_user_id]) ? $user_map[$selected_user_id] : '';

$start_timestamp = !empty($meeting_info->start_date) ? (int)$meeting_info->start_date : null;
$end_timestamp = !empty($meeting_info->end_date) ? (int)$meeting_info->end_date : null;
$start_date = !empty($start_timestamp) ? date('Y-m-d', $start_timestamp) : date('Y-m-d');
$end_date = !empty($end_timestamp) ? date('Y-m-d', $end_timestamp) : date('Y-m-d');
$start_time = !empty($start_timestamp) ? display_time($start_timestamp, true) : '';
$end_time = !empty($end_timestamp) ? display_time($end_timestamp, true) : '';
$start_datetime = !empty($start_timestamp) ? date('Y-m-d H:i', $start_timestamp) : date('Y-m-d H:i');
$end_datetime = !empty($end_timestamp) ? date('Y-m-d H:i', $end_timestamp) : date('Y-m-d H:i', strtotime('+1 hour'));

$form_action = base_url($config_map[$module]['save'] . '/' . $module_id . '/' . (!empty($meeting_info->mettings_id) ? $meeting_info->mettings_id : ''));
$form_label = !empty($meeting_info) ? lang('updates') : lang('save');
?>

<?php echo form_open($form_action, array('class' => 'modal-form', 'data-parsley-validate' => '', 'data-meeting-datetime-form' => '1')); ?>
<div class="grid gap-4">
	<div class="grid gap-4 md:grid-cols-2">
		<?= form_input_group('meeting_subject', lang('metting_subject'), (!empty($meeting_info->meeting_subject) ? $meeting_info->meeting_subject : ''), 'text', true); ?>
		<?= form_input_group('location', lang('location'), (!empty($meeting_info->location) ? $meeting_info->location : ''), 'text', true); ?>
		<?= form_datepicker('start_datetime', lang('start_date') . ' & ' . lang('start_time'), $start_datetime, true, array(
			'id' => 'meeting-start-datetime',
			'data-type' => 'datetime',
			'data-format' => 'Y-m-d H:i',
			'data-max' => '#meeting-end-datetime',
			'data-auto-close' => 'true',
			'data-today-btn' => 'false',
		)); ?>
		<?= form_datepicker('end_datetime', lang('end_date') . ' & ' . lang('end_time'), $end_datetime, true, array(
			'id' => 'meeting-end-datetime',
			'data-type' => 'datetime',
			'data-format' => 'Y-m-d H:i',
			'data-min' => '#meeting-start-datetime',
			'data-auto-close' => 'true',
			'data-today-btn' => 'false',
		)); ?>
		<input type="hidden" name="start_date" value="<?= html_escape($start_date) ?>" data-meeting-start-date>
		<input type="hidden" name="start_time" value="<?= html_escape($start_time) ?>" data-meeting-start-time>
		<input type="hidden" name="end_date" value="<?= html_escape($end_date) ?>" data-meeting-end-date>
		<input type="hidden" name="end_time" value="<?= html_escape($end_time) ?>" data-meeting-end-time>
		<?= form_multi_lookup_group('attendees', lang('attendess'), $attendees_selected_items, true, array('id' => 'attendees'), '', array('type' => 'user', 'min_length' => 0, 'placeholder' => lang('search') . ' ' . lang('attendess'))); ?>
		<?= form_lookup_group('user_id', lang('responsible'), $selected_user_id, $selected_user_label, true, array(), '', array('type' => 'staff')); ?>
		<div class="md:col-span-2">
			<?= form_textarea_group('description', lang('description'), (!empty($meeting_info->description) ? $meeting_info->description : ''), 3, false, array('class' => 'textarea')); ?>
		</div>
	</div>
</div>

<div class="mt-6 flex items-center justify-end gap-2">
	<button type="button" class="cancel-upload inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-xs font-semibold text-slate-600 hover:bg-slate-50" data-dismiss="modal">
		<i data-lucide="x" class="h-4 w-4"></i>
		<?= lang('close'); ?>
	</button>
	<button type="submit" class="start-upload inline-flex items-center gap-2 rounded-lg bg-slate-900 px-4 py-2.5 text-xs font-semibold text-white hover:bg-slate-800 dark:bg-slate-700 dark:hover:bg-slate-600">
		<i data-lucide="check-circle" class="h-4 w-4"></i>
		<?= $form_label; ?>
	</button>
</div>
<?php echo form_close(); ?>

<script>
(function() {
	const form = document.currentScript && document.currentScript.previousElementSibling;
	if (!form || form.dataset.meetingDatetimeBound === '1') return;
	form.dataset.meetingDatetimeBound = '1';

	const splitDatetime = function(value) {
		const normalized = String(value || '').trim().replace('T', ' ');
		const parts = normalized.split(/\s+/);
		return {
			date: parts[0] || '',
			time: (parts[1] || '').slice(0, 5)
		};
	};

	const syncFields = function() {
		const startInput = form.querySelector('[name="start_datetime"]');
		const endInput = form.querySelector('[name="end_datetime"]');
		const start = splitDatetime(startInput ? startInput.value : '');
		const end = splitDatetime(endInput ? endInput.value : '');
		const startDate = form.querySelector('[data-meeting-start-date]');
		const startTime = form.querySelector('[data-meeting-start-time]');
		const endDate = form.querySelector('[data-meeting-end-date]');
		const endTime = form.querySelector('[data-meeting-end-time]');

		if (startDate) startDate.value = start.date;
		if (startTime) startTime.value = start.time;
		if (endDate) endDate.value = end.date;
		if (endTime) endTime.value = end.time;
	};

	form.addEventListener('input', syncFields, true);
	form.addEventListener('change', syncFields, true);
	form.addEventListener('submit', syncFields, true);
	syncFields();
})();
</script>
