<?php

namespace Brandy\Core;

use Brandy\Newsletter\NewsletterProviderFactory;
use Brandy\Traits\SingletonTrait;
use WP_Query;

class Ajax {
	use SingletonTrait;

	protected function __construct() {
		add_action( 'wp_ajax_nopriv_brandy_search', array( $this, 'search' ) );
		add_action( 'wp_ajax_brandy_search', array( $this, 'search' ) );

		add_action( 'wp_ajax_nopriv_brandy_send_subscription', array( $this, 'send_subscription_email' ) );
		add_action( 'wp_ajax_brandy_send_subscription', array( $this, 'send_subscription_email' ) );
	}

	public function send_subscription_email() {
		try {
			$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( $_POST['nonce'] ) : '';

			if ( ! wp_verify_nonce( $nonce, 'send_subscription' ) ) {
				throw new \Error( __( 'Invalid nonce', 'brandy' ) );
			}

			$email = isset( $_POST['email'] ) ? sanitize_text_field( $_POST['email'] ) : '';

			$newsletter_extension = get_option( 'brandy_extensions', array() )['newsletter'] ?? array();

			$success_message = $newsletter_extension['success_message'] ?? 'Thank you for subscribing to our newsletter!';

			if ( empty( $email ) || ! is_email( $email ) ) {
				wp_send_json_success(
					array(
						'success' => false,
						'message' => __( 'Invalid email', 'brandy' ),
					)
				);
			}

			$newsletter_provider = NewsletterProviderFactory::create( $newsletter_extension['provider'] ?? '' );

			if ( ! $newsletter_provider ) {
				wp_send_json_success(
					array(
						'success' => false,
						'message' => __( 'Newsletter provider not found', 'brandy' ),
					)
				);
			}

			$add_subscriber_result = $newsletter_provider->add_subscriber(
				array(
					'email'   => $email,
					'name'    => '',
					'list_id' => $newsletter_extension['list_id'] ?? '',
				)
			);

			if ( ! $add_subscriber_result['success'] ) {
				wp_send_json_success(
					array(
						'success' => false,
						'message' => $add_subscriber_result['message'] ?? __( 'Subscribe failed', 'brandy' ),
					)
				);
			}

			wp_send_json_success(
				array(
					'success' => true,
					'message' => $success_message,
				)
			);
		} catch ( \Error $err ) {
			wp_send_json_success(
				array(
					'success' => false,
					'message' => $err->getMessage(),
				)
			);
		}
		die();
	}

	/**
	 * Build WP_Query args based on sort option.
	 */
	private function build_search_query_args( $post_types, $limit, $offset, $search_term, $sort_by ) {
		$args = array(
			'post_type'      => $post_types,
			'posts_per_page' => $limit,
			'offset'         => $offset,
			's'              => $search_term,
			'post_status'    => 'publish',
		);

		$allowed_sorts = array( 'relevance', 'newest', 'price_asc', 'price_desc', 'on_sale', 'popularity' );
		if ( ! in_array( $sort_by, $allowed_sorts, true ) ) {
			$sort_by = 'relevance';
		}

		switch ( $sort_by ) {
			case 'newest':
				$args['orderby'] = 'date';
				$args['order']   = 'DESC';
				break;

			case 'price_asc':
				$args['meta_key'] = '_price'; // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
				$args['orderby']  = 'meta_value_num';
				$args['order']    = 'ASC';
				break;

			case 'price_desc':
				$args['meta_key'] = '_price'; // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
				$args['orderby']  = 'meta_value_num';
				$args['order']    = 'DESC';
				break;

			case 'on_sale':
				$sale_product_ids = wc_get_product_ids_on_sale();
				$args['post__in'] = ! empty( $sale_product_ids ) ? $sale_product_ids : array( 0 );
				$args['orderby']  = 'date';
				$args['order']    = 'DESC';
				break;

			case 'popularity':
				$args['meta_key'] = 'total_sales'; // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
				$args['orderby']  = 'meta_value_num';
				$args['order']    = 'DESC';
				break;

			case 'relevance':
			default:
				$args['orderby'] = 'relevance';
				$args['order']   = 'DESC';
				break;
		}

		return $args;
	}

	/**
	 * Search function for search box element
	 */
	public function search() {
		// $nonce = isset( $_GET['nonce'] ) ? sanitize_text_field( $_GET['nonce'] ) : '';
		// if ( ! wp_verify_nonce( $nonce, 'brandy_search_action' ) ) {
		// 	wp_send_json_error(
		// 		array(
		// 			'message' => __( 'Verify nonce failed', 'brandy' ),
		// 		)
		// 	);
		// }

		try {
			$search_term = isset( $_GET['s'] ) ? sanitize_text_field( $_GET['s'] ) : ''; //phpcs:ignore.

			$post_types = isset( $_GET['post_types'] ) ? sanitize_text_field( $_GET['post_types'] ) : ''; //phpcs:ignore.
			$post_types = $post_types;

			$limit   = isset( $_GET['limit'] ) ? sanitize_text_field( $_GET['limit'] ) : ''; //phpcs:ignore.
			$offset  = isset( $_GET['offset'] ) ? sanitize_text_field( $_GET['offset'] ) : ''; //phpcs:ignore.
			$sort_by = isset( $_GET['sort_by'] ) ? sanitize_text_field( $_GET['sort_by'] ) : 'relevance'; //phpcs:ignore.

			if ( empty( $post_types ) ) {
				wp_send_json_success(
					array(
						'data' => array(),
					)
				);
			}

			$query_args = $this->build_search_query_args( $post_types, $limit, $offset, $search_term, $sort_by );
			$query      = new WP_Query( $query_args );

			ob_start();
			get_template_part(
				'template-parts/builder/elements/search-results',
				'',
				array(
					'search_query' => $query,
				)
			);
			$html = ob_get_contents();
			ob_end_clean();

			wp_send_json_success(
				array(
					'html' => $html,
				)
			);

		} catch ( \Error $err ) {
			wp_send_json_error(
				array(
					'message' => $err->getMessage(),
				)
			);
		}

	}

}
