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

// -------------------------------------------------------------
// AJAX HANDLERS
// -------------------------------------------------------------
add_action( 'wp_ajax_sifency_set_cpt_thumbnail', 'sifency_ajax_set_cpt_thumbnail' );
function sifency_ajax_set_cpt_thumbnail() {
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_thumb_nonce' ) ) {
		wp_send_json_error( array( 'message' => 'Security verification failed.' ) );
	}

	$post_id   = intval( $_POST['post_id'] );
	$attach_id = intval( $_POST['attach_id'] );
	if ( $post_id && current_user_can( 'edit_post', $post_id ) ) {
		$attach_id > 0 ? set_post_thumbnail( $post_id, $attach_id ) : delete_post_thumbnail( $post_id );
		wp_send_json_success();
	}
	wp_send_json_error();
}

add_action( 'wp_ajax_sifency_update_cpt_terms', 'sifency_ajax_update_cpt_terms' );
function sifency_ajax_update_cpt_terms() {
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_term_nonce' ) ) {
		wp_send_json_error( array( 'message' => 'Security verification failed.' ) );
	}

	$post_id  = intval( $_POST['post_id'] );
	$taxonomy = sanitize_key( $_POST['taxonomy'] );
	$terms    = isset( $_POST['terms'] ) ? $_POST['terms'] : array();

	if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
		wp_send_json_error();
	}

	$final_term_ids = array();
	if ( is_array( $terms ) ) {
		foreach ( $terms as $term ) {
			if ( is_numeric( $term ) ) {
				$final_term_ids[] = intval( $term );
			} else {
				$term_name = sanitize_text_field( $term );
				$exists    = term_exists( $term_name, $taxonomy );
				if ( $exists ) {
					$final_term_ids[] = (int) $exists['term_id'];
				} else {
					$new_term = wp_insert_term( $term_name, $taxonomy );
					if ( ! is_wp_error( $new_term ) ) {
						$final_term_ids[] = (int) $new_term['term_id'];
					}
				}
			}
		}
	}
	wp_set_object_terms( $post_id, $final_term_ids, $taxonomy );
	wp_send_json_success();
}

add_action( 'wp_ajax_sifency_get_post_details_for_modal', 'sifency_ajax_get_modal_data' );
function sifency_ajax_get_modal_data() {
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_meta_nonce' ) ) {
		wp_send_json_error( array( 'message' => 'Security verification failed.' ) );
	}

	$post_id = intval( $_POST['post_id'] );
	if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
		wp_send_json_error( array( 'message' => 'Invalid post or insufficient permissions.' ) );
	}

	$post      = get_post( $post_id );
	$post_type = $post->post_type;
	$all_meta  = get_post_meta( $post_id );

	$post_type_metaboxes = sifency_get_metaboxes_for_post_type( $post_type );
	$defined_fields      = array();

	ob_start();

	if ( ! empty( $post_type_metaboxes ) ) {
		foreach ( $post_type_metaboxes as $metabox_id => $metabox ) {
			if ( ! empty( $metabox['fields'] ) && is_array( $metabox['fields'] ) ) {
				echo '<div class="sifency-meta-section">';

				foreach ( $metabox['fields'] as $field ) {
					$field_id = isset( $field['id'] ) ? $field['id'] : '';
					if ( ! $field_id ) {
						continue;
					}

					$field_type = isset( $field['type'] ) ? $field['type'] : 'text';

					if ( in_array( $field_type, array( 'repeater', 'group', 'gallery', 'relationship', 'clone' ) ) ) {
						continue;
					}

					$field_title = isset( $field['title'] ) ? $field['title'] : $field_id;
					$val         = get_post_meta( $post_id, $field_id, true );

					sifency_render_meta_field(
						$field_id,
						$val,
						array(
							'type'    => $field_type,
							'label'   => $field_title,
							'options' => isset( $field['options'] ) ? $field['options'] : array(),
							'desc'    => isset( $field['desc'] ) ? $field['desc'] : '',
						)
					);

					$defined_fields[ $field_id ] = true;
					if ( isset( $all_meta[ $field_id ] ) ) {
						unset( $all_meta[ $field_id ] );
					}
				}
				echo '</div>';
			}
		}
	}

	if ( ! empty( $all_meta ) ) {
		foreach ( $all_meta as $key => $val_arr ) {
			if ( substr( $key, 0, 1 ) === '_' ) {
				continue;
			}
			if ( isset( $defined_fields[ $key ] ) ) {
				continue;
			}

			$val           = is_array( $val_arr ) ? ( $val_arr[0] ?? '' ) : $val_arr;
			$is_serialized = is_serialized( $val );

			if ( $is_serialized ) {
				continue;
			}

			if ( ( strpos( $key, 'image' ) !== false || strpos( $key, 'file' ) !== false || strpos( $key, 'photo' ) !== false ) && is_numeric( $val ) ) {
				sifency_render_meta_field(
					$key,
					$val,
					array(
						'type'  => 'image',
						'label' => $key,
					)
				);
			} else {
				sifency_render_meta_field(
					$key,
					$val,
					array(
						'type'  => 'text',
						'label' => $key,
					)
				);
			}
		}
	}

	$html = ob_get_clean();
	wp_send_json_success(
		array(
			'title'   => $post->post_title,
			'content' => $post->post_content,
			'excerpt' => $post->post_excerpt,
			'html'    => $html,
		)
	);
}

/**
 * Get metabox definitions for a specific post type
 *
 * @param string $post_type The post type to get metaboxes for
 * @return array Array of metabox definitions
 */
function sifency_get_metaboxes_for_post_type( $post_type ) {
	$metabox_file = SIFENCY_TB_PATH . 'post-type/' . $post_type . '/' . $post_type . '-meta.php';

	if ( ! file_exists( $metabox_file ) ) {
		$alternate_names = array(
			SIFENCY_TB_PATH . 'post-type/' . $post_type . '/class-meta.php',
			SIFENCY_TB_PATH . 'post-type/' . $post_type . '/member-meta.php',
			SIFENCY_TB_PATH . 'post-type/' . $post_type . '/product-meta.php',
			SIFENCY_TB_PATH . 'post-type/' . $post_type . '/restaurant-menu-meta.php',
		);

		foreach ( $alternate_names as $alt_file ) {
			if ( file_exists( $alt_file ) ) {
				$metabox_file = $alt_file;
				break;
			}
		}
	}

	if ( ! file_exists( $metabox_file ) ) {
		return array();
	}
	$definitions = include $metabox_file;

	return is_array( $definitions ) ? $definitions : array();
}

function sifency_render_meta_field( $key, $val, $config ) {
	$type  = isset( $config['type'] ) ? $config['type'] : 'text';
	$label = isset( $config['label'] ) ? $config['label'] : $key;
	$desc  = isset( $config['desc'] ) ? $config['desc'] : '';

	if ( in_array( $type, array( 'repeater', 'group', 'gallery', 'relationship', 'clone' ) ) ) {
		return;
	}

	if ( is_array( $val ) && ! empty( $val ) ) {
		return;
	}

	echo '<div class="sifency-meta-row">';
	echo '<div class="sifency-meta-label">';
	echo '<label>' . esc_html( $label ) . '</label>';
	if ( $desc ) {
		echo '<p class="description">' . wp_kses_post( $desc ) . '</p>';
	}
	echo '</div>';
	echo '<div class="sifency-meta-input">';

	switch ( $type ) {
		case 'select':
			echo '<select name="meta[' . esc_attr( $key ) . ']" class="widefat sifency-admin-btn">';
			if ( isset( $config['options'] ) && is_array( $config['options'] ) ) {
				foreach ( $config['options'] as $opt_val => $opt_label ) {
					$selected = ( $val == $opt_val ) ? 'selected' : '';
					echo '<option value="' . esc_attr( $opt_val ) . '" ' . selected( $current_value, $opt_val, false ) . '>' . esc_html( $opt_label ) . '</option>';
				}
			}
			echo '</select>';
			break;

		case 'media':
		case 'image':
			$img_url = $val ? wp_get_attachment_image_url( $val, 'thumbnail' ) : '';
			$style   = $img_url ? '' : 'display:none;';
			echo '<div class="sifency-media-wrap">';
			echo '<input type="hidden" name="meta[' . esc_attr( $key ) . ']" value="' . esc_attr( $val ) . '" class="sifency-img-input">';
			echo '<img src="' . esc_url( $img_url ) . '" class="sifency-media-preview" style="' . esc_attr( $style ) . '; max-width: 150px; height: auto;">';
			echo '<button type="button" class="button sifency-upload-btn sifency-admin-btn">Upload/Select</button>';
			echo '<button type="button" class="button sifency-remove-img sifency-admin-btn" style="color:#b32d2e;">Remove</button>';
			echo '</div>';
			break;

		case 'textarea':
		case 'wp_editor':
			echo '<textarea name="meta[' . esc_attr( $key ) . ']" class="widefat sifency-admin-btn" rows="5">' . esc_textarea( $val ) . '</textarea>';
			break;

		case 'upload':
		case 'file':
			$file_url  = $val ? wp_get_attachment_url( $val ) : '';
			$file_name = $val ? basename( wp_get_attachment_url( $val ) ) : 'No file';
			echo '<div class="sifency-file-wrap">';
			echo '<input type="hidden" name="meta[' . esc_attr( $key ) . ']" value="' . esc_attr( $val ) . '" class="sifency-file-input">';
			echo '<div class="sifency-file-display">📄 ' . esc_html( $file_name ) . '</div>';
			echo '<button type="button" class="button sifency-upload-btn sifency-admin-btn">Upload/Select</button>';
			echo '<button type="button" class="button sifency-remove-img sifency-admin-btn" style="color:#b32d2e;">Remove</button>';
			echo '</div>';
			break;

		case 'checkbox':
		case 'checkboxes':
			echo '<div class="sifency-checkbox-group">';
			if ( isset( $config['options'] ) && is_array( $config['options'] ) ) {
				foreach ( $config['options'] as $opt_val => $opt_label ) {
					$checked = ( is_array( $val ) && in_array( $opt_val, $val ) ) || ( $val == $opt_val ) ? 'checked' : '';
					echo '<label class="sifency-checkbox-label">';
					echo '<input type="checkbox" name="meta[' . esc_attr( $key ) . '][]" value="' . esc_attr( $opt_val ) . '" ' . checked( $checked, true, false ) . '>';
					echo ' ' . esc_html( $opt_label );
					echo '</label>';
				}
			}
			echo '</div>';
			break;

		case 'radio':
		case 'radio_button':
			echo '<div class="sifency-radio-group">';
			if ( isset( $config['options'] ) && is_array( $config['options'] ) ) {
				foreach ( $config['options'] as $opt_val => $opt_label ) {
					$checked = ( $val == $opt_val ) ? 'checked' : '';
					echo '<label class="sifency-radio-label">';
					echo '<input type="radio" name="meta[' . esc_attr( $key ) . ']" value="' . esc_attr( $opt_val ) . '" ' . checked( $checked, true, false ) . '>';
					echo ' ' . esc_html( $opt_label );
					echo '</label>';
				}
			}
			echo '</div>';
			break;

		case 'number':
			echo '<input type="number" name="meta[' . esc_attr( $key ) . ']" value="' . esc_attr( $val ) . '" class="widefat sifency-admin-btn">';
			break;

		case 'date':
			echo '<input type="date" name="meta[' . esc_attr( $key ) . ']" value="' . esc_attr( $val ) . '" class="widefat sifency-admin-btn">';
			break;

		case 'time':
			echo '<input type="time" name="meta[' . esc_attr( $key ) . ']" value="' . esc_attr( $val ) . '" class="widefat sifency-admin-btn">';
			break;

		case 'url':
		case 'link':
			echo '<input type="url" name="meta[' . esc_attr( $key ) . ']" value="' . esc_attr( $val ) . '" class="widefat sifency-admin-btn" placeholder="https://example.com">';
			break;

		case 'email':
			echo '<input type="email" name="meta[' . esc_attr( $key ) . ']" value="' . esc_attr( $val ) . '" class="widefat sifency-admin-btn">';
			break;

		case 'color':
			echo '<input type="color" name="meta[' . esc_attr( $key ) . ']" value="' . esc_attr( $val ) . '" class="sifency-color-picker">';
			break;

		default: // text
			echo '<input type="text" name="meta[' . esc_attr( $key ) . ']" value="' . esc_attr( $val ) . '" class="widefat sifency-admin-btn">';
			break;
	}
	echo '</div>';
	echo '</div>';
}

add_action( 'wp_ajax_sifency_save_post_details_from_modal', 'sifency_ajax_save_modal_data' );
function sifency_ajax_save_modal_data() {
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_meta_nonce' ) ) {
		wp_send_json_error( array( 'message' => 'Security verification failed.' ) );
	}

	$post_id = intval( $_POST['post_id'] );
	if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
		wp_send_json_error( array( 'message' => 'Invalid post or insufficient permissions.' ) );
	}

	$update_post_args = array( 'ID' => $post_id );
	if ( isset( $_POST['post_title'] ) ) {
		$update_post_args['post_title'] = sanitize_text_field( $_POST['post_title'] );
	}
	if ( isset( $_POST['post_content'] ) ) {
		$update_post_args['post_content'] = wp_kses_post( wp_unslash( $_POST['post_content'] ) );
	}
	if ( isset( $_POST['post_excerpt'] ) ) {
		$update_post_args['post_excerpt'] = sanitize_textarea_field( $_POST['post_excerpt'] );
	}
	if ( count( $update_post_args ) > 1 ) {
		wp_update_post( $update_post_args );
	}

	if ( isset( $_POST['meta'] ) && is_array( $_POST['meta'] ) ) {
		$post                = get_post( $post_id );
		$post_type           = $post ? $post->post_type : '';
		$post_type_metaboxes = sifency_get_metaboxes_for_post_type( $post_type );

		$field_configs = array();
		if ( ! empty( $post_type_metaboxes ) ) {
			foreach ( $post_type_metaboxes as $metabox ) {
				if ( ! empty( $metabox['fields'] ) && is_array( $metabox['fields'] ) ) {
					foreach ( $metabox['fields'] as $field ) {
						if ( isset( $field['id'] ) ) {
							$field_configs[ $field['id'] ] = $field;
						}
					}
				}
			}
		}

		foreach ( $_POST['meta'] as $key => $val ) {
			$sanitized_key = sanitize_key( $key );

			if ( isset( $field_configs[ $sanitized_key ] ) ) {
				$sanitized_val = sifency_ajax_sanitize_field( $val, $field_configs[ $sanitized_key ] );
			} elseif ( is_array( $val ) ) {
					$sanitized_val = array_map( 'sanitize_text_field', $val );
			} else {
				$sanitized_val = sanitize_text_field( $val );
			}

			update_post_meta( $post_id, $sanitized_key, $sanitized_val );
		}
	}
	wp_send_json_success();
}

/**
 * Sanitizes metadata fields saved via the quick-edit meta modal, matching
 * the behavior of Sifency_Addons_Master_Metabox::sanitize_field.
 */
function sifency_ajax_sanitize_field( $data, $field_config ) {
	if ( ! is_array( $field_config ) ) {
		return is_array( $data ) ? array_map( 'sanitize_text_field', $data ) : sanitize_text_field( $data );
	}

	if ( isset( $field_config['type'] ) && 'repeater' === $field_config['type'] ) {
		$sanitized_data = array();
		if ( is_array( $data ) ) {
			foreach ( $data as $index => $row_data ) {
				$sanitized_row = array();
				if ( isset( $field_config['fields'] ) && is_array( $field_config['fields'] ) ) {
					foreach ( $field_config['fields'] as $sub_field ) {
						if ( isset( $row_data[ $sub_field['id'] ] ) ) {
							$sanitized_row[ $sub_field['id'] ] = sifency_ajax_sanitize_field( $row_data[ $sub_field['id'] ], $sub_field );
						}
					}
				}
				$sanitized_data[] = $sanitized_row;
			}
		}
		return $sanitized_data;
	}

	if ( isset( $field_config['sanitize'] ) ) {
		switch ( $field_config['sanitize'] ) {
			case 'wp_kses_post':
				return wp_kses_post( $data );
			case 'allow_iframe':
				$allowed_html = array(
					'iframe' => array(
						'src'             => true,
						'width'           => true,
						'height'          => true,
						'style'           => true,
						'frameborder'     => true,
						'allowfullscreen' => true,
						'loading'         => true,
						'referrerpolicy'  => true,
					),
				);
				return wp_kses( $data, $allowed_html );
			case false:
			case 'none':
				return $data;
		}
	}

	$type = isset( $field_config['type'] ) ? $field_config['type'] : 'text';
	switch ( $type ) {
		case 'textarea':
			return sanitize_textarea_field( $data );
		case 'checkbox':
			return is_array( $data ) ? array_map( 'sanitize_text_field', $data ) : array();
		case 'slider':
			return floatval( $data );
		case 'upload':
		case 'media':
			return absint( $data );
		case 'email':
			return sanitize_email( $data );
		case 'url':
			return esc_url_raw( $data );
		case 'number':
			return intval( $data );
		case 'wp_editor':
			return wp_kses_post( $data );
		case 'color':
			return sanitize_hex_color( $data );

		case 'select':
		case 'button_set':
		case 'text':
		case 'date':
		case 'time':
		case 'datetime':
		default:
			return sanitize_text_field( $data );
	}
}

add_action( 'wp_ajax_sifency_update_cpt_post_details', 'sifency_ajax_update_cpt_post_details' );

/**
 * AJAX: update CPT card title, slug, and publish status from inline tooltip.
 */
function sifency_ajax_update_cpt_post_details() {
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'sifency_meta_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,
		null
	);

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

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