<?php
namespace Kanews\Builder;
use CSF;

class Terms {

	private static $instance;

	/**
	 * Get singleton instance
	 * 
	 * @return self
	 */
	public static function getInstance() {
		if ( null === static::$instance ) {
			static::$instance = new static();
		}
		return static::$instance;
	}

	/**
	 * Constructor
	 */
	public function __construct() {

		add_action( 'category_add_form_fields', [ $this, 'create_category_fields' ], 10, 2 );
		add_action( 'created_category', [ $this, 'save_category_fields' ], 10, 2 );
		add_action( 'category_edit_form_fields', [ $this, 'edit_category_fields' ], 10, 2 );
		add_action( 'edited_category', [ $this, 'updated_category_fields' ], 10, 2 );

		add_action( 'post_tag_edit_form_fields', [ $this, 'edit_tag_fields' ], 10, 2 );
		add_action( 'edited_post_tag', [ $this, 'updated_tag_fields' ], 10, 2 );
		add_action( 'post_tag_add_form_fields', [ $this, 'create_tag_fields' ], 10, 2 );
		add_action( 'created_post_tag', [ $this, 'save_tag_fields' ], 10, 2 );

		add_action( 'admin_enqueue_scripts', [ $this, 'admin_add_scripts' ] );
		add_action( 'admin_footer', [ $this, 'admin_print_scripts' ] );

		$this->category_options();
		$this->nav_options();
	}

	/**
	 * Nav Options
	 * 
	 * @return void
	 */
	private function nav_options() {
		if ( ! class_exists( 'CSF' ) ) {
			return;
		}

		$prefix = '_kan_menu_options';

		CSF::createNavMenuOptions( $prefix, [
			'data_type' => 'serialize',
		] );

		CSF::createSection( $prefix, [
			'fields' => [
				[
					'id' => 'icon',
					'type' => 'icon',
					'title' => esc_html__( 'İkon', 'kanews' ),
				],
				[
					'id' => 'image',
					'type' => 'media',
					'title' => esc_html__( 'Görsel İkon', 'kanews' ),
					'desc' => esc_html__( 'svg formatında ikon', 'kanews' ),
				],
				[
					'id' => 'badge',
					'type' => 'text',
					'title' => esc_html__( 'Etiket', 'kanews' ),
				],
				[
					'id' => 'badge_color',
					'type' => 'color',
					'title' => sprintf( esc_html__( '%s %s', 'kanews' ), esc_html__( 'Etiket', 'kanews' ), esc_html__( 'Renk', 'kanews' ) ),
				],
			]
		] );
	}

	/**
	 * Category Options
	 *
	 * @since 1.0.0
	 * @return void
	 */
	private function category_options() {
		if ( ! class_exists( 'CSF' ) ) {
			return;
		}

		$prefix = 'kanews_taxonomy_options';

		CSF::createTaxonomyOptions( $prefix, [
			'taxonomy' => 'category',
			'data_type' => 'unserialize',
		] );

		CSF::createSection( $prefix, [
			'title' => esc_html__( 'Kanews Ayarları', 'kanews' ),
			'fields' => [

				[
					'id' => 'kanews_logo',
					'type' => 'fieldset',
					'title' => esc_html__( 'Kategori Logosu', 'kanews' ),
					'fields' => [
						[
							'id' => 'type',
							'type' => 'radio',
							'inline' => false,
							'options' => [
								'default' => esc_html__( 'Varsayılan', 'kanews' ),
								'img' => esc_html__( 'Görsel', 'kanews' ),
							],
						],
						[
							'type' => 'media',
							'id' => 'logo-img',
							'button_title' => esc_html__( 'Görsel', 'kanews' ),
							'dependency' => [ 'type', '==', 'img' ],
						],
					],
					'default' => [
						'type' => 'default',
					],
				],
				[
					'id' => 'kanews_logo_mobile',
					'title' => esc_html__( 'Retina Logo', 'kanews' ),
					'desc' => esc_html__( 'Ana logodan 2 kat daha büyük olmalıdır.', 'kanews' ),
					'type' => 'media'
				],
				[
					'id' => 'kanews_logo_dark',
					'title' => esc_html__( 'Koyu Mod Logo', 'kanews' ),
					'desc' => esc_html__( 'Koyu mod aktif edildiğinde gözükecek olan logo.', 'kanews' ),
					'type' => 'media'
				],
				[
					'id' => 'kanews_menu',
					'type' => 'select',
					'options' => 'menus',
					'chosen' => true,
					'ajax' => true,
					'placeholder' => esc_html__( 'Varsayılan', 'kanews' ),
					'title' => esc_html__( 'Özel Menü', 'kanews' ),
				],
				[
					'id' => 'recent-post-section-title',
					'type' => 'text',
					'title' => esc_html__( 'Son Yazılar Başlığı', 'kanews' ),
				],
				[
					'id' => 'category-recent-posts-style',
					'type' => 'select',
					'default' => 'style1',
					'options' => [
						'' => esc_html__( 'Varsayılan', 'kanews' ),
						'disable' => esc_html__( 'Gösterme', 'kanews' ),
						'1' => sprintf( esc_html__( '%s #%s', 'kanews' ), esc_html__( 'Görünüm', 'kanews' ), '1' ),
						'2' => sprintf( esc_html__( '%s #%s', 'kanews' ), esc_html__( 'Görünüm', 'kanews' ), '2' ),
						'3' => sprintf( esc_html__( '%s #%s', 'kanews' ), esc_html__( 'Görünüm', 'kanews' ), '3' ),
						'4' => sprintf( esc_html__( '%s #%s', 'kanews' ), esc_html__( 'Görünüm', 'kanews' ), '4' ),
						'5' => sprintf( esc_html__( '%s #%s', 'kanews' ), esc_html__( 'Görünüm', 'kanews' ), '5' ),
						'6' => sprintf( esc_html__( '%s #%s', 'kanews' ), esc_html__( 'Görünüm', 'kanews' ), '6' ),
					],
					'title' => esc_html__( 'Son Yazıların Görünümü', 'kanews' ),
				],
				[
					'id' => 'category-posts-per-page',
					'type' => 'number',
					'min' => 0,
					'title' => esc_html__( 'Son Yazı Sayısı', 'kanews' ),
				],
				[
					'id' => 'private-category',
					'type' => 'switcher',
					'text_on' => esc_html__( 'Yes', 'kanews' ),
					'text_off' => esc_html__( 'No', 'kanews' ),
					'title' => esc_html__( 'Ücretli İçerik Kategorisi', 'kanews' ),
				],
				[
					'id' => 'hidden-category-desc',
					'type' => 'switcher',
					'text_on' => esc_html__( 'Yes', 'kanews' ),
					'text_off' => esc_html__( 'No', 'kanews' ),
					'title' => esc_html__( 'Açıklamayı Gizle', 'kanews' ),
				],
				[
					'id' => 'category-desc-on-footer',
					'type' => 'switcher',
					'text_on' => esc_html__( 'Yes', 'kanews' ),
					'text_off' => esc_html__( 'No', 'kanews' ),
					'title' => esc_html__( 'Açıklamayı Sayfanın Altına Taşı', 'kanews' ),
				],
				[
					'id' => 'ilan-category',
					'type' => 'switcher',
					'text_on' => esc_html__( 'Yes', 'kanews' ),
					'text_off' => esc_html__( 'No', 'kanews' ),
					'title' => esc_html__( 'Resmi İlan Kategorisidir', 'kanews' ),
				],
			]
		] );
	}

	/**
	 * Enqueue Scripts
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function admin_add_scripts() {
		wp_enqueue_media();
		wp_enqueue_script( 'wp-color-picker' );
		wp_enqueue_style( 'wp-color-picker' );
	}

	/**
	 * Print Script
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function admin_print_scripts() {
		$taxonomy = isset( $_GET['taxonomy'] ) ? sanitize_text_field( $_GET['taxonomy'] ) : '';
		
		?>
		<script>
			jQuery( document ).ready( function( $ ) {
				$( '.colorpicker' ).wpColorPicker();
			} );
		</script>
		<?php if ( in_array( $taxonomy, [ 'category', 'post_tag' ], true ) ) : ?>
		<script>
			jQuery( document ).ready( function( $ ) {
				var imagePrefix = '<?php echo esc_js( $taxonomy === 'category' ? 'category' : 'tag' ); ?>';
				var imageIdField = '#' + imagePrefix + '-image-id';
				var imageWrapper = '#' + imagePrefix + '-image-wrapper';

				function ct_media_upload( button_class ) {
					var _custom_media = true,
						_orig_send_attachment = wp.media.editor.send.attachment;
					
					$( 'body' ).on( 'click', button_class, function( e ) {
						var button_id = '#' + $( this ).attr( 'id' );
						var send_attachment_bkp = wp.media.editor.send.attachment;
						var button = $( button_id );
						_custom_media = true;
						
						wp.media.editor.send.attachment = function( props, attachment ) {
							if ( _custom_media ) {
								$( imageIdField ).val( attachment.id );
								$( imageWrapper ).html( '<img class="custom_media_image" src="" style="margin:0;padding:0;max-height:100px;float:none;" />' );
								$( imageWrapper + ' .custom_media_image' ).attr( 'src', attachment.url ).css( 'display', 'block' );
							} else {
								return _orig_send_attachment.apply( button_id, [ props, attachment ] );
							}
						};
						
						wp.media.editor.open( button );
						return false;
					} );
				}

				ct_media_upload( '.ct_tax_media_button.button' );
				
				$( 'body' ).on( 'click', '.ct_tax_media_remove', function() {
					$( imageIdField ).val( '' );
					$( imageWrapper ).html( '<img class="custom_media_image" src="" style="margin:0;padding:0;max-height:100px;float:none;" />' );
				} );

				$( document ).ajaxComplete( function( event, xhr, settings ) {
					var queryStringArr = settings.data.split( '&' );
					if ( $.inArray( 'action=add-tag', queryStringArr ) !== -1 ) {
						var xml = xhr.responseXML;
						var response = $( xml ).find( 'term_id' ).text();
						if ( response !== '' ) {
							$( imageWrapper ).html( '' );
						}
					}
				} );
			} );
		</script>
		<?php endif; ?>
		<?php
	}

	/**
	 * Add a form field in the new category page
	 *
	 * @since 1.0.0
	 * @param string $taxonomy Taxonomy name
	 * @return void
	 */
	public function create_category_fields( $taxonomy ) {
		$this->render_image_field( 'category', 'category-image-id', 'category-image-wrapper' );
		$this->render_color_field( '_category_color', 'term-colorpicker', esc_html__( 'Kategori Rengi', 'kanews' ) );
	}

	/**
	 * Render image upload field
	 * 
	 * @param string $prefix Field prefix (category or tag)
	 * @param string $field_id Field ID
	 * @param string $wrapper_id Wrapper ID
	 * @return void
	 */
	private function render_image_field( $prefix, $field_id, $wrapper_id ) {
		?>
		<div class="form-field term-group">
			<label for="<?php echo esc_attr( $field_id ); ?>"><?php esc_html_e( 'Görsel', 'kanews' ); ?></label>
			<input type="hidden" id="<?php echo esc_attr( $field_id ); ?>" name="<?php echo esc_attr( $field_id ); ?>" class="custom_media_url" value="">
			<div id="<?php echo esc_attr( $wrapper_id ); ?>"></div>
			<p>
				<input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="<?php esc_attr_e( 'Görsel Ekle', 'kanews' ); ?>" />
				<input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="<?php esc_attr_e( 'Görseli Kaldır', 'kanews' ); ?>" />
			</p>
		</div>
		<?php
	}

	/**
	 * Render color picker field
	 * 
	 * @param string $field_name Field name
	 * @param string $field_id Field ID
	 * @param string $label Field label
	 * @return void
	 */
	private function render_color_field( $field_name, $field_id, $label ) {
		?>
		<div class="form-field term-group">
			<label for="<?php echo esc_attr( $field_id ); ?>"><?php echo esc_html( $label ); ?></label>
			<input name="<?php echo esc_attr( $field_name ); ?>" class="colorpicker" id="<?php echo esc_attr( $field_id ); ?>" />
		</div>
		<?php
	}

	/**
	 * Add a form field in the new category edit page
	 *
	 * @since 1.0.0
	 * @param \WP_Term $term Term object
	 * @param string $taxonomy Taxonomy name
	 * @return void
	 */
	public function edit_category_fields( $term, $taxonomy ) {
		$image_id = get_term_meta( $term->term_id, 'category-image-id', true );
		$color = get_term_meta( $term->term_id, '_category_color', true );
		$color = ! empty( $color ) ? '#' . esc_attr( $color ) : '';
		?>
		<tr class="form-field term-group-wrap">
			<th scope="row">
				<label for="category-image-id"><?php esc_html_e( 'Görsel', 'kanews' ); ?></label>
			</th>
			<td>
				<input type="hidden" id="category-image-id" name="category-image-id" value="<?php echo esc_attr( $image_id ); ?>">
				<div id="category-image-wrapper">
					<?php if ( $image_id ) : ?>
						<?php echo wp_get_attachment_image( $image_id, 'kanews-post-6' ); ?>
					<?php endif; ?>
				</div>
				<p>
					<input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="<?php esc_attr_e( 'Görsel Ekle', 'kanews' ); ?>" />
					<input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="<?php esc_attr_e( 'Görseli Kaldır', 'kanews' ); ?>" />
				</p>
			</td>
		</tr>
		<tr class="form-field term-colorpicker-wrap">
			<th scope="row"><label for="term-colorpicker"><?php esc_html_e( 'Renk', 'kanews' ); ?></label></th>
			<td>
				<input name="_category_color" value="<?php echo esc_attr( $color ); ?>" class="colorpicker" id="term-colorpicker" />
			</td>
		</tr>
		<?php
	}

	/**
	 * Save the form field
	 *
	 * @since 1.0.0
	 * @param int $term_id Term ID
	 * @param int $tt_id Term taxonomy ID
	 * @return void
	 */
	public function save_category_fields( $term_id, $tt_id ) {
		$this->save_term_image( $term_id, 'category-image-id' );
		$this->save_term_color( $term_id, '_category_color' );
	}

	/**
	 * Update the form field value
	 *
	 * @since 1.0.0
	 * @param int $term_id Term ID
	 * @param int $tt_id Term taxonomy ID
	 * @return void
	 */
	public function updated_category_fields( $term_id, $tt_id ) {
		$image_id = isset( $_POST['category-image-id'] ) ? absint( $_POST['category-image-id'] ) : 0;
		update_term_meta( $term_id, 'category-image-id', $image_id );
		$this->save_term_color( $term_id, '_category_color' );
	}

	/**
	 * Save term image
	 * 
	 * @param int $term_id Term ID
	 * @param string $field_name Field name
	 * @return void
	 */
	private function save_term_image( $term_id, $field_name ) {
		if ( isset( $_POST[ $field_name ] ) && '' !== $_POST[ $field_name ] ) {
			$image = absint( $_POST[ $field_name ] );
			add_term_meta( $term_id, $field_name, $image, true );
		}
	}

	/**
	 * Save term color
	 * 
	 * @param int $term_id Term ID
	 * @param string $field_name Field name
	 * @return void
	 */
	private function save_term_color( $term_id, $field_name ) {
		if ( isset( $_POST[ $field_name ] ) && ! empty( $_POST[ $field_name ] ) ) {
			$color = sanitize_hex_color_no_hash( $_POST[ $field_name ] );
			update_term_meta( $term_id, $field_name, $color );
		} else {
			delete_term_meta( $term_id, $field_name );
		}
	}
	/**
	 * Add a form field in the new tag page
	 *
	 * @since 1.0.0
	 * @param string $taxonomy Taxonomy name
	 * @return void
	 */
	public function create_tag_fields( $taxonomy ) {
		$this->render_image_field( 'tag', 'tag-image-id', 'tag-image-wrapper' );
		$this->render_color_field( '_tag_color', 'term-colorpicker', esc_html__( 'Renk', 'kanews' ) );
	}

	/**
	 * Add a form field in the new tag edit page
	 *
	 * @since 1.0.0
	 * @param \WP_Term $term Term object
	 * @param string $taxonomy Taxonomy name
	 * @return void
	 */
	public function edit_tag_fields( $term, $taxonomy ) {
		$image_id = get_term_meta( $term->term_id, 'tag-image-id', true );
		$color = get_term_meta( $term->term_id, '_tag_color', true );
		$color = ! empty( $color ) ? '#' . esc_attr( $color ) : '';
		?>
		<tr class="form-field term-colorpicker-wrap">
			<th scope="row"><label for="term-colorpicker"><?php esc_html_e( 'Renk', 'kanews' ); ?></label></th>
			<td>
				<input name="_tag_color" value="<?php echo esc_attr( $color ); ?>" class="colorpicker" id="term-colorpicker" />
			</td>
		</tr>
		<tr class="form-field term-group-wrap">
			<th scope="row">
				<label for="tag-image-id"><?php esc_html_e( 'Görsel', 'kanews' ); ?></label>
			</th>
			<td>
				<input type="hidden" id="tag-image-id" name="tag-image-id" value="<?php echo esc_attr( $image_id ); ?>">
				<div id="tag-image-wrapper">
					<?php if ( $image_id ) : ?>
						<?php echo wp_get_attachment_image( $image_id, 'kanews-post-6' ); ?>
					<?php endif; ?>
				</div>
				<p>
					<input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="<?php esc_attr_e( 'Görsel Ekle', 'kanews' ); ?>" />
					<input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="<?php esc_attr_e( 'Görseli Kaldır', 'kanews' ); ?>" />
				</p>
			</td>
		</tr>
		<?php
	}

	/**
	 * Save the form field
	 *
	 * @since 1.0.0
	 * @param int $term_id Term ID
	 * @param int $tt_id Term taxonomy ID
	 * @return void
	 */
	public function save_tag_fields( $term_id, $tt_id ) {
		$this->save_term_image( $term_id, 'tag-image-id' );
		$this->save_term_color( $term_id, '_tag_color' );
	}

	/**
	 * Update the form field value
	 *
	 * @since 1.0.0
	 * @param int $term_id Term ID
	 * @param int $tt_id Term taxonomy ID
	 * @return void
	 */
	public function updated_tag_fields( $term_id, $tt_id ) {
		$image_id = isset( $_POST['tag-image-id'] ) ? absint( $_POST['tag-image-id'] ) : 0;
		update_term_meta( $term_id, 'tag-image-id', $image_id );
		$this->save_term_color( $term_id, '_tag_color' );
	}

}
/**
 * Get menus for CSF options
 * 
 * @return string Exported menu array
 */
function kanews_get_menus() {
	$menus = get_terms( [
		'taxonomy' => 'nav_menu',
		'hide_empty' => true,
	] );

	if ( is_wp_error( $menus ) || empty( $menus ) ) {
		return var_export( [], true );
	}

	$menu_array = [];
	foreach ( $menus as $menu ) {
		$menu_array[ $menu->slug ] = $menu->name;
	}

	return var_export( $menu_array, true );
}