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

<?php
$created = can_action('55', 'created');
$edited = can_action('55', 'edited');
$deleted = can_action('55', 'deleted');

$leads_view = isset($leads_view) && $leads_view === 'kanban' ? 'kanban' : 'list';

if ($leads_view == 'kanban') {
	$toggle_target = 'list';
} else {
	$toggle_target = 'kanban';
}

$lead_statuses = isset($lead_statuses) ? $lead_statuses : $this->db->order_by('order_no', 'ASC')->get('tbl_lead_status')->result();
$lead_sources = isset($lead_sources) ? $lead_sources : $this->db->order_by('lead_source_id', 'DESC')->get('tbl_lead_source')->result();

$lead_status_options = array('' => lang('all'));
if (!empty($lead_statuses)) {
	foreach ($lead_statuses as $status) {
		$lead_status_options[$status->lead_status_id] = lang($status->lead_type) . ' - ' . $status->lead_status;
	}
}

$lead_source_options = array('' => lang('all'));
if (!empty($lead_sources)) {
	foreach ($lead_sources as $source) {
		$lead_source_options[$source->lead_source_id] = $source->lead_source;
	}
}

$page_size = 6;
$load_label = lang('load_more');
if ($load_label === 'load_more') {
	$load_label = 'Load more';
}

$status_meta = array();
$tone_map = array(
	'open' => 'emerald',
	'closed' => 'rose',
	'lost' => 'rose',
	'dead' => 'slate',
	'on_hold' => 'amber',
	'in_progress' => 'blue',
);

if (!empty($lead_statuses)) {
	foreach ($lead_statuses as $status) {
		$status_meta[$status->lead_status_id] = array(
			'label' => $status->lead_status,
			'type' => $status->lead_type,
			'tone' => isset($tone_map[$status->lead_type]) ? $tone_map[$status->lead_type] : 'slate',
		);
	}
}

$kanban_columns = array();
$kanban_items = array();

if ($leads_view == 'kanban') {
	$status_counts = array();
	$count_query = $this->db
		->select('lead_status_id, COUNT(*) AS total', false)
		->from('tbl_leads')
		->where('converted_client_id', 0)
		->group_by('lead_status_id');

	if (!empty($this->items_model)) {
		$this->items_model->staff_query('tbl_leads');
	}

	$count_rows = $count_query->get()->result();
	if (!empty($count_rows)) {
		foreach ($count_rows as $row) {
			$status_counts[$row->lead_status_id] = (int) $row->total;
		}
	}

	if (!empty($lead_statuses)) {
		foreach ($lead_statuses as $status) {
			$tone = isset($status_meta[$status->lead_status_id]) ? $status_meta[$status->lead_status_id]['tone'] : 'slate';
			$kanban_columns[] = array(
				'id' => (string) $status->lead_status_id,
				'label' => $status->lead_status,
				'subtitle' => lang($status->lead_type),
				'tone' => $tone,
				'total' => isset($status_counts[$status->lead_status_id]) ? $status_counts[$status->lead_status_id] : 0,
			);
		}

		foreach ($lead_statuses as $status) {
			$tone = isset($status_meta[$status->lead_status_id]) ? $status_meta[$status->lead_status_id]['tone'] : 'slate';
			$leads_query = $this->db
				->select('tbl_leads.leads_id, tbl_leads.lead_name, tbl_leads.contact_name, tbl_leads.email, tbl_leads.phone, tbl_leads.last_contact')
				->select('COALESCE(lead_comments.comment_count, 0) AS comment_count', false)
				->select('COALESCE(lead_attachments.attachment_count, 0) AS attachment_count', false)
				->from('tbl_leads')
				->join('(SELECT module_field_id, COUNT(*) AS comment_count FROM tbl_task_comment WHERE module="leads" GROUP BY module_field_id) AS lead_comments', 'lead_comments.module_field_id = tbl_leads.leads_id', 'left')
				->join('(SELECT module_field_id, COUNT(*) AS attachment_count FROM tbl_attachments WHERE module="leads" GROUP BY module_field_id) AS lead_attachments', 'lead_attachments.module_field_id = tbl_leads.leads_id', 'left')
				->where('tbl_leads.lead_status_id', $status->lead_status_id)
				->where('tbl_leads.converted_client_id', 0)
				->order_by('tbl_leads.index_no', 'asc')
				->order_by('tbl_leads.leads_id', 'desc')
				->limit($page_size);

			if (!empty($this->items_model)) {
				$this->items_model->staff_query('tbl_leads');
			}

			$status_leads = $leads_query->get()->result();
			if (!empty($status_leads)) {
				foreach ($status_leads as $lead) {
					$subtitle_parts = array();
					if (!empty($lead->contact_name)) {
						$subtitle_parts[] = $lead->contact_name;
					}
					if (!empty($lead->email)) {
						$subtitle_parts[] = $lead->email;
					} elseif (!empty($lead->phone)) {
						$subtitle_parts[] = $lead->phone;
					}
					if (!empty($lead->last_contact)) {
						$subtitle_parts[] = time_ago($lead->last_contact);
					}

					$progress = ($status->lead_type === 'closed') ? 100 : 0;

					$kanban_items[] = array(
						'id' => (int) $lead->leads_id,
						'title' => $lead->lead_name,
						'subtitle' => !empty($subtitle_parts) ? implode(' • ', $subtitle_parts) : '',
						'progress' => $progress,
						'status' => (string) $status->lead_status_id,
						'status_label' => $status->lead_status,
						'status_tone' => $tone,
						'link' => base_url('admin/leads/leads_details/' . $lead->leads_id),
						'comments' => (int) $lead->comment_count,
						'attachments' => (int) $lead->attachment_count,
					);
				}
			}
		}
	}
}
?>

<div class="space-y-4">
	<?= message_box('success'); ?>
	<?= message_box('error'); ?>

	<?php if ($leads_view == 'kanban') { ?>
		<link rel="stylesheet" href="<?= base_url() ?>assets/plugins/kanban/kanban.css" />
		<div class="rounded-2xl border border-border bg-card p-5">
			<p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-4"><?= lang('kanban'); ?></p>
			<div class="kanban" data-kanban
				data-sort-url-base="<?= base_url('admin/leads/change_leads_status/') ?>"
				data-load-url-base="<?= base_url('admin/leads/load_status_leads/') ?>"
				data-page-size="<?= (int) $page_size ?>"
				data-load-label="<?= html_escape($load_label) ?>"
				data-columns='<?= html_escape(json_encode($kanban_columns)) ?>'
				data-items='<?= html_escape(json_encode($kanban_items)) ?>'>
				<div class="kanban-board"></div>
			</div>
		</div>
		<script src="<?= base_url() ?>assets/plugins/kanban/kanban.js"></script>
	<?php } else { ?>
		<div class="min-w-0 rounded-2xl border border-border bg-card shadow-sm">
			<div class="table-responsive p-4">
				<table class="table table-striped DataTables bulk_table" id="DataTables" cellspacing="0" width="100%">
					<thead>
						<tr>
							<?php if (!empty($deleted)) { ?>
								<th data-orderable="false">
									<div class="checkbox c-checkbox">
										<label class="needsclick">
											<input id="select_all" type="checkbox">
											</label>
									</div>
								</th>
							<?php } ?>
							<th><?= lang('lead_name') ?></th>
							<th><?= lang('contact_name') ?></th>
							<th><?= lang('email') ?></th>
							<th><?= lang('phone') ?></th>
							<th><?= lang('tags') ?></th>
							<th><?= lang('source') ?></th>
							<th><?= lang('status') ?></th>
							<th><?= lang('last_contact') ?></th>
							<th><?= lang('assigned_to') ?></th>
							<?php $show_custom_fields = custom_form_table(5, null);
							if (!empty($show_custom_fields)) {
								foreach ($show_custom_fields as $c_label => $v_fields) {
									if (!empty($c_label)) { ?>
										<th><?= $c_label ?> </th>
							<?php }
								}
							}
							?>
							<th class="col-options no-sort text-right"><?= lang('action') ?></th>
						</tr>
					</thead>
					<tbody></tbody>
				</table>
			</div>
		</div>
	<?php } ?>
</div>

<script>
	list = base_url + "admin/leads/leadList";
	window.erpDatatablePreload = window.erpDatatablePreload || {};
	window.erpDatatablePreload.DataTables = window.erpDatatablePreload.DataTables || {};
	<?php if (!empty($datatable_preload)) { ?>
	window.erpDatatablePreload.DataTables["list"] = <?= json_encode($datatable_preload, JSON_UNESCAPED_SLASHES) ?>;
	<?php } ?>
	<?php if (!empty($deleted)) { ?>
		bulk_url = base_url + "admin/leads/bulk_delete";
	<?php } ?>

	function reloadWith(filter, searchType) {
		var url = list;
		if (filter) {
			url += "/" + filter;
			if (searchType) {
				url += "/" + searchType;
			}
		}
		if (typeof table_url !== "undefined") {
			table_url(url);
		} else if (typeof fire_datatable === "function") {
			fire_datatable(url);
		}
	}

	$(function() {
		$(document).on('click', '[data-lead-filter-action]', function() {
			var $item = $(this);
			var $dropdown = $item.closest('details');
			$dropdown.find('[data-header-filter-item]').removeClass('bg-indigo-50 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300');
			$dropdown.find('[data-header-filter-item]').addClass('text-slate-700 hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800');
			$item.addClass('bg-indigo-50 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300');
			$item.removeClass('text-slate-700 hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800');
			$dropdown.find('[data-header-filter-selected]').text($item.data('lead-filter-label') || '<?= html_escape(lang('all')); ?>');
			$dropdown.prop('open', false);
			reloadWith($item.data('lead-filter') || '', $item.data('lead-search') || '');
		});
	});
</script>
