<?php
/**
 * Meta WhatsApp Sender for Automation Web Platform.
 * Handles Meta API settings, templates, and webhooks for the modern React dashboard.
 *
 * @package automation-web-platform
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


/**
 * Class WAWP_Meta_Sender
 *
 * @package automation-web-platform
 */
class WAWP_Meta_Sender extends WAWP_Sender_Base {
	/**
	 * Singleton instance.
	 *
	 * @var WAWP_Meta_Sender
	 */
	private static $instance = null;

	/**
	 * Get singleton instance.
	 *
	 * @return WAWP_Meta_Sender
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Setup class properties.
	 */
	protected function setup_properties() {
		$this->nonce_action = 'wawp_nonce';
	}



	/**
	 * Save Meta settings.
	 *
	 * @param array $data Settings data.
	 * @return array
	 */
	public function handle_save_settings( $data = array() ) {
		global $wpdb;
		$table  = $wpdb->prefix . 'wawp_mws_settings';
		$fields = array(
			'wawp_mws_api_token',
			'wawp_mws_waba_id',
			'wawp_mws_phone_number_id',
			'wawp_mws_verify_token',
			'wawp_mws_app_id',
			'wawp_mws_app_secret',
		);

		foreach ( $fields as $field ) {
			$val = isset( $data[ $field ] ) ? $data[ $field ] : filter_input( INPUT_POST, $field, FILTER_DEFAULT );

			if ( null !== $val ) {
				WAWP()->db->upsert_row(
					'mws_settings',
					array(
						'setting_name'  => $field,
						'setting_value' => $val,
					)
				);
			}
		}
		wp_cache_delete( 'wawp_mws_all_settings', 'wawp_meta' );

		return array(
			'success' => true,
			'message' => __( 'Meta settings saved successfully.', 'automation-web-platform' ),
		);
	}

	/**
	 * Subscribe to Meta webhooks.
	 *
	 * @return array
	 */
	public function handle_subscribe_webhooks() {
		$token   = $this->get_mws_setting( 'wawp_mws_api_token' );
		$waba_id = $this->get_mws_setting( 'wawp_mws_waba_id' );
		$app_id  = $this->get_mws_setting( 'wawp_mws_app_id' );

		if ( empty( $token ) || empty( $waba_id ) ) {
			return array(
				'success' => false,
				'message' => __( 'Access Token and WABA ID are required.', 'automation-web-platform' ),
			);
		}

		$url = "https://graph.facebook.com/v17.0/{$waba_id}/subscribed_apps";

		$response = wp_remote_post(
			$url,
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $token,
				),
				'timeout' => 20,
			)
		);

		if ( is_wp_error( $response ) ) {
			return array(
				'success' => false,
				'message' => $response->get_error_message(),
			);
		}

		$code = wp_remote_retrieve_response_code( $response );
		if ( $code >= 200 && $code < 300 ) {
			return array(
				'success' => true,
				'message' => __( 'Webhooks successfully subscribed via Direct API.', 'automation-web-platform' ),
			);
		}

		$res_body = json_decode( wp_remote_retrieve_body( $response ), true );
		return array(
			'success' => false,
			'message' => isset( $res_body['error']['message'] ) ? $res_body['error']['message'] : __( 'Failed to subscribe webhooks.', 'automation-web-platform' ),
		);
	}

	/**
	 * Fetch templates from Meta.
	 *
	 * @return array
	 */
	public function handle_fetch_templates() {
		$token   = $this->get_mws_setting( 'wawp_mws_api_token' );
		$waba_id = $this->get_mws_setting( 'wawp_mws_waba_id' );
		$app_id  = $this->get_mws_setting( 'wawp_mws_app_id' );

		if ( empty( $token ) || empty( $waba_id ) ) {
			return array(
				'success' => false,
				'message' => __( 'Access Token and WABA ID are required.', 'automation-web-platform' ),
			);
		}

		$url = "https://graph.facebook.com/v17.0/{$waba_id}/message_templates";

		$response = wp_remote_get(
			$url,
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $token,
				),
				'timeout' => 20,
			)
		);

		if ( is_wp_error( $response ) ) {
			return array(
				'success' => false,
				'message' => $response->get_error_message(),
			);
		}

		$res_body = json_decode( wp_remote_retrieve_body( $response ), true );
		if ( isset( $res_body['data'] ) && is_array( $res_body['data'] ) ) {
			global $wpdb;
			$count = 0;
			foreach ( $res_body['data'] as $tpl ) {
				if ( empty( $tpl['name'] ) ) {
					continue;
				}
				WAWP()->db->upsert_row(
					'mws_templates',
					array(
						'template_name' => $tpl['name'],
						'language_code' => isset( $tpl['language'] ) ? $tpl['language'] : 'en',
					)
				);
				++$count;
			}
			wp_cache_delete( 'wawp_mws_templates', 'wawp_database' );

			return array(
				'success'   => true,
				/* translators: %d: Number of templates synced */
				'message'   => sprintf( __( 'Sync Complete! %d templates were pulled from Meta via Direct API.', 'automation-web-platform' ), $count ),
				'templates' => array(),
			);
		}

		return array(
			'success' => false,
			'message' => isset( $res_body['error']['message'] ) ? $res_body['error']['message'] : __( 'Failed to fetch templates from Meta.', 'automation-web-platform' ),
		);
	}

	/**
	 * Send a template message.
	 *
	 * @param string $to            Recipient.
	 * @param string $template_name Template name.
	 * @param string $language_code Language code.
	 * @param array  $components    Template components.
	 * @return array
	 */
	public function send_template( $to, $template_name, $language_code, $components = array() ) {
		$token    = $this->get_mws_setting( 'wawp_mws_api_token' );
		$phone_id = $this->get_mws_setting( 'wawp_mws_phone_number_id' );

		if ( empty( $token ) || empty( $phone_id ) ) {
			return array(
				'status'  => 'error',
				'message' => __( 'Meta API Token or Phone ID is missing.', 'automation-web-platform' ),
			);
		}

		$url  = "https://graph.facebook.com/v17.0/{$phone_id}/messages";
		$body = array(
			'messaging_product' => 'whatsapp',
			'to'                => $to,
			'type'              => 'template',
			'template'          => array(
				'name'       => $template_name,
				'language'   => array( 'code' => $language_code ),
				'components' => $components,
			),
		);

		$response = wp_remote_post(
			$url,
			array(
				'body'    => wp_json_encode( $body ),
				'headers' => array(
					'Authorization' => 'Bearer ' . $token,
					'Content-Type'  => 'application/json',
				),
				'timeout' => 20,
			)
		);

		if ( is_wp_error( $response ) ) {
			return array(
				'status'  => 'error',
				'message' => $response->get_error_message(),
			);
		}

		$code     = wp_remote_retrieve_response_code( $response );
		$res_body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( $code >= 200 && $code < 300 ) {
			return array(
				'status' => 'success',
				'id'     => isset( $res_body['messages'][0]['id'] ) ? $res_body['messages'][0]['id'] : '',
			);
		}

		return array(
			'status'  => 'error',
			'message' => isset( $res_body['error']['message'] ) ? $res_body['error']['message'] : __( 'Meta API Error', 'automation-web-platform' ),
		);
	}

	/**
	 * Send a text message.
	 *
	 * @param string $to   Recipient.
	 * @param string $text Message text.
	 * @return array
	 */
	public function send_message( $to, $text ) {
		$token    = $this->get_mws_setting( 'wawp_api_token' ) ? $this->get_mws_setting( 'wawp_api_token' ) : $this->get_mws_setting( 'wawp_mws_api_token' );
		$phone_id = $this->get_mws_setting( 'wawp_phone_number_id' ) ? $this->get_mws_setting( 'wawp_phone_number_id' ) : $this->get_mws_setting( 'wawp_mws_phone_number_id' );

		if ( empty( $token ) || empty( $phone_id ) ) {
			return array(
				'status'  => 'error',
				'message' => __( 'Meta API Token or Phone ID is missing.', 'automation-web-platform' ),
			);
		}

		$url  = "https://graph.facebook.com/v17.0/{$phone_id}/messages";
		$body = array(
			'messaging_product' => 'whatsapp',
			'to'                => $to,
			'type'              => 'text',
			'text'              => array( 'body' => $text ),
		);

		$response = wp_remote_post(
			$url,
			array(
				'body'    => wp_json_encode( $body ),
				'headers' => array(
					'Authorization' => 'Bearer ' . $token,
					'Content-Type'  => 'application/json',
				),
				'timeout' => 20,
			)
		);

		if ( is_wp_error( $response ) ) {
			return array(
				'status'  => 'error',
				'message' => $response->get_error_message(),
			);
		}

		$code     = wp_remote_retrieve_response_code( $response );
		$res_body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( $code >= 200 && $code < 300 ) {
			return array(
				'status' => 'success',
				'id'     => isset( $res_body['messages'][0]['id'] ) ? $res_body['messages'][0]['id'] : '',
			);
		}

		return array(
			'status'  => 'error',
			'message' => isset( $res_body['error']['message'] ) ? $res_body['error']['message'] : __( 'Meta API Error', 'automation-web-platform' ),
		);
	}

	/**
	 * Get a Meta setting.
	 *
	 * @param string $name Setting name.
	 * @return string
	 */
	private function get_mws_setting( $name ) {
		global $wpdb;
		$table     = $wpdb->prefix . 'wawp_mws_settings';
		$cache_key = 'wawp_mws_setting_' . md5( (string) $name );
		$val       = wp_cache_get( $cache_key, 'wawp_meta' );

		if ( false === $val ) {
			$val = WAWP()->db->get_var( $wpdb->prepare( 'SELECT setting_value FROM %i WHERE setting_name = %s', $table, $name ) );
			wp_cache_set( $cache_key, $val, 'wawp_meta', 300 );
		}

		return $val;
	}

	/**
	 * Get React settings data.
	 *
	 * @return array
	 */
	public function get_react_settings_data() {
		global $wpdb;
		$settings_table  = $wpdb->prefix . 'wawp_mws_settings';
		$templates_table = $wpdb->prefix . 'wawp_mws_templates';

		$settings_results = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT setting_name, setting_value FROM %i', $settings_table ), 'wawp_mws_all_settings', 'wawp_meta', HOUR_IN_SECONDS );
		$settings         = array();
		if ( $settings_results ) {
			foreach ( $settings_results as $row ) {
				$settings[ $row['setting_name'] ] = $row['setting_value'];
			}
		}

		$templates = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT template_name, language_code FROM %i ORDER BY template_name ASC, language_code ASC', $templates_table ), 'wawp_mws_templates', 'wawp_database', HOUR_IN_SECONDS );
		if ( ! is_array( $templates ) ) {
			$templates = array();
		}

		return array(
			'settings'  => $settings,
			'templates' => $templates,
			'nonces'    => array(
				'save'    => wp_create_nonce( 'wawp_nonce' ),
				'fetch'   => wp_create_nonce( 'wawp_nonce' ),
				'webhook' => wp_create_nonce( 'wawp_nonce' ),
			),
			'i18n'      => array(
				'title'                     => __( 'Meta API Configuration', 'automation-web-platform' ),
				'subtitle'                  => __( 'Setup official WhatsApp Business API integration via Meta Cloud API.', 'automation-web-platform' ),
				'apiCredentials'            => __( 'API Credentials', 'automation-web-platform' ),
				'apiCredentialsDesc'        => __( 'Authorize your Business Account and sync tokens', 'automation-web-platform' ),
				'quickConnect'              => __( 'Quick Connect', 'automation-web-platform' ),
				'quickConnectDesc'          => __( 'Auto-fetch access tokens using your Meta App credentials below.', 'automation-web-platform' ),
				'connectWithFacebook'       => __( 'Connect with Facebook', 'automation-web-platform' ),
				'metaAppId'                 => __( 'Meta App ID (Client ID)', 'automation-web-platform' ),
				'metaAppSecret'             => __( 'Meta App Secret', 'automation-web-platform' ),
				'permanentAccessToken'      => __( 'Permanent Access Token', 'automation-web-platform' ),
				'permanentAccessTokenDesc'  => __( 'Get your permanent token from the Meta Dev Dashboard.', 'automation-web-platform' ),
				'getPermanentToken'         => __( 'Get your permanent token from the', 'automation-web-platform' ),
				'metaDevDashboard'          => __( 'Meta Dev Dashboard', 'automation-web-platform' ),
				'wabaId'                    => __( 'WhatsApp Business ID (WABA)', 'automation-web-platform' ),
				'phoneNumberId'             => __( 'Phone Number ID', 'automation-web-platform' ),
				'webhookActiveMsg'          => __( 'Cloud API credentials are set. Official Meta routing is ready for delivery.', 'automation-web-platform' ),
				'webhookInactiveMsg'        => __( 'Incomplete credentials. Please connect with Facebook or enter your IDs manually to enable Cloud API.', 'automation-web-platform' ),
				'incomingEventsWebhook'     => __( 'Incoming Events (Webhook)', 'automation-web-platform' ),
				'incomingEventsWebhookDesc' => __( 'Track delivery status and customer replies in real-time', 'automation-web-platform' ),
				'verifyToken'               => __( 'Verify Token', 'automation-web-platform' ),
				'verifyTokenDesc'           => __( 'Must match the token in Meta App Webhook Settings.', 'automation-web-platform' ),
				'restEndpointUrl'           => __( 'Rest Endpoint URL', 'automation-web-platform' ),
				'webhookWarning'            => __( 'Webhook subscriptions allow the platform to track real-time delivery status and update your logs.', 'automation-web-platform' ),
				'subscribeAutomatically'    => __( 'Subscribe Automatically', 'automation-web-platform' ),
				'webhookActive'             => __( "Webhook tracking is configured. Ensure the 'Verify Token' matches your settings in the Meta App dashboard.", 'automation-web-platform' ),
				'webhookInactive'           => __( "Webhook tracking is disabled. You won't receive real-time delivery status updates from Meta.", 'automation-web-platform' ),
				'whatsappTemplates'         => __( 'WhatsApp Templates', 'automation-web-platform' ),
				'whatsappTemplatesDesc'     => __( 'Official templates fetched from Cloud API', 'automation-web-platform' ),
				'syncNow'                   => __( 'Sync Now', 'automation-web-platform' ),
				'templateName'              => __( 'Template Name', 'automation-web-platform' ),
				'language'                  => __( 'Language', 'automation-web-platform' ),
				'contentPreview'            => __( 'Content Preview', 'automation-web-platform' ),
				'noContentPreview'          => __( 'No content preview', 'automation-web-platform' ),
				'noTemplatesSynced'         => __( 'No templates synced', 'automation-web-platform' ),
				'noTemplatesSyncedDesc'     => __( 'Templates must be approved in your Meta Business Manager before they appear here.', 'automation-web-platform' ),
				'syncComplete'              => __( 'Sync Complete! Tokens and IDs were successfully pulled from Meta.', 'automation-web-platform' ),
				'tokenUpdatedWarning'       => __( 'Token Updated! However, Meta returned no active Business Accounts. Please ensure you have added a phone number in your App Dashboard.', 'automation-web-platform' ),
				'loginFailed'               => __( 'Facebook Login cancelled or failed.', 'automation-web-platform' ),
				'enterAppIdError'           => __( 'Please enter your Meta App ID first.', 'automation-web-platform' ),
				'sdkLoadingError'           => __( 'Facebook SDK is loading. Please wait a few seconds and try again.', 'automation-web-platform' ),
				'failedFetchTemplates'      => __( 'Failed to fetch templates.', 'automation-web-platform' ),
				'failedSetWebhook'          => __( 'Failed to set webhook.', 'automation-web-platform' ),
				'unexpectedError'           => __( 'An unexpected error occurred.', 'automation-web-platform' ),
			),
		);
	}

	/**
	 * Get Meta WhatsApp templates as select options.
	 */
	public static function get_meta_templates() {
		global $wpdb;
		$db_manager = WAWP()->db;
		if ( ! isset( $db_manager->tables['mws_templates'] ) ) {
			return array();
		}
		$templates_table = $db_manager->tables['mws_templates'];

		$templates = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT template_name, language_code FROM %i ORDER BY template_name ASC, language_code ASC', $templates_table ), 'wawp_mws_templates_grouped', 'wawp_database', HOUR_IN_SECONDS );
		$options   = array();
		if ( ! empty( $templates ) ) {
			foreach ( $templates as $template ) {
				$options[] = array(
					'label' => $template['template_name'] . ' (' . $template['language_code'] . ')',
					'value' => $template['template_name'] . '|' . $template['language_code'],
				);
			}
		}

		return $options;
	}

	/**
	 * Get Meta templates grouped by name for the Flow/Notifications Builder.
	 */
	public static function get_meta_templates_grouped() {
		global $wpdb;
		$db_manager = WAWP()->db;
		if ( ! isset( $db_manager->tables['mws_templates'] ) ) {
			return array();
		}
		$templates_table = $db_manager->tables['mws_templates'];

		$rows    = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT DISTINCT template_name, language_code FROM %i ORDER BY template_name ASC, language_code ASC', $templates_table ), 'wawp_mws_templates_distinct', 'wawp_database', HOUR_IN_SECONDS );
		$grouped = array();
		foreach ( $rows as $row ) {
			$grouped[ $row['template_name'] ][] = $row['language_code'];
		}

		return $grouped;
	}
}
