<?php

namespace Alexr\Settings;

use Alexr\Models\Restaurant;
use Alexr\Settings\Traits\UseMessageTags;
use Evavel\Models\SettingListing;

class WhatsappAction extends SettingListing
{
	use UseMessageTags;
	public $is_whatsapp = true;

	public static $meta_key = 'whatsapp_action';
	public static $table_name = 'restaurant_setting';
	public static $pivot_tenant_field = 'restaurant_id';
	public static $component_list_item = 'item-whatsapp-action';

	protected $casts = [
		'whatsapp_active' => 'boolean',
	];

	public static function description() {
		return __eva('Configure keyword-triggered WhatsApp actions. When a customer sends a message matching the keywords, an automatic response will be sent using a template or custom message.');
	}

	public function restaurant()
	{
		return $this->belongsTo(Restaurant::class);
	}

	public function fields()
	{
		return [
			[
				'attribute' => 'name',
				'stacked' => true,
				'inputClass' => 'form-input-bordered-highlight',
				'name' => __eva('Action Name'),
				'helpText' => __eva('Use this field to identify your action (e.g., "Opening Hours", "Menu Request", "Location Info").'),
				'component' => 'text-field',
				'value' => $this->name
			],
			[
				'attribute' => 'whatsapp_active',
				'stacked' => true,
				'style' => 'display: inline-block; width: 20%; vertical-align: top;',
				'name' => __eva('Enable this action'),
				'component' => 'boolean-field',
				'type' => 'switch',
				'value' => $this->whatsapp_active
			],
			[
				'attribute' => 'whatsapp_action',
				'stacked' => true,
				'name' => __eva('WhatsApp action configuration'),
				'component' => 'group-whatsapp-action-field',
				'helpText' => __eva('Configure keywords and response for each language. When a customer message contains any of the keywords, the configured response will be sent automatically.'),
				'value' => $this->valueWithLanguagesFor('whatsapp_action'),
				'bookingFields' => self::getBookingFields(),
				'restaurantTags' => self::getRestaurantTags(),
				'isAdmin' => false,
			],
		];
	}

	public function defaultValue()
	{
		return [
			'name' => __eva('WhatsApp Action'),
			'whatsapp_active' => false,
			'whatsapp_action' => $this->getDefaultActionValue(),
		];
	}

	/**
	 * Get default action value structure for all languages
	 *
	 * @return array
	 */
	protected function getDefaultActionValue()
	{
		$languages = evavel_languages_allowed();
		$value = [];

		foreach ($languages as $lang => $label) {
			$value[$lang] = [
				'keywords' => '',
				'response_type' => 'template', // 'template' or 'custom'
				'template_sid' => '',
				'template_name' => '',
				'field_mapping' => [],
				'custom_message' => '',
			];
		}

		return $value;
	}

	/**
	 * Get value with languages for a specific field
	 *
	 * @param string $key
	 * @return array
	 */
	public function valueWithLanguagesFor($key)
	{
		$languages = evavel_languages_allowed();
		$value = $this->{$key};

		if (!is_array($value)) {
			$value = [];
		}

		// Ensure all languages have a configuration
		foreach ($languages as $lang => $label) {
			if (!isset($value[$lang])) {
				$value[$lang] = [
					'keywords' => '',
					'response_type' => 'template',
					'template_sid' => '',
					'template_name' => '',
					'field_mapping' => [],
					'custom_message' => '',
				];
			}
		}

		return $value;
	}

	/**
	 * Get configured action for a specific language
	 *
	 * @param string $language
	 * @return array|null
	 */
	public function getActionConfig($language)
	{
		$config = $this->whatsapp_action;

		if (!is_array($config) || !isset($config[$language])) {
			return null;
		}

		return $config[$language];
	}

	/**
	 * Check if the action is enabled
	 *
	 * @return bool
	 */
	public function isEnabled()
	{
		return (bool) $this->whatsapp_active;
	}

	/**
	 * Get keywords for a specific language as an array
	 *
	 * @param string $language
	 * @return array
	 */
	public function getKeywords($language)
	{
		$config = $this->getActionConfig($language);

		if (!$config || empty($config['keywords'])) {
			return [];
		}

		// Keywords are stored comma-separated
		return array_map('trim', array_filter(explode(',', $config['keywords'])));
	}

	/**
	 * Check if a message matches any of the keywords for a given language
	 *
	 * @param string $message The incoming message text
	 * @param string $language The language code
	 * @return bool
	 */
	public function matchesKeywords($message, $language)
	{
		$keywords = $this->getKeywords($language);

		if (empty($keywords)) {
			return false;
		}

		$messageLower = mb_strtolower(trim($message));

		foreach ($keywords as $keyword) {
			$keywordLower = mb_strtolower(trim($keyword));
			if (!empty($keywordLower) && mb_strpos($messageLower, $keywordLower) !== false) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Get the response type for a given language ('template' or 'custom')
	 *
	 * @param string $language
	 * @return string
	 */
	public function getResponseType($language)
	{
		$config = $this->getActionConfig($language);

		if (!$config || empty($config['response_type'])) {
			return 'template';
		}

		return $config['response_type'];
	}

	/**
	 * Check if the response is a template for a given language
	 *
	 * @param string $language
	 * @return bool
	 */
	public function isTemplateResponse($language)
	{
		return $this->getResponseType($language) === 'template';
	}

	/**
	 * Check if the response is a custom message for a given language
	 *
	 * @param string $language
	 * @return bool
	 */
	public function isCustomResponse($language)
	{
		return $this->getResponseType($language) === 'custom';
	}

	/**
	 * Get the custom message for a given language
	 *
	 * @param string $language
	 * @return string
	 */
	public function getCustomMessage($language)
	{
		$config = $this->getActionConfig($language);

		if (!$config || empty($config['custom_message'])) {
			return '';
		}

		return $config['custom_message'];
	}

	/**
	 * Get the template config for a given language (same structure as other WhatsApp settings)
	 *
	 * @param string $language
	 * @return array|null
	 */
	public function getTemplateConfig($language)
	{
		$config = $this->getActionConfig($language);

		if (!$config || empty($config['template_sid'])) {
			return null;
		}

		return [
			'template_sid' => $config['template_sid'],
			'template_name' => $config['template_name'] ?? '',
			'field_mapping' => $config['field_mapping'] ?? [],
			'book_now_widget_id' => $config['book_now_widget_id'] ?? null
		];
	}
}
