<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Handles all AJAX requests for the theme builder.
 */
class Sifency_Ajax {

	public function __construct() {
		$actions = [
			'toggle_template_status',
			'save_display_conditions',
			'get_display_conditions',
			'search_posts_terms',
			'create_new_template',
		];

		foreach ( $actions as $action ) {
			add_action( "wp_ajax_sifency_{$action}", [ $this, "ajax_{$action}" ] );
		}
	}

	public function ajax_create_new_template() {
        check_ajax_referer( 'sifency_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( [ 'message' => 'Permission denied.' ] );
		}

        $title = isset( $_POST['title'] ) ? sanitize_text_field( $_POST['title'] ) : '';
        $type  = isset( $_POST['type'] ) ? sanitize_key( $_POST['type'] ) : '';

        if ( empty( $title ) ) {
            wp_send_json_error( [ 'message' => 'Template title is required.' ] );
        }
        if ( empty( $type ) || !term_exists( $type, 'sifency_builder_type' ) ) {
            wp_send_json_error( [ 'message' => 'Invalid template type.' ] );
        }

        $new_post_args = [
            'post_type'   => 'themebuilder',
            'post_title'  => $title,
            'post_status' => 'draft',
            'tax_input'   => [
                'sifency_builder_type' => [ $type ],
            ],
        ];

        $post_id = wp_insert_post( $new_post_args, true );

        if ( is_wp_error( $post_id ) ) {
            wp_send_json_error( [ 'message' => $post_id->get_error_message() ] );
        }

        wp_send_json_success( [
            'message'  => 'Template created successfully!',
            'post_id'  => $post_id,
            'edit_url' => admin_url( 'post.php?post=' . $post_id . '&action=elementor' )
        ] );
    }

	public function ajax_toggle_template_status() {
		check_ajax_referer( 'sifency_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( [ 'message' => 'Permission denied.' ] );
		$sifency_addons_template_id = isset( $_POST['template_id'] ) ? intval( $_POST['template_id'] ) : 0;
		$is_active   = isset( $_POST['is_active'] ) && 'true' === $_POST['is_active'];
		if ( ! $sifency_addons_template_id || get_post_type( $sifency_addons_template_id ) !== 'themebuilder' ) wp_send_json_error( [ 'message' => 'Invalid template ID.' ] );
		update_post_meta( $sifency_addons_template_id, '_sifency_builder_active', $is_active ? '1' : '0' );
		wp_send_json_success( [ 'message' => 'Status updated.' ] );
	}

	public function ajax_save_display_conditions() {
		check_ajax_referer( 'sifency_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( [ 'message' => 'Permission denied.' ] );
		$sifency_addons_template_id = isset( $_POST['template_id'] ) ? intval( $_POST['template_id'] ) : 0;
		$conditions_json = isset( $_POST['conditions'] ) ? wp_unslash( $_POST['conditions'] ) : '[]';
		$conditions = json_decode( $conditions_json, true );
		if ( ! $sifency_addons_template_id || get_post_type( $sifency_addons_template_id ) !== 'themebuilder' ) wp_send_json_error( [ 'message' => 'Invalid template ID.' ] );
		$sanitized_conditions = $this->sanitize_conditions_array( $conditions );
		update_post_meta( $sifency_addons_template_id, '_themebuilder_conditions', $sanitized_conditions );
		$include_count = count( $sanitized_conditions['include'] ?? [] );
		$exclude_count = count( $sanitized_conditions['exclude'] ?? [] );
		$summary = sprintf(
			/* translators: %1$d: number of included items, %2$d: number of excluded items */
			esc_html__( '%1$d Include, %2$d Exclude', 'sifency-addons' ),
			$include_count,
			$exclude_count
		);
		wp_send_json_success( [ 'message' => 'Conditions saved.', 'summary' => $summary ] );
	}

	public function ajax_get_display_conditions() {
		check_ajax_referer( 'sifency_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( [ 'message' => 'Permission denied.' ] );
		$sifency_addons_template_id = isset( $_POST['template_id'] ) ? intval( $_POST['template_id'] ) : 0;
		if ( ! $sifency_addons_template_id || get_post_type( $sifency_addons_template_id ) !== 'themebuilder' ) wp_send_json_error( [ 'message' => 'Invalid template ID.' ] );
		$conditions = get_post_meta( $sifency_addons_template_id, '_themebuilder_conditions', true );
		$conditions = is_array( $conditions ) ? $conditions : [ 'include' => [], 'exclude' => [] ];
		$render_condition_rows = function( $rules ) {
			if ( empty( $rules ) ) {
				echo '<p class="sifency-no-rules-message">' . esc_html__( 'No conditions set.', 'sifency-addons' ) . '</p>';
			} else {
				foreach ( $rules as $rule ) $this->render_single_condition_row( $rule );
			}
		};
		ob_start();
		?>
		<div class="sifency-conditions-builder">
			<div class="sifency-conditions-group">
				<h3><?php esc_html_e( 'Include', 'sifency-addons' ); ?></h3>
				<div class="sifency-conditions-list" id="sifency-include-rules"><?php $render_condition_rows( $conditions['include'] ?? [] ); ?></div>
				<button class="button sifency-add-condition sifency-badge include sifency-admin-btn" data-group="include"><?php esc_html_e( 'Add Include Rule', 'sifency-addons' ); ?></button>
			</div>
			<div class="sifency-conditions-group">
				<h3><?php esc_html_e( 'Exclude', 'sifency-addons' ); ?></h3>
				<div class="sifency-conditions-list" id="sifency-exclude-rules"><?php $render_condition_rows( $conditions['exclude'] ?? [] ); ?></div>
				<button class="button sifency-add-condition sifency-badge exclude sifency-admin-btn" data-group="exclude"><?php esc_html_e( 'Add Exclude Rule', 'sifency-addons' ); ?></button>
			</div>
		</div>
		<div id="sifency-condition-row-template" style="display: none;"><?php $this->render_single_condition_row(); ?></div>
		<?php
		wp_send_json_success( [ 'html' => ob_get_clean() ] );
	}

	public function ajax_search_posts_terms() {
		check_ajax_referer( 'sifency_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();
		$search_term = isset( $_GET['q'] ) ? sanitize_text_field( wp_unslash( $_GET['q'] ) ) : '';
		$search_type = isset( $_GET['search_type'] ) ? sanitize_key( $_GET['search_type'] ) : 'post';
		$results = [];
		switch ( $search_type ) {
			case 'post':
			case 'page':
			case 'product':
			case 'download':
			case 'portfolio':
			case 'service':
			case 'team':
			case 'event':
			case 'career':
			case 'digital':
			case 'doc':
				$query = new WP_Query( [ 'post_type' => $search_type, 's' => $search_term, 'post_status' => 'publish', 'posts_per_page' => 20 ] );
				if ( $query->have_posts() ) {
					foreach ( $query->posts as $post ) $results[] = [ 'id' => $post->ID, 'text' => $post->post_title ];
				}
				break;
			case 'in_category': case 'category':
				$terms = get_terms( [ 'taxonomy' => 'category', 'name__like' => $search_term, 'number' => 20, 'hide_empty' => false ] );
				if ( ! is_wp_error( $terms ) ) {
					foreach ( $terms as $term ) $results[] = [ 'id' => $term->term_id, 'text' => $term->name ];
				}
				break;
			case 'tag':
				$terms = get_terms( [ 'taxonomy' => 'post_tag', 'name__like' => $search_term, 'number' => 20, 'hide_empty' => false ] );
				if ( ! is_wp_error( $terms ) ) {
					foreach ( $terms as $term ) $results[] = [ 'id' => $term->term_id, 'text' => $term->name ];
				}
				break;
			case 'author':
				$users = get_users( [ 'search' => '*' . $search_term . '*', 'search_columns' => [ 'user_login', 'user_nicename', 'display_name' ], 'number' => 20 ] );
				foreach ( $users as $user ) $results[] = [ 'id' => $user->ID, 'text' => $user->display_name ];
				break;
		}
		wp_send_json_success( $results );
	}

	/**
	 * Sanitizes the display conditions array from an AJAX request.
	 */
	private function sanitize_conditions_array( $conditions ) {
		if ( ! is_array( $conditions ) ) return [ 'include' => [], 'exclude' => [] ];
		$sanitized = [ 'include' => [], 'exclude' => [] ];
		foreach ( [ 'include', 'exclude' ] as $group ) {
			if ( isset( $conditions[ $group ] ) && is_array( $conditions[ $group ] ) ) {
				foreach ( $conditions[ $group ] as $rule ) {
					if ( ! is_array( $rule ) || empty( $rule['type'] ) ) continue;
					$sanitized[ $group ][] = [
						'type'    => sanitize_key( $rule['type'] ),
						'subtype' => isset( $rule['subtype'] ) ? sanitize_key( $rule['subtype'] ) : '',
						'value'   => isset( $rule['value'] ) ? sanitize_text_field( $rule['value'] ) : '',
					];
				}
			}
		}
		return $sanitized;
	}

	/**
	 * Renders a single row for the display conditions modal.
	 */
	private function render_single_condition_row( $rule = null ) {
		$type = $rule['type'] ?? 'general';
		$subtype = $rule['subtype'] ?? '';
		$value = $rule['value'] ?? '';

		$combined_subtype = $subtype;
		if ( in_array($subtype, ['post_type', 'post_type_archive']) && !empty($value) ) {
			$combined_subtype = $subtype . '-' . $value;
		}
		?>
		<div class="sifency-condition-row" data-subtype="<?php echo esc_attr($combined_subtype); ?>" data-value="<?php echo esc_attr($value); ?>">
			<select class="sifency-condition-type" name="type">
				<option value="general" <?php selected( $type, 'general' ); ?>><?php esc_html_e( 'General', 'sifency-addons' ); ?></option>
				<option value="singular" <?php selected( $type, 'singular' ); ?>><?php esc_html_e( 'Singular', 'sifency-addons' ); ?></option>
				<option value="archive" <?php selected( $type, 'archive' ); ?>><?php esc_html_e( 'Archives', 'sifency-addons' ); ?></option>
			</select>
			<select class="sifency-condition-subtype" name="subtype"></select>
			<select class="sifency-condition-value" name="value" data-placeholder="<?php esc_attr_e( 'Select...', 'sifency-addons' ); ?>">
				<?php
				if ( ! empty( $value ) ) {
					$text = '';
					switch ( $subtype ) {
						case 'post':
						case 'page':
						case 'product':
						case 'download':
						case 'portfolio':
						case 'service':
						case 'team':
						case 'event':
						case 'career':
						case 'doc':
						case 'digital':
							$text = get_the_title( $value ); break;
						case 'in_category': case 'category': case 'tag':
							$term = get_term( $value );
							if ( ! is_wp_error( $term ) && $term ) $text = $term->name;
							break;
						case 'author':
							$user = get_userdata( $value );
							if ( $user ) $text = $user->display_name;
							break;
					}
					if ( ! empty( $text ) ) {
						echo '<option value="' . esc_attr( $value ) . '" selected="selected">' . esc_html( $text ) . '</option>';
					}
				}
				?>
			</select>
			<a href="#" class="sifency-remove-condition dashicons-before dashicons-no-alt sifency-admin-btn"></a>
		</div>
		<?php
	}
}