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

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

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

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

	public function ajax_create_new_template() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security verification failed.' ) );
		}
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( array( '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( array( 'message' => 'Template title is required.' ) );
		}
		if ( empty( $type ) || ! term_exists( $type, 'sifency_builder_type' ) ) {
			wp_send_json_error( array( 'message' => 'Invalid template type.' ) );
		}

		$new_post_args = array(
			'post_type'   => 'themebuilder',
			'post_title'  => $title,
			'post_status' => 'draft',
			'tax_input'   => array(
				'sifency_builder_type' => array( $type ),
			),
		);

		$post_id = wp_insert_post( $new_post_args, true );

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

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

	public function ajax_update_template_details() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'sifency_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security verification failed.', 'sifency-addons' ) ) );
		}

		$template_id = isset( $_POST['template_id'] ) ? absint( $_POST['template_id'] ) : 0;
		$title       = isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
		$slug        = isset( $_POST['slug'] ) ? sanitize_title( wp_unslash( $_POST['slug'] ) ) : '';
		$post_status = isset( $_POST['post_status'] ) ? sanitize_key( wp_unslash( $_POST['post_status'] ) ) : '';

		$result = sifency_addons_update_template_inline_meta(
			$template_id,
			$title,
			$slug,
			$post_status,
			'themebuilder'
		);

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success(
			array_merge(
				array( 'message' => __( 'Template updated.', 'sifency-addons' ) ),
				$result
			)
		);
	}

	public function ajax_toggle_template_status() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security verification failed.' ) );
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( '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( array( 'message' => 'Invalid template ID.' ) );
		}
		update_post_meta( $sifency_addons_template_id, '_sifency_builder_active', $is_active ? '1' : '0' );
		wp_send_json_success( array( 'message' => 'Status updated.' ) );
	}

	public function ajax_save_display_conditions() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security verification failed.' ) );
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( '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( array( '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'] ?? array() );
		$exclude_count = count( $sanitized_conditions['exclude'] ?? array() );
		$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(
			array(
				'message' => 'Conditions saved.',
				'summary' => $summary,
			)
		);
	}

	public function ajax_get_display_conditions() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security verification failed.' ) );
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( '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( array( 'message' => 'Invalid template ID.' ) );
		}
		$conditions            = get_post_meta( $sifency_addons_template_id, '_themebuilder_conditions', true );
		$conditions            = is_array( $conditions ) ? $conditions : array(
			'include' => array(),
			'exclude' => array(),
		);
		$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 );
				}
			}
		};
		$terms                 = wp_get_post_terms( $sifency_addons_template_id, 'sifency_builder_type', array( 'fields' => 'slugs' ) );
		$template_type         = ! empty( $terms ) && ! is_wp_error( $terms ) ? $terms[0] : '';

		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'] ?? array() ); ?></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'] ?? array() ); ?></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(
			array(
				'html'          => ob_get_clean(),
				'template_type' => $template_type,
			)
		);
	}

	public function ajax_search_posts_terms() {
		if ( ! isset( $_POST['nonce'] ) && ! isset( $_GET['nonce'] ) ) {
			wp_send_json_error();
		}

		$nonce = isset( $_POST['nonce'] ) ? $_POST['nonce'] : $_GET['nonce'];
		if ( ! wp_verify_nonce( $nonce, 'sifency_admin_nonce' ) ) {
			wp_send_json_error();
		}
		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';
		$template_id = isset( $_GET['template_id'] ) ? intval( $_GET['template_id'] ) : 0;
		$used_items  = array();

		if ( $template_id ) {
			$terms = wp_get_post_terms( $template_id, 'sifency_builder_type', array( 'fields' => 'slugs' ) );
			$type  = ! empty( $terms ) && ! is_wp_error( $terms ) ? $terms[0] : '';

			if ( $type ) {
				$args            = array(
					'post_type'      => 'themebuilder',
					'post_status'    => 'publish',
					'posts_per_page' => -1,
					'post__not_in'   => array( $template_id ),
					'tax_query'      => array(
						array(
							'taxonomy' => 'sifency_builder_type',
							'field'    => 'slug',
							'terms'    => $type,
						),
					),
					'meta_query'     => array(
						array(
							'key'   => '_sifency_builder_active',
							'value' => '1',
						),
					),
				);
				$other_templates = get_posts( $args );
				foreach ( $other_templates as $t ) {
					$conds = get_post_meta( $t->ID, '_themebuilder_conditions', true );
					if ( ! empty( $conds['include'] ) ) {
						foreach ( $conds['include'] as $rule ) {
							if ( isset( $rule['subtype'] ) && isset( $rule['value'] ) ) {
								$used_items[ $rule['subtype'] . '|' . $rule['value'] ] = $t->post_title;
							}
						}
					}
				}
			}
		}

		$results = array();
		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(
					array(
						'post_type'      => $search_type,
						's'              => $search_term,
						'post_status'    => 'publish',
						'posts_per_page' => 20,
					)
				);
				if ( $query->have_posts() ) {
					foreach ( $query->posts as $post ) {
						$results[] = array(
							'id'   => $post->ID,
							'text' => $post->post_title,
						);
					}
				}
				break;
			case 'in_category':
			case 'category':
					$terms = get_terms(
						array(
							'taxonomy'   => 'category',
							'name__like' => $search_term,
							'number'     => 20,
							'hide_empty' => false,
						)
					);
				if ( ! is_wp_error( $terms ) ) {
					foreach ( $terms as $term ) {
						$results[] = array(
							'id'   => $term->term_id,
							'text' => $term->name,
						);
					}
				}
				break;
			case 'tag':
				$terms = get_terms(
					array(
						'taxonomy'   => 'post_tag',
						'name__like' => $search_term,
						'number'     => 20,
						'hide_empty' => false,
					)
				);
				if ( ! is_wp_error( $terms ) ) {
					foreach ( $terms as $term ) {
						$results[] = array(
							'id'   => $term->term_id,
							'text' => $term->name,
						);
					}
				}
				break;
			case 'author':
				$users = get_users(
					array(
						'search'         => '*' . $search_term . '*',
						'search_columns' => array( 'user_login', 'user_nicename', 'display_name' ),
						'number'         => 20,
					)
				);
				foreach ( $users as $user ) {
					$results[] = array(
						'id'   => $user->ID,
						'text' => $user->display_name,
					);
				}
				break;
		}

		$cpt_taxonomy_map = array(
			'product_in_category'   => 'product_cat',
			'product_in_tag'        => 'product_tag',
			'portfolio_in_category' => 'portfolio_category',
			'portfolio_in_tag'      => 'portfolio_tag',
			'service_in_category'   => 'service_category',
			'service_in_tag'        => 'service_tag',
			'team_in_category'      => 'team_category',
			'event_in_category'     => 'event_category',
			'doc_in_category'       => 'doc_category',
			'digital_in_category'   => 'digital_category',
		);

		if ( array_key_exists( $search_type, $cpt_taxonomy_map ) ) {
			$tax_name = $cpt_taxonomy_map[ $search_type ];
			$terms    = get_terms(
				array(
					'taxonomy'   => $tax_name,
					'name__like' => $search_term,
					'number'     => 20,
					'hide_empty' => false,
				)
			);

			if ( ! is_wp_error( $terms ) ) {
				foreach ( $terms as $term ) {
					$results[] = array(
						'id'   => $term->term_id,
						'text' => $term->name,
					);
				}
			}
		}

		foreach ( $results as &$res ) {
			$key = $search_type . '|' . $res['id'];
			if ( isset( $used_items[ $key ] ) ) {
				$res['disabled'] = true;
				$res['text']    .= ' ' . sprintf(
					/* translators: %s: template name that uses this condition */
					esc_html__( '(Used in %s)', 'sifency-addons' ),
					$used_items[ $key ]
				);
			}
		}

		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 array(
				'include' => array(),
				'exclude' => array(),
			);
		}
		$sanitized = array(
			'include' => array(),
			'exclude' => array(),
		);
		foreach ( array( '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 ][] = array(
						'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, array( '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 ); ?>">
			<span class="sifency-condition-drag dashicons dashicons-menu" title="<?php esc_attr_e( 'Drag to reorder', 'sifency-addons' ); ?>"></span>
			<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( (int) $value );
							break;

						case 'in_category':
						case 'category':
							$term = get_term( (int) $value, 'category' );
							if ( ! is_wp_error( $term ) && $term ) {
								$text = $term->name;
							}
							break;

						case 'tag':
						case 'in_tag':
							$term = get_term( (int) $value, 'post_tag' );
							if ( ! is_wp_error( $term ) && $term ) {
								$text = $term->name;
							}
							break;

						case 'product_in_category':
						case 'product_in_tag':
						case 'portfolio_in_category':
						case 'portfolio_in_tag':
						case 'service_in_category':
						case 'service_in_tag':
						case 'team_in_category':
						case 'event_in_category':
						case 'doc_in_category':
						case 'digital_in_category':
							$cpt_taxonomy_map = array(
								'product_in_category'   => 'product_cat',
								'product_in_tag'        => 'product_tag',
								'portfolio_in_category' => 'portfolio_category',
								'portfolio_in_tag'      => 'portfolio_tag',
								'service_in_category'   => 'service_category',
								'service_in_tag'        => 'service_tag',
								'team_in_category'      => 'team_category',
								'event_in_category'     => 'event_category',
								'doc_in_category'       => 'doc_category',
								'digital_in_category'   => 'digital_category',
							);

							if ( isset( $cpt_taxonomy_map[ $subtype ] ) ) {
								$term = get_term( (int) $value, $cpt_taxonomy_map[ $subtype ] );
								if ( ! is_wp_error( $term ) && $term ) {
									$text = $term->name;
								}
							}
							break;

						case 'author':
							$user = get_userdata( (int) $value );
							if ( $user ) {
								$text = $user->display_name;
							}
							break;
					}
					if ( ! empty( $text ) ) {
						echo '<option value="' . esc_attr( $value ) . '" selected="selected">' . esc_html( $text ) . '</option>';
					}
				}
				?>
			</select>
			<div class="sifency-condition-actions d-flex">
				<a href="#" class="sifency-duplicate-condition dashicons-before dashicons-admin-page sifency-admin-btn"></a>
				<a href="#" class="sifency-remove-condition dashicons-before dashicons-no-alt sifency-admin-btn"></a>
			</div>
		</div>
		<?php
	}
}