<?php

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

class AIEO_DMM_SEO_Social extends AIEO_DMM_Module_Base {

	public function get_id()       { return 'seo_social'; }
	public function get_label()    { return __( 'Social', 'ai-eshop-optimizer' ); }
	public function get_priority() { return 10; }
	public function get_group()    { return 'seo'; }
	public function get_section()  { return 'social'; }

	public function register_hooks() {
		add_action( 'wp_ajax_aieo_seo_save_social', array( $this, 'ajax_save' ) );
	}

	public function ajax_save() {
		AIEO_DMM::verify_ajax_request();

		$twitter = isset( $_POST['twitter_user'] ) ? sanitize_text_field( wp_unslash( $_POST['twitter_user'] ) ) : '';
		$twitter = ltrim( trim( $twitter ), '@' );

		$urls = array();
		if ( isset( $_POST['social_urls'] ) ) {
			foreach ( preg_split( '/\r\n|\r|\n/', (string) wp_unslash( $_POST['social_urls'] ) ) as $line ) {
				$u = esc_url_raw( trim( $line ) );
				if ( '' !== $u ) {
					$urls[] = $u;
				}
			}
		}

		$clean = array(
			'og_default_image' => isset( $_POST['og_default_image'] ) ? esc_url_raw( wp_unslash( $_POST['og_default_image'] ) ) : '',
			'twitter_user'     => $twitter,
			'social_urls'      => array_values( array_unique( $urls ) ),
		);
		AIEO_DMM_Settings::update( array( 'seo' => $clean ) );
		wp_send_json_success( array( 'message' => __( 'Social settings saved.', 'ai-eshop-optimizer' ) ) );
	}

	public function render_subtab() {
		if ( function_exists( 'wp_enqueue_media' ) ) {
			wp_enqueue_media();
		}
		$this->render_template(
			'seo/social.php',
			array(
				'seo'   => (array) AIEO_DMM_Settings::get( 'seo', array() ),
				'nonce' => wp_create_nonce( AIEO_DMM::NONCE_ACTION ),
				'ajax'  => admin_url( 'admin-ajax.php' ),
			)
		);
	}
}
