<?php
include (PATH_CONTROLLERS . "Common.php") ;
require_once(PATH_MODELS . "prospect/ProspectClass.php");
require_once(PATH_MODELS . "prospect/ProspectContactClass.php");
require_once(PATH_MODELS . "prospect/ProspectConversationClass.php");
require_once(PATH_MODELS . "admin/UserGroupClass.php");
require_once(PATH_MODELS . "admin/UserRight.php");
require_once (PATH_LIB . "LicenseFile.php") ;

class ScheduleList extends MobileBase {
	private $type ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
	}
	function __destruct() {
		$this->db->close() ;
	}
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
			$isTurnOff = false;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}

			switch ($this->type) {
				case REQ_QUERY:
					$this->processQuery($params) ;
					break ;
				case REQ_VIEW:
					$this->processView() ;
					break ;
				default:
					$this->sendJsonResponse(Status::Error,"Invalid request.","") ;
					break ;
			}
			$this->db->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			die ($e->getMessage()) ;
		}
	}

	private function processQuery($params) {
		$cls = new ProspectClass($this->db);
		$clsConv = new ProspectConversationClass($this->db);
		$clsGroup = new UserGroupClass($this->db);
		$clsRight = new UserRight();

        $row_group = $clsGroup->getRecord($_SESSION[SE_USERGROUP]);
		
		if (is_null($row_group[UserGroupTable::C_RIGHTS]))
			$clsRight->initRights();
		else {
			$clsRight->toRights($row_group[UserGroupTable::C_RIGHTS]);
		}
		$rights = $clsRight->getAdminRights();
        
        $created_by  = $_SESSION[SE_USERID];
        if ($rights[UserRight::C_MARKETING_VIEW_OTHERS][UserRight::C_ENABLE] == 1 || $rights[UserRight::C_SALES_VIEW_OTHERS][UserRight::C_ENABLE] == 1) {
            $created_by =  0;
        }
        $rows = $cls->getFollowUpList($params, false, $created_by);

        $lists = [];
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
				$id = $row[ProspectTable::C_ID];
				$contact_id = $row[ProspectContactTable::C_CONTACT_ID] ?? 0;
				$conversationHistory = $clsConv->getConversationHistory($id, $contact_id, 2);

				if (!$conversationHistory || count($conversationHistory) === 0) {
					continue;
				}

				$historyHtml = $this->buildHistoryHtml(json_encode($conversationHistory));

                $status_array = ["Follow Up", "Confirmed", "Closed", "KIV"];
                $list = [
                    "id" 				=> $id,
                    "account_name" 		=> $row[ProspectTable::C_NAME],
                    "conversation_id"	=> $row[ProspectConversationTable::C_CONVERSATION_ID] ?? 0,
                    "person_id" 		=> $row[ProspectContactTable::C_PERSON_CONTACT],
                    "contact_id" 		=> $contact_id,
                    "contact_name" 		=> htmlentities($row[PersonContactTable::C_FULL_NAME] ?? ""),
                    "contact_phone" 	=> htmlentities($row[PersonContactTable::C_TELEPHONE] ?? ""),
                    "action_date" 		=> date_create($row[ProspectContactTable::C_ACTION_DATE])->format('d M Y'),
                    "action_time" 		=> date('h:i A', strtotime($row[ProspectContactTable::C_BEST_TIME])),
                    "action_location" 	=> htmlentities($row[ProspectContactTable::C_ACTION_LOCATION] ?? ""),
                    "next_action" 		=> htmlentities($row[ProspectContactTable::C_NEXT_ACTION] ?? ""),
                    "action_status" 	=> $status_array[$row[ProspectContactTable::C_ACTION_STATUS] ?? 0],
					"history_html"      => $historyHtml
                ];
                array_push($lists, $list);
            }
        }
		$htmlList = "";

		if (!is_null($lists) && count($lists) > 0) {

			// Group records by status
			$grouped = [];
			foreach ($lists as $list) {
				$status = $list["action_status"] ?: "Unspecified";
				$grouped[$status][] = $list;
			}

			// Define custom order (Confirmed first)
			$statusOrder = ["Confirmed", "Follow Up", "Closed", "KIV", "Unspecified"];

			// Sort groups according to order above
			$orderedGroups = [];
			foreach ($statusOrder as $s) {
				if (isset($grouped[$s])) {
					$orderedGroups[$s] = $grouped[$s];
					unset($grouped[$s]);
				}
			}
			
			// Add any remaining (unexpected) statuses at the end
			foreach ($grouped as $s => $items) {
				$orderedGroups[$s] = $items;
			}
			
			// Build HTML
			foreach ($orderedGroups as $status => $items) {
				$htmlList .= "<div class='status-group mb-3'>";
				$htmlList .= "<h6 class='text-primary border-bottom pb-1 mb-2'>$status</h6>";

				foreach ($items as $list) {
					$htmlList .= $this->buildHtmlList(
						$list["contact_id"],
						$list["account_name"],
						$list["contact_name"],
						$list["contact_phone"],
						$list["action_date"],
						$list["action_time"],
						$list["action_location"],
						$list["next_action"],
						$list["action_status"],
						$list["conversation_id"],
						$list["person_id"],
						$list["id"],
						$list["history_html"]
					);
				}

				$htmlList .= "</div>";
			}
		} else {
			// If no record found
			$htmlList = '
				<div class="text-center text-muted py-4">
					<i class="bi bi-calendar-x fs-1 d-block mb-2"></i>
					<p class="m-0">No schedule record</p>
				</div>';
		}

        $this->sendJsonResponse(Status::Ok, "", $htmlList, $this->type);
	}

	private function buildHtmlList($contact_id, $account_name, $contact_name, $contact_phone, $action_date, $action_time, $action_location, $next_action, $action_status, $conversation_id, $person_id, $prospect_id, $history_html) {
		return <<<HTML
			<div class="history-card position-relative mb-3 p-3 rounded shadow-sm" data-status="$action_status" style="background:#fff;">
				<div class="history-header" onclick="expandCollapse('', '#collapse_$contact_id')">
					<a class="text-decoration-none text-dark w-100">
						<div class="d-flex justify-content-between align-items-center">
							<strong>$contact_name</strong>
							<span class="history-date text-muted small">$action_date • $action_time</span>
						</div>
					</a>
				</div>

				<div class="collapse mt-2" id="collapse_$contact_id">
					<div class="border-top pt-2 pb-5">
						<div class="mb-1"><strong>$account_name</strong></div>

						<div class="d-flex align-items-center mb-1">
							<small class="me-2">Telephone: $contact_phone</small>
							<a href="tel:$contact_phone" class="btn btn-sm btn-success" title="Call $contact_name">
								<i class="bi bi-telephone"></i>
							</a>
						</div>

						<small>Meeting Place: $action_location</small><br>
						<small>Status: $action_status</small><br>
						<small>Agenda: $next_action</small>

						<div class="position-absolute" style="bottom: 8px; right: 10px;">
							<!-- Start Meeting: reuse getMeetinginfo to open meeting with this record's data -->
							<button id="btnStartFromHistory_$contact_id" class="btn btn-sm btn-primary me-2"
								onclick="getMeetinginfo($prospect_id, $person_id, $conversation_id, $contact_id, true)"
								title="Start Meeting from this history">
								<i class="bi bi-play-circle"></i>
							</button>

							<button id="btnHistory_$contact_id" class="btn btn-sm btn-secondary me-2"
								onclick="$('#conversationHistoryContainer_$contact_id').toggleClass('d-none')"
								title="View Conversation History">
								<i class="bi bi-chat-dots"></i>
							</button>

							<a onclick="getMeetinginfo($prospect_id, $person_id, $conversation_id, $contact_id)"
								class="btn btn-sm btn-warning" title="Edit Appointment">
								<i class="bi bi-pencil-square"></i>
							</a>
						</div>

						<div id="conversationHistoryContainer_$contact_id" class="conversation-history mt-3 d-none">
							<hr>
							<h6 class="text-secondary small mb-2">
								<i class="bi bi-clock-history me-1"></i>Conversation History
							</h6>
							<div class="history-list small text-muted">
								$history_html
							</div>
						</div>
					</div>
				</div>
			</div>
			HTML;
	}


	private function buildHistoryHtml($historyData) {
		if (empty($historyData)) {
			return '<p class="m-0 text-muted small">No previous conversation</p>';
		}

		// Example: if $historyData is JSON array
		$historyItems = json_decode($historyData, true);
		if (!is_array($historyItems)) return '<p class="m-0 text-muted small">No previous conversation</p>';

		$html = '<ul class="list-unstyled small">';
		foreach ($historyItems as $msg) {
			$date = date_create($msg[ProspectConversationTable::C_CREATE_DATE])->format('d M Y');
			$content = htmlentities($msg[ProspectConversationTable::C_DESC] ?? '');
			$html .= "<li class='border-bottom py-1'><strong>$date</strong><br>$content</li>";
		}
		$html .= '</ul>';

		return $html;
	}


	private function processView() {
		ob_start() ;
		include (PATH_VIEWS . "mobile/ScheduleListView.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}
}
?>
