<?php

namespace SEOAIC;

use Exception;
use SeoaicAjaxValidation;

class SEOAIC_PROMOTE
{
	private $seoaic;
	private $endpointGetMedia = 'api/backlink-promotion/get-media-list';
	private $endpointSendPromote = 'api/backlink-promotion/send-result';
	private $defaultLanguage = 'en';
	private $companyName = '';

	public function __construct( $seoaic )
	{
		global $SEOAIC_OPTIONS;

		$this->seoaic = $seoaic;

		$lang = substr( get_locale(), 0, 2 );
		$this->defaultLanguage = $lang ? $lang : 'en';
		$this->companyName = !empty($SEOAIC_OPTIONS['seoaic_business_name']) ? $SEOAIC_OPTIONS['seoaic_business_name'] : get_option('blogname', true);

		add_action( 'wp_ajax_seoaic_get_promote_media_list', [ $this, 'fetchMediaList' ] );
		add_action( 'wp_ajax_seoaic_send_to_promote', [ $this, 'submitPromotionRequest' ] );
	}

	public function getDefaultMediaList()
	{
		$defaultMediaPayload = array(
			'data' => array(
				'filters' => array(
				),
				'limit' => 24
			)
		);

		try {
			$response = $this->seoaic->curl->init( $this->endpointGetMedia, $defaultMediaPayload, true, true, true );

			if( ! empty( $response ) ) {
				return  $response;
			}else{
				throw new Exception( 'No result' );
			}

		} catch ( Exception $e ) {
			return $e;
		}
	}

	public function fetchMediaList()
	{
		check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

		$this->validateRequestData( $_REQUEST );

		$request = wp_unslash( $_REQUEST );
		$payload = $this->buildFetchPayload( $request );

		try {
			$response = $this->seoaic->curl->init( $this->endpointGetMedia, $payload, true, true, true );

			if( ! empty( $response ) ) {
				SEOAICAjaxResponse::success()->addFields( $response )->wpSend();
			}else{
				throw new Exception( 'No result' );
			}

		} catch ( Exception $e ) {
			SEOAICAjaxResponse::error( $e->getMessage() )->wpSend();
		}
	}

	public function submitPromotionRequest()
	{
		check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

		$this->validateRequestData(
			$_REQUEST,
			array(
				'post_id',
				'media_id',
				'media_name',
				'final_price'
			)
		);

		$request = wp_unslash( $_REQUEST );
		$payload = $this->buildRequestPayload( $request );

		try {
			$response = $this->seoaic->curl->init( $this->endpointSendPromote, $payload, true, true, true );

			if( ! empty( $response ) ) {
				SEOAICAjaxResponse::success()->addFields( $response )->wpSend();
			}else{
				throw new Exception( 'No result' );
			}

		} catch ( Exception $e ) {
			SEOAICAjaxResponse::error( $e->getMessage() )->wpSend();
		}
	}

	public function getDefaultLanguage()
	{
		return $this->defaultLanguage;
	}

	private function validateRequestData( $request, $required_fields = array() )
	{
		if ( ! is_array( $request ) || empty( $request ) ) {
			SEOAICAjaxResponse::error( 'Invalid request payload.' )->wpSend();
		}

		if ( ! empty( $required_fields ) ) {
			foreach ( $required_fields as $required_field ) {
				if ( ! isset( $request[ $required_field ] ) || empty( $request[ $required_field ] ) ) {
					SEOAICAjaxResponse::error( 'Missing or empty required field: ' . $required_field )->wpSend();
				}
			}
		}
	}

	private function buildFetchPayload( $data )
	{
		$data = $data['data'];
		$page = $data['page'] ?: 1;
		$filters = $data['filters'] ?: [];

		$payload = array(
			'data' => array(
				'filters' => $filters,
				'page' => $page,
				'limit' => 24
			)
		);

		return $payload;
	}

	private function buildRequestPayload( $data )
	{
		$payload = array(
			'data' => array(
				'post' => array(
					'title' => get_the_title( $data['post_id'] ),
					'url' => get_the_permalink( $data['post_id'] )
				),
				'company_name' => $this->companyName,
				'media_id' => $data['media_id'],
				'media_name' => $data['media_name'],
				'final_price' => $data['final_price'],
			)
		);

		return $payload;
	}
}