<?php

class MVC_Library_Flow
{
	public function start($uid, $phone, $message, $flows, $subscription = [], $extra = [])
	{
		// Get flow configuration
		if(isset($flows)):
			if(is_string($flows)):
				$flows = json_decode($flows, true);
				if(json_last_error() !== JSON_ERROR_NONE):
					return [];
				endif;
			elseif(is_array($flows)):
				// Handle flows from database (array with IDs as keys)
				$allFlowSteps = [];
				foreach($flows as $id => $flow):
					if(isset($flow['flow_data'])):
						$flowData = json_decode($flow['flow_data'], true);
						if(json_last_error() === JSON_ERROR_NONE && !empty($flowData) && isset($flowData['drawflow']['Home']['data'])):
							// Find source node
							$sourceNode = false;
							foreach($flowData['drawflow']['Home']['data'] as $node) {
								if($node['name'] === 'sms' || $node['name'] === 'whatsapp') {
									$sourceNode = $node['name'];
									break;
								}
							}

							// Process flow if valid source node found
							if($sourceNode) {
								$flowSteps = $this->processFlow(
									$uid,
									$sourceNode,
									$phone,
									$message,
									$flowData,
									$subscription,
									$extra
								);
								
								if(!empty($flowSteps)) {
									$allFlowSteps[] = [
										'id' => $id,
										'name' => $flow['name'],
										'steps' => $flowSteps
									];
								}
							}
						endif;
					endif;
				endforeach;
				return $allFlowSteps;
			endif;
		endif;

		return [];
	}

	public function processFlow($uid, $source, $phone, $message, $flowData, $subscription = [], $extra = [])
	{
		$flowSteps = [];

		if(empty($flowData) || !isset($flowData["drawflow"]["Home"]["data"])):
			return $flowSteps;
		endif;

		// Find source nodes (SMS or WhatsApp)
		$sourceNodes = [];
		foreach($flowData["drawflow"]["Home"]["data"] as $nodeId => $node):
			if($node["name"] === $source):
				// For WhatsApp, check if the account matches
				if($source === "whatsapp" && isset($node["data"]["whatsapp"])):
					if($node["data"]["whatsapp"] !== $extra["account"]):
						continue;
					endif;
				endif;

				// For SMS, check if the device matches
				if($source === "sms" && isset($node["data"]["sms"])):
					if($node["data"]["sms"] !== $extra["device"]):
						continue;
					endif;
				endif;

				$sourceNodes[] = $node;
			endif;
		endforeach;

		// Process each matching source node
		foreach($sourceNodes as $sourceNode):
			$nodesToProcess = [[
				"node" => $sourceNode["id"],
				"parent" => null,
				"pathValid" => true
			]];
			$processedNodes = [];

			// Process all nodes in the queue
			while(!empty($nodesToProcess)):
				$current = array_shift($nodesToProcess);
				$currentNodeId = $current["node"];

				// Skip if already processed in this path
				if(in_array($currentNodeId, $processedNodes)):
					continue;
				endif;

				$currentNode = $flowData["drawflow"]["Home"]["data"][$currentNodeId] ?? null;
				if(!$currentNode):
					continue;
				endif;

				$processedNodes[] = $currentNodeId;

				// If the path is invalid, skip processing this node
				if(!$current["pathValid"]):
					continue;
				endif;

				// Process node based on its type
				switch($currentNode["name"]):
					case "send_text":
						$replyMessage = $currentNode["data"]["message"] ?? "";
						if($replyMessage):
							if($source === "whatsapp"):
								$flowSteps[] = [
									"type" => "send_text",
									"priority" => $currentNode["data"]["priority"] ?? 2,
									"account" => $extra["account"],
									"message" => json_encode([
										"text" => (new \Lex\Parser())->parse(footermark($subscription["footermark"], $replyMessage, system_message_mark), [
											"phone" => $phone,
											"message" => $message,
											"date" => [
												"now" => date("F j, Y"),
												"time" => date("h:i A")
											]
										])
									])
								];
							else:
								$flowSteps[] = [
									"type" => "send_text",
									"priority" => $currentNode["data"]["priority"] ?? 2,
									"device" => $extra["device"],
									"message" => (new \Lex\Parser())->parse(footermark($subscription["footermark"], $replyMessage, system_message_mark), [
										"phone" => $phone,
										"message" => $message,
										"date" => [
											"now" => date("F j, Y"),
											"time" => date("h:i A")
										]
									])
								];
							endif;
						endif;
						break;

					case "send_image":
						if($source === "whatsapp"):
							$imageUrl = $currentNode["data"]["value"] ?? "";
							$caption = $currentNode["data"]["caption"] ?? "";
							if($imageUrl):
								$flowSteps[] = [
									"type" => "send_image",
									"priority" => $currentNode["data"]["priority"] ?? 2,
									"account" => $extra["account"],
									"message" => json_encode([
										"image" => [
											"url" => filter_var($imageUrl, FILTER_VALIDATE_URL) === false ? site_url($imageUrl, true) : $imageUrl
										],
										"caption" => (new \Lex\Parser())->parse(footermark($subscription["footermark"], $caption, system_message_mark), [
											"phone" => $phone,
											"message" => $message,
											"date" => [
												"now" => date("F j, Y"),
												"time" => date("h:i A")
											]
										])
									])
								];
							endif;
						endif;
						break;

					case "send_video":
						if($source === "whatsapp"):
							$videoUrl = $currentNode["data"]["value"] ?? "";
							$caption = $currentNode["data"]["caption"] ?? "";
							if($videoUrl):
								$flowSteps[] = [
									"type" => "send_video",
									"priority" => $currentNode["data"]["priority"] ?? 2,
									"account" => $extra["account"],
									"message" => json_encode([
										"video" => [
											"url" => filter_var($videoUrl, FILTER_VALIDATE_URL) === false ? site_url($videoUrl, true) : $videoUrl
										],
										"caption" => (new \Lex\Parser())->parse(footermark($subscription["footermark"], $caption, system_message_mark), [
											"phone" => $phone,
											"message" => $message,
											"date" => [
												"now" => date("F j, Y"),
												"time" => date("h:i A")
											]
										])
									])
								];
							endif;
						endif;
						break;

					case "send_audio":
						if($source === "whatsapp"):
							$audioUrl = $currentNode["data"]["value"] ?? "";
							if($audioUrl):
								$flowSteps[] = [
									"type" => "send_audio",
									"priority" => $currentNode["data"]["priority"] ?? 2,
									"account" => $extra["account"],
									"message" => json_encode([
										"audio" => [
											"url" => filter_var($audioUrl, FILTER_VALIDATE_URL) === false ? site_url($audioUrl, true) : $audioUrl
										]
									])
								];
							endif;
						endif;
						break;

					case "send_document":
						if($source === "whatsapp"):
							$file = $currentNode["data"]["value"] ?? "";
							$filename = basename($file);
							if($file):
								$flowSteps[] = [
									"priority" => $currentNode["data"]["priority"] ?? 2,
									"account" => $extra["account"],
									"message" => json_encode([
										"message_type" => "document",
										"document" => filter_var($file, FILTER_VALIDATE_URL) === false ? site_url($file, true) : $file,
										"filename" => $filename
									])
								];
							endif;
						endif;
						break;

					case "ai_reply":
						$aiKey = $currentNode["data"]["ai_key"] ?? "";
						$aiPlugin = $currentNode["data"]["ai_plugin"] ?? "";
						
						$flowSteps[] = [
							"type" => "ai_reply",
							"ai_key" => $aiKey,
							"ai_plugin" => (int) $aiPlugin,
							"message" => $message
						];
						break;

					case "save_contact":
						$group = $currentNode["data"]["group"] ?? "";

						$flowSteps[] = [
							"type" => "save_contact",
							"group" => $group
						];
						break;

					case "condition":
						$conditionType = $currentNode["data"]["condition"] ?? "contains";
						$value = $currentNode["data"]["value"] ?? "";
						$result = false;

						switch($conditionType):
							case "starts_with":
								$result = stripos($message, $value) === 0;
								break;
							case "ends_with":
								$result = substr_compare($message, $value, -strlen($value)) === 0;
								break;
							case "contains":
								$result = stripos($message, $value) !== false;
								break;
							case "equal":
								$result = strcasecmp($message, $value) === 0;
								break;
							case "not_contain":
								$result = stripos($message, $value) === false;
								break;
							case "regex":
								$result = preg_match($value, $message) === 1;
								break;
						endswitch;

						if(!$result):
							$current["pathValid"] = false;
						endif;
						break;
				endswitch;

				if(isset($currentNode["outputs"])):
					foreach($currentNode["outputs"] as $output):
						if(isset($output["connections"])):
							foreach($output["connections"] as $connection):
								$nodesToProcess[] = [
									"node" => $connection["node"],
									"parent" => $currentNodeId,
									"pathValid" => $current["pathValid"]
								];
							endforeach;
						endif;
					endforeach;
				endif;
			endwhile;
		endforeach;

		return $flowSteps;
	}
}