<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://ecacode.com
 * @since      1.0.0
 *
 * @package    Eca_Socialnotify_Cf7
 * @subpackage Eca_Socialnotify_Cf7/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Eca_Socialnotify_Cf7
 * @subpackage Eca_Socialnotify_Cf7/admin
 * @author     Ecacode Team <ray@ecatechnologies.com>
 */
class Eca_Socialnotify_Cf7_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	private $general_helper;
	private $options;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;
		$this->general_helper = eca_socialnotify_cf7_general_helper();
		$this->options = $this->general_helper->get_plugin_options();
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Eca_Socialnotify_Cf7_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Eca_Socialnotify_Cf7_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/eca-socialnotify-cf7-admin.css', array(), $this->version, 'all' );

	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Eca_Socialnotify_Cf7_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Eca_Socialnotify_Cf7_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/eca-socialnotify-cf7-admin.js', array( 'jquery' ), $this->version, false );

	}

	public function eca_socialnotify_admin_menu()
	{
		add_menu_page(
			'EcaSocialNotify Settings',
			'SocialNotify Contact Form 7',
			'manage_options',
			'eca-socialnotify-cf7-settings',
			[$this, 'settings_page_callback'],
			'dashicons-testimonial',
			20
		);
	}

	public function eca_socialnotify_settings_init()
	{
		// phpcs:ignore PluginCheck.CodeAnalysis.SettingSanitization.register_settingDynamic
		register_setting(
			'eca_socialnotify_cf7_settings_group',
			'eca_socialnotify_cf7_options',
			[$this, 'validate_settings']
		);

		// General Tab Settings
		add_settings_section(
			'general_settings_section',
			'General Settings',
			[$this, 'section_info_callback'],
			'eca-socialnotify-cf7-settings-general'
		);

		add_settings_field(
			'twilio_account_sid',
			'Twilio Account SID',
			[$this, 'common_input_callback'],
			'eca-socialnotify-cf7-settings-general',
			'general_settings_section',
			[
				'placeholder' => 'Enter Twilio Account SID',
				'key' => 'twilio_account_sid',
			]
		);

		add_settings_field(
			'twilio_auth_token',
			'Twilio Auth Token',
			[$this, 'common_input_callback'],
			'eca-socialnotify-cf7-settings-general',
			'general_settings_section',
			[
				'type' => 'password',
				'placeholder' => 'Enter Twilio Auth Token',
				'key' => 'twilio_auth_token',
			]
		);

		add_settings_field(
			'twilio_phone_number',
			'Twilio Phone Number',
			[$this, 'common_input_callback'],
			'eca-socialnotify-cf7-settings-general',
			'general_settings_section',
			[
				'placeholder' => 'Enter Twilio Phone Number',
				'key' => 'twilio_phone_number',
				'text' => 'with country code, e.g., +14161234567'
			]
		);
	}

	public function settings_page_callback()
	{
	?>
		<div class="wrap">
			<h1>SocialNotify Settings</h1>
			<p><?php settings_errors('eca_socialnotify_cf7_options'); ?></p>
			<form method="post" action="options.php">
				<?php
				settings_fields('eca_socialnotify_cf7_settings_group');
				do_settings_sections('eca-socialnotify-cf7-settings-general');
				submit_button();
				?>
			</form>
		</div>
	<?php
	}

	public function section_info_callback($args)
	{
		$text =  $args['text'] ?? 'Configure the settings for your plugin.';
		echo "<p>" . esc_html($text, $this->plugin_name) . "</p>";
	}

	public function common_input_callback($args)
	{
		$input_type = $args['type'] ?? 'text';
		$input_placeholder = $args['placeholder'] ?? '';
		$key = $args['key'];
		$text = $args['text'] ?? '';
	?>
		<input type="<?php echo esc_attr($input_type) ?>" name="eca_socialnotify_cf7_options[<?php echo esc_attr($key) ?>]"
			value="<?php echo esc_attr($this->options[$key] ?? ''); ?>"
			placeholder="<?php echo esc_attr($input_placeholder); ?>" />
		<div>
			<small><?php echo esc_attr($text) ?></small>
		</div>
	<?php
	}

	public function validate_settings($input)
	{
		$sanitized_input = [];
	
		if (isset($input['twilio_account_sid'])) {
			$sanitized_input['twilio_account_sid'] = sanitize_text_field($input['twilio_account_sid']);
		}
		if (isset($input['twilio_auth_token'])) {
			$sanitized_input['twilio_auth_token'] = sanitize_text_field($input['twilio_auth_token']);
		}
		if (isset($input['twilio_phone_number'])) {
			$sanitized_input['twilio_phone_number'] = sanitize_text_field($input['twilio_phone_number']);
		}
	
		$existing_options = $this->options;
		return array_merge($existing_options, $sanitized_input);
	}

	// Contact form 7 settings
	public function addWhatsnotifyPanel( $panels ) {
		$panels = array_merge( $panels, [
			'socialnotify-panel' => array(
				'title'    => __( 'SocialNotify', 'eca-socialnotify-cf7' ),
				'callback' => [$this, 'editorWhatsnotifyPanel'],
			),
		] );
		return $panels;
	}

	public function editorWhatsnotifyPanel($post, $args = '') {
		$settings = get_post_meta($post->id(), '_socialnotify_settings', true);
		$error_logs = get_post_meta($post->id(), '_socialnotify_error_logs', true);
		$error_logs = is_array($error_logs) ? array_reverse($error_logs) : [];

		if (!$settings) {
			$settings = [
				'user_socialnotify_enabled' => '',
				'user_phone' => '',
				'user_template' => '',
				'admin_socialnotify_enabled' => '',
				'admin_phone'  => '',
				'admin_template' => '',
			];
		}
		?>
	
		<h1><?php echo esc_html(__('SocialNotify Settings', 'eca-socialnotify-cf7')); ?></h1>
		<p>
			<?php echo esc_html("You can use the following shortcodes:", 'eca-socialnotify-cf7'); ?>
			<?php $post->suggest_mail_tags(); ?>
		</p>
		<hr>
		<h2><?php echo esc_html("User Notification Settings", 'eca-socialnotify-cf7'); ?></h2>
		<label>
			<input type="checkbox" name="eca_socialnotify_settings_<?php echo esc_attr($post->id()); ?>[user_socialnotify_enabled]" value="1" <?php checked($settings['user_socialnotify_enabled'], 1); ?>>
			<?php echo esc_html("Enable User WhatsApp Notifications", 'eca-socialnotify-cf7'); ?>
		</label>

		<p><?php echo esc_html("Enter the shortcode of the user's phone number field:", 'eca-socialnotify-cf7'); ?></p>
		<input type="text" name="eca_socialnotify_settings_<?php echo esc_attr($post->id()); ?>[user_phone]" 
			value="<?php echo esc_attr($settings['user_phone']); ?>" 
			class="regular-text">
	
		<p><?php echo esc_html("Define the message template for user notifications:", 'eca-socialnotify-cf7'); ?></p>
		<textarea name="eca_socialnotify_settings_<?php echo esc_attr($post->id()); ?>[user_template]" 
			rows="4" 
			class="large-text"><?php echo esc_textarea($settings['user_template']); ?></textarea>
	
		<hr>
	
		<h2><?php echo esc_html("Admin Notification Settings", 'eca-socialnotify-cf7'); ?></h2>
		<label>
			<input type="checkbox" name="eca_socialnotify_settings_<?php echo esc_attr($post->id()); ?>[admin_socialnotify_enabled]" value="1" <?php checked($settings['admin_socialnotify_enabled'], 1); ?>>
			<?php echo esc_html("Enable Admin WhatsApp Notifications", 'eca-socialnotify-cf7'); ?>
		</label>
	
		<p><?php echo esc_html("Enter the admin's phone number with country code, e.g., +14161234567 (without shortcode):", 'eca-socialnotify-cf7'); ?></p>
		<input type="text" name="eca_socialnotify_settings_<?php echo esc_attr($post->id()); ?>[admin_phone]" 
			value="<?php echo esc_attr($settings['admin_phone']); ?>" 
			class="regular-text">
	
		<p><?php echo esc_html("Define the message template for admin notifications:", 'eca-socialnotify-cf7'); ?></p>
		<textarea name="eca_socialnotify_settings_<?php echo esc_attr($post->id()); ?>[admin_template]" 
			rows="4" 
			class="large-text"><?php echo esc_textarea($settings['admin_template']); ?></textarea>
	
		<hr>

		<h2><?php esc_html("Error Logs", 'eca-socialnotify-cf7'); ?></h2>
		<p><?php esc_html("Below are the latest error logs related to WhatsApp notifications:", 'eca-socialnotify-cf7'); ?></p>
		<textarea rows="6" class="large-text" readonly><?php echo esc_textarea($error_logs ? implode("\n", $error_logs) : __('No errors recorded.', 'eca-socialnotify-cf7')); ?></textarea>
		<?php wp_nonce_field('save_socialnotify_settings', 'eca-socialnotify-cf7'); ?>
		<?php
	}	

	public function saveWhatsnotifySettings($form) {
		$post_id = $form->id();
		if (
			(isset($_POST['eca_socialnotify_settings_' . $post_id]) &&
			isset($_POST['eca-socialnotify-cf7'])) && 
			wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['eca-socialnotify-cf7'])), 'save_socialnotify_settings')
		) {
			$options = [
				'user_socialnotify_enabled' => isset($_POST['eca_socialnotify_settings_' . $post_id]['user_socialnotify_enabled']) ? 1 : 0,
				'user_phone' => isset($_POST['eca_socialnotify_settings_' . $post_id]['user_phone']) 
					? sanitize_text_field(wp_unslash($_POST['eca_socialnotify_settings_' . $post_id]['user_phone'])) 
					: '',
				'user_template' => isset($_POST['eca_socialnotify_settings_' . $post_id]['user_template']) 
					? sanitize_textarea_field(wp_unslash($_POST['eca_socialnotify_settings_' . $post_id]['user_template'])) 
					: '',
				'admin_socialnotify_enabled' => isset($_POST['eca_socialnotify_settings_' . $post_id]['admin_socialnotify_enabled']) ? 1 : 0,
				'admin_phone' => isset($_POST['eca_socialnotify_settings_' . $post_id]['admin_phone']) 
					? sanitize_text_field(wp_unslash($_POST['eca_socialnotify_settings_' . $post_id]['admin_phone'])) 
					: '',
				'admin_template' => isset($_POST['eca_socialnotify_settings_' . $post_id]['admin_template']) 
					? sanitize_textarea_field(wp_unslash($_POST['eca_socialnotify_settings_' . $post_id]['admin_template'])) 
					: '',
			];
	
			update_post_meta($post_id, '_socialnotify_settings', $options);
		}
	}

	public function beforeSendMail($form, &$abort, $submission) {
		if (!$submission) {
			return;
		}
	
		$post_id = $form->id();
		$settings = get_post_meta($post_id, '_socialnotify_settings', true);
		$error_logs = get_post_meta($post_id, '_socialnotify_error_logs', true) ?: [];
		$is_whatsapp_sent = true;
	
		// User Notification
		if (
			!empty($settings['user_socialnotify_enabled']) && 
			!empty($settings['user_phone']) && 
			!empty($settings['user_template'])
		) {
			$user_number = trim(wpcf7_mail_replace_tags($settings['user_phone']));
			$user_message = trim(wpcf7_mail_replace_tags($settings['user_template']));
	
			if (!empty($user_number)) {
				if (!eca_socialnotify_cf7_twilio_helper()->sendWpMessage($user_number, $user_message, $error_logs)) {
					$is_whatsapp_sent = false;
				}
			}
		}
	
		// Admin Notification
		if (
			!empty($settings['admin_socialnotify_enabled']) && 
			!empty($settings['admin_phone']) && 
			!empty($settings['admin_template'])
		) {
			$admin_number = trim($settings['admin_phone']);
			$admin_message = trim(wpcf7_mail_replace_tags($settings['admin_template']));
	
			if (!empty($admin_number)) {
				if (!eca_socialnotify_cf7_twilio_helper()->sendWpMessage($admin_number, $admin_message, $error_logs)) {
					$is_whatsapp_sent = false;
				}
			}
		}

		// Save error logs
		update_post_meta($post_id, '_socialnotify_error_logs', array_slice($error_logs, -10)); // Keep last 10 errors only
	}
}
