<?php

/**
 *
 * @package ag-theme-builder
 */

use Ag_Theme_Builder\Lib\Ag_Target_Rules_Fields;

defined( 'ABSPATH' ) || exit;

/**
 * Ag_Theme_Builder_Admin setup
 *
 * @since 1.0.0
 */
class Ag_Theme_Builder_Admin {

	/**
	 * Instance of Ag_Theme_Builder_Admin
	 *
	 * @var Ag_Theme_Builder_Admin
	 */
	private static $_instance = null;

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

		add_action( 'init', array( $this, 'ag_theme_builder_post_type' ) );
		add_action( 'init', array( $this, 'ag_theme_builder_frontend_settings' ) );
		add_action( 'parse_query', array( $this, 'ag_theme_parse_query' ) );
		// add_action( 'add_meta_boxes', array( $this, 'ag_theme_builder_register_metabox' ) );
		add_action( 'save_post_ag-themer', [ $this, 'ag_theme_builder_save_meta' ] );
		add_action('admin_init', [ $this, 'remove_revision_metabox' ]);
		add_action( 'template_redirect', array( $this, 'block_template_frontend' ) );
		add_action( 'admin_menu', array( $this, 'register_settings_submenus' ), 99 );
		add_action('edit_form_after_title', [ $this, 'render_ui' ]);
		add_action('admin_init', [$this, 'load_ajax_handlers']);
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'prk_enqueue_admin_builder_script' ) );
		add_action('admin_head', [ $this, 'hide_default_metaboxes' ]);
		add_filter( 'manage_ag-themer_posts_columns', array( $this, 'set_custom_columns' ) );
		add_action( 'manage_ag-themer_posts_custom_column', array( $this, 'render_custom_column' ), 10, 2 );
		add_action( 'manage_ag-themer_posts_custom_column', array( $this, 'column_content' ), 10, 2 );
		add_filter( 'manage_ag-themer_posts_columns', array( $this, 'column_headings' ) );

	    add_action('pre_get_posts', array($this, 'filter_ag_themer_query_by_template_type'));

		add_action('views_edit-ag-themer', array($this, 'prk_ag_themer_tabs_before_subsubsub'), 5);
		add_action('admin_footer-edit.php', array($this, 'prk_ag_themer_add_modal_trigger'));

		add_filter('manage_ag-themer_posts_columns', [$this, 'add_status_column']);
		add_action('manage_ag-themer_posts_custom_column', [$this, 'render_status_column'], 10, 2);
		add_action('admin_footer-edit.php', [$this, 'inline_js_for_switch']);
		add_action('wp_ajax_prk_toggle_themer_status', [$this, 'ajax_toggle_status']);

		add_action( 'admin_head', array( $this, 'correct_current_active_menu' ), 50 );

		$this->add_elementor_cpt_support();

		if ( defined( 'ELEMENTOR_PRO_VERSION' ) && ELEMENTOR_PRO_VERSION > 2.8 ) {
			add_action( 'elementor/editor/footer', array( $this, 'register_ag_theme_builder_epro_script' ), 99 );
		}

		register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );
		register_activation_hook( __FILE__, array( $this, 'flush_rewrites' ) );

	}

	public function load_ajax_handlers() {
    require_once get_template_directory() . '/inc/ag-theme-builder/admin/save-handler.php';
	}

	public function filter_ag_themer_query_by_template_type($query) {
		global $pagenow;
		$post_type = $_GET['post_type'] ?? '';

		if (
			is_admin() &&
			$pagenow === 'edit.php' &&
			$post_type === 'ag-themer' &&
			!empty($_GET['template_type'])
		) {
			$query->set('meta_query', [
				[
					'key' => 'ag_theme_builder_template_type',
					'value' => sanitize_text_field($_GET['template_type']),
					'compare' => '='
				]
			]);
		}
	}

	public function filter_ag_themer_by_template_type() {
		global $typenow;
		if ($typenow !== 'ag-themer') return;

		$current = $_GET['template_type'] ?? '';
		?>
		<select name="template_type">
			<option value="">نوع طرح (همه)</option>
			<optgroup label="ساختار صفحه">
				<option value="type_header" <?php selected($current, 'type_header'); ?>>هدر سایت</option>
				<option value="type_footer" <?php selected($current, 'type_footer'); ?>>فوتر سایت</option>
			</optgroup>
			<optgroup label="محتوای صفحه">
				<option value="type_archive" <?php selected($current, 'type_archive'); ?>>صفحه آرشیو</option>
				<option value="type_singular" <?php selected($current, 'type_singular'); ?>>صفحه تکی</option>
				<option value="custom" <?php selected($current, 'custom'); ?>>کد کوتاه</option>
			</optgroup>
		</select>
		<?php
	}

	public function add_ag_themer_template_type_tabs($views) {
		global $wpdb;

		$current = $_GET['template_type'] ?? '';
		$post_type = 'ag-themer';

		$template_types = [
			'type_header'   => 'هدر سایت',
			'type_footer'   => 'فوتر سایت',
			'type_archive'  => 'آرشیو',
			'type_singular' => 'تکی',
			'custom'        => 'کد کوتاه',
		];

		// ساخت تب‌ها با شمارنده
		foreach ($template_types as $key => $label) {
			$count = $wpdb->get_var($wpdb->prepare(
				"SELECT COUNT(*) FROM $wpdb->posts p
				JOIN $wpdb->postmeta m ON p.ID = m.post_id
				WHERE p.post_type = %s AND p.post_status != 'trash' AND m.meta_key = 'ag_theme_builder_template_type' AND m.meta_value = %s",
				$post_type,
				$key
			));

			$class = ($current === $key) ? 'current' : '';
			$link = add_query_arg([
				'post_type'     => $post_type,
				'template_type' => $key,
			], admin_url('edit.php'));

			$views[$key] = sprintf(
				'<a href="%s" class="%s">%s <span class="count">(%d)</span></a>',
				esc_url($link),
				$class,
				$label,
				$count
			);
		}

		return $views;
	}

	public function prk_ag_themer_tabs_before_subsubsub($views) {
		$current = $_GET['template_type'] ?? '';
		$template_types = [
			''               => 'همه',
			'type_header'    => 'هدر سایت',
			'type_footer'    => 'فوتر سایت',
			'type_archive'   => 'صفحه آرشیو',
			'type_singular'  => 'صفحه تکی',
			'custom'         => 'کدکوتاه',
		];

		echo '<div class="nav-tab-wrapper" style="margin: 10px 0 0;">';
		foreach ($template_types as $key => $label) {
			$class = ($current === $key || ($key === '' && $current === '')) ? 'nav-tab nav-tab-active' : 'nav-tab';
			$url = add_query_arg([
				'post_type'     => 'ag-themer',
				'template_type' => $key,
			], admin_url('edit.php'));

			echo '<a href="' . esc_url($url) . '" class="' . esc_attr($class) . '">' . esc_html($label) . '</a>';
		}
		echo '</div>';

		return $views; // مهمه که بازگردونده بشه تا subsubsub هم کار کنه
	}

	public function prk_ag_themer_add_modal_trigger() {
		if ($_GET['post_type'] !== 'ag-themer') return;
		$template_type = get_post_meta($post->ID, 'ag_theme_builder_template_type', true);
		?>

		<!--  طرح جدید مدال -->
		<div class="prk-modal" id="ag-themer-modal" data-append-to-body="false"  data-z-index="999999" data-overlay-blur="1px" data-overlay-background="rgba(0, 0, 0, 0.54)"
			style="border-radius: 4px;width: 950px;max-width: 90%;z-index: 1000000;">
			<div class="modal-header">
				<h2 class="modal-title">افزودن طرح بندی جدید</h2>
				<button data-modal-close="ag-themer-modal" class="modal-close">
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#424750" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
					<line x1="18" y1="6" x2="6" y2="18"></line>
					<line x1="6" y1="6" x2="18" y2="18"></line>
					</svg>
				</button>
			</div>

			<div class="modal-body">
				<div class="ag-theme-builder-options">
					<div class="ag-ui-form-group">

						<input type="text" name="post_title" value="<?php echo esc_attr(get_the_title($post)); ?>" class="ag-ui-input" placeholder="افزودن عنوان جدید..." id="ag-themer-input">
					</div>

					<div class="ag-theme-builder-options-row type-of-template">
						<div class="ag-theme-builder-options-row-heading">
							<label for="templateTypeSelector"><?php esc_html_e('انتخاب طرح', 'parskala'); ?></label>
						</div>
						<div class="ag-theme-builder-options-row-content">
							<select name="ag_theme_builder_template_type" id="ag_theme_builder_template_type" >
								<option value="" <?php selected($template_type, ''); ?>><?php esc_html_e('انتخاب', 'parskala'); ?></option>
								<optgroup label="<?php esc_html_e('ساختار', 'parskala'); ?>">
									<option value="type_header" <?php selected($template_type, 'type_header'); ?>><?php esc_html_e('هدر', 'parskala'); ?></option>
									<option value="type_footer" <?php selected($template_type, 'type_footer'); ?>><?php esc_html_e('فوتر', 'parskala'); ?></option>
								</optgroup>
								<optgroup label="<?php esc_html_e('محتوا', 'parskala'); ?>">
									<option value="type_archive" <?php selected($template_type, 'type_archive'); ?>><?php esc_html_e('آرشیو', 'parskala'); ?></option>
									<option value="type_singular" <?php selected($template_type, 'type_singular'); ?>><?php esc_html_e('صفحه تکی', 'parskala'); ?></option>
									<option value="custom" <?php selected($template_type, 'custom'); ?>><?php esc_html_e('کد کوتاه', 'parskala'); ?></option>
								</optgroup>
							</select>
						</div>
					</div>

					<input type="hidden" id="selectedLayout" name="ag_theme_builder_predefined_layout" value="">
				</div>

				<div class="predefined-layouts-section">
					<p>طرح بندی های از پیش تعریف شده</p>

					<div class="predefined-layouts">

						<div class="predefined-layout" data-name="layout_23" data-template-type="type_header">
							<img src="<?php echo get_template_directory_uri(); ?>/inc/ag-theme-builder/admin/assets/images/layout_1.jpg" alt="">
							<div class="predefined-layout-preview">
								<a href="#">
									<svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
										<path d="M15.5799 11.9999C15.5799 13.9799 13.9799 15.5799 11.9999 15.5799C10.0199 15.5799 8.41992 13.9799 8.41992 11.9999C8.41992 10.0199 10.0199 8.41992 11.9999 8.41992C13.9799 8.41992 15.5799 10.0199 15.5799 11.9999Z" stroke="#fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
										<path d="M11.9998 20.2702C15.5298 20.2702 18.8198 18.1902 21.1098 14.5902C22.0098 13.1802 22.0098 10.8102 21.1098 9.40021C18.8198 5.80021 15.5298 3.72021 11.9998 3.72021C8.46984 3.72021 5.17984 5.80021 2.88984 9.40021C1.98984 10.8102 1.98984 13.1802 2.88984 14.5902C5.17984 18.1902 8.46984 20.2702 11.9998 20.2702Z" stroke="#fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
									</svg>

									پیش نمایش
								</a>
							</div>
						</div>

						<div class="predefined-layout" data-name="layout_24" data-template-type="type_header">
							<img src="<?php echo get_template_directory_uri(); ?>/inc/ag-theme-builder/admin/assets/images/layout_1.jpg" alt="">
							<div class="predefined-layout-preview">
								<a href="#">
									<svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
										<path d="M15.5799 11.9999C15.5799 13.9799 13.9799 15.5799 11.9999 15.5799C10.0199 15.5799 8.41992 13.9799 8.41992 11.9999C8.41992 10.0199 10.0199 8.41992 11.9999 8.41992C13.9799 8.41992 15.5799 10.0199 15.5799 11.9999Z" stroke="#fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
										<path d="M11.9998 20.2702C15.5298 20.2702 18.8198 18.1902 21.1098 14.5902C22.0098 13.1802 22.0098 10.8102 21.1098 9.40021C18.8198 5.80021 15.5298 3.72021 11.9998 3.72021C8.46984 3.72021 5.17984 5.80021 2.88984 9.40021C1.98984 10.8102 1.98984 13.1802 2.88984 14.5902C5.17984 18.1902 8.46984 20.2702 11.9998 20.2702Z" stroke="#fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
									</svg>

									پیش نمایش
								</a>
							</div>
						</div>


					</div>
				</div>
			</div>


			<div class="modal-footer">

				<button id="agThemerConfirmModal" name="ag_theme_builder_template_type" class="ag-themer-modal-submit-btn ag-ui-submit-btn" type="submit">
					<svg width="21" height="21" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
						<path d="M6 12H18" stroke="#fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
						<path d="M12 18V6" stroke="#fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
					</svg>

					افزودن
				</button>
			
				<button data-modal-close="ag-themer-modal" class="ag-themer-modal-submit-btn cansel">لغو</button>	
			
			</div>

		</div>
		<script>
			document.addEventListener("DOMContentLoaded", function () {
				const submenuAddBtn = document.querySelector('li > a[href$="post-new.php?post_type=ag-themer"]');
				if (submenuAddBtn) {
					submenuAddBtn.addEventListener('click', function (e) {
						e.preventDefault();
						PrkModal.openById("ag-themer-modal");
					});
				}
				const btn = document.querySelector('.page-title-action');
				if (!btn) return;
				btn.href = "#";
				btn.addEventListener('click', function (e) {
					e.preventDefault();
					PrkModal.openById("ag-themer-modal");
				});
			});

			document.getElementById('agThemerConfirmModal')?.addEventListener('click', function (e) {
				e.preventDefault();
				const btn = this;
				// حالت لودینگ اضافه کن


				const title = document.getElementById('ag-themer-input')?.value.trim();
				const type = document.getElementById('ag_theme_builder_template_type')?.value;
				const layout = document.getElementById('selectedLayout')?.value;

				if (!title && !type){
					queue_alert( "لطفاً عنوان و نوع طرح را وارد کنید.", 'info', 1000);
					return;
				}else if (!title) {
					queue_alert( "لطفا نام طرح را وارد کنید.", 'info', 1000);
					return;
				}
				else if (!type) {
					queue_alert( "لطفا نوع طرح را وارد کنید.", 'info', 1000);
					return;
				}				

				if (title && type){
				btn.classList.add('is-loading');
				btn.innerHTML = 'درحال ذخیره ...';
				}

				const formData = new FormData();
				formData.append('action', 'prk_create_ag_themer_post');
				formData.append('_wpnonce', '<?php echo wp_create_nonce('create_ag_themer_post'); ?>');
				formData.append('post_title', title);
				formData.append('ag_theme_builder_template_type', type);
				formData.append('ag_theme_builder_predefined_layout', layout);

				fetch(ajaxurl, {
					method: 'POST',
					body: formData
				})
				.then(res => res.json())
				.then(data => {
					if (data.success) {
						window.location.href = data.data.edit_url;
					} else {
						alert(data.data || 'خطا در ذخیره طرح!');
					}
				});
			});

			</script>

		<?php
	}
	
	public static function add_status_column($columns) {
		$columns['ag_status'] = 'فعال';
		return $columns;
	}

	public static function render_status_column($column, $post_id) {
		if ($column !== 'ag_status') return;

		$status    = get_post_status($post_id);
		$is_active = $status === 'publish' ? 'xts-active' : '';

		echo '<div class="xts-switcher-btn ' . esc_attr($is_active) . '" data-id="' . esc_attr($post_id) . '" data-status="' . esc_attr($status) . '">
			<div class="xts-switcher-dot-wrap"><div class="xts-switcher-dot"></div></div>
			<div class="xts-switcher-labels">
				<span class="xts-switcher-label xts-on">روشن</span>
				<span class="xts-switcher-label xts-off">خاموش</span>
			</div>
		</div>';
	}

	public static function inline_js_for_switch() {
		if (!isset($_GET['post_type']) || $_GET['post_type'] !== 'ag-themer') return;

		$nonce = wp_create_nonce('toggle_themer_status');
		?>
		<script>
			document.addEventListener("DOMContentLoaded", function () {
				document.querySelectorAll(".xts-switcher-btn").forEach(el => {
					el.addEventListener("click", function () {
						const postId = this.dataset.id;
						const currentStatus = this.dataset.status;
						const newStatus = currentStatus === 'publish' ? 'draft' : 'publish';
						const btn = this;

						btn.classList.add('xts-loading');

						const formData = new FormData();
						formData.append('action', 'prk_toggle_themer_status');
						formData.append('_wpnonce', '<?php echo esc_js($nonce); ?>');
						formData.append('post_id', postId);
						formData.append('new_status', newStatus);

						fetch(ajaxurl, {
							method: 'POST',
							body: formData
						})
						.then(res => res.json())
						.then(data => {
							if (data.success) {
								btn.dataset.status = newStatus;
								btn.classList.toggle('xts-active', newStatus === 'publish');
							} else {
								alert("خطا در تغییر وضعیت");
							}
						})
						.finally(() => {
							btn.classList.remove('xts-loading');
						});
					});
				});
			});
		</script>
		<?php
	}

	public static function ajax_toggle_status() {
		check_ajax_referer('toggle_themer_status');

		$post_id    = intval($_POST['post_id'] ?? 0);
		$new_status = sanitize_text_field($_POST['new_status'] ?? '');

		if (!in_array($new_status, ['publish', 'draft'], true)) {
			wp_send_json_error('وضعیت نامعتبر است.');
		}

		if (get_post_type($post_id) !== 'ag-themer') {
			wp_send_json_error('پست یافت نشد.');
		}

		wp_update_post([
			'ID'          => $post_id,
			'post_status' => $new_status
		]);

		wp_send_json_success('وضعیت به‌روزرسانی شد.');
	}



	public function render_ui($post) {

		if ($post->post_type !== 'ag-themer') return;
		echo '<div id="ag-themer-builder">';
		include get_template_directory() . '/inc/ag-theme-builder/admin/ag-themer-ui.php';
		echo '</div>';
	}




	public function remove_revision_metabox() {
		remove_meta_box('revisionsdiv', 'ag-themer', 'normal');
	}

	public function hide_default_metaboxes() {
		$screen = get_current_screen();
		if ($screen->post_type !== 'ag-themer') return;

		echo '<style>
			#postdivrich, #submitdiv, .edit-post-sidebar, .block-editor, #minor-publishing {
				display: none !important;
			}
			.notice,
			.e-notice,
		
			body:not(.edit-php) .wp-heading-inline,
			.e-notice--warning,
			body:not(.edit-php) .page-title-action,
			.e-notice--dismissible {
				display: none !important;
			}
			#screen-options-link-wrap {
				display: none !important;
			}
			#elementor-switch-mode,
			#elementor-editor,
			#elementor-edit-button-gutenberg,
			#elementor-editor-button,
			#elementor-gutenberg-panel {
				display: none !important;
			}
		</style>';
	}

	public function enqueue_admin_styles($hook) {
		$screen = get_current_screen();
		if ( isset( $screen->post_type ) && $screen->post_type === 'ag-themer' ) {
			wp_enqueue_style(
				'ag-builder-ui',
				get_template_directory_uri() . '/inc/ag-theme-builder/admin/assets/css/ag-builder-ui.css',
				array(),
				'1'
			);
		}
	}

	public function prk_enqueue_admin_builder_script($hook) {
		// فقط برای ویرایش یا ساخت ag-themer
		if (!in_array($hook, ['post-new.php', 'post.php'])) {
			return;
		}

		$screen = get_current_screen();
		if (!$screen || $screen->post_type !== 'ag-themer') {
			return;
		}

		// لود فایل جاوااسکریپت
		wp_enqueue_script(
			'parskala-admin-builder',
			get_template_directory_uri() . '/inc/ag-theme-builder/admin/assets/js/admin-builder.js',
			['jquery'],
			'1.0.0',
			true
		);

		// انتقال داده به جاوااسکریپت
		wp_localize_script('parskala-admin-builder', 'ajax_nonces', [
			'save_ag_themer' => wp_create_nonce('save_ag_themer_nonce'),
			'ajaxurl'        => admin_url('admin-ajax.php'),
		]);
	}


	/**
	 * Instance of Ag_Theme_Builder_Admin
	 *
	 * @return Ag_Theme_Builder_Admin Instance of Ag_Theme_Builder_Admin
	 */
	public static function instance() {
		if ( ! isset( self::$_instance ) ) {
			self::$_instance = new self();
		}

		return self::$_instance;
	}

	/**
	 * Script for Elementor Pro full site editing support.
	 *
	 * @return void
	 * @since 1.0.0
	 *
	 */
	public function register_ag_theme_builder_epro_script() {
		$ids_array = array(
			array(
				'id'    => get_ag_theme_builder_header_id(),
				'value' => 'Header',
			),
			array(
				'id'    => get_ag_theme_builder_footer_id(),
				'value' => 'Footer',
			),
			array(
				'id'    => ag_theme_builder_get_singular_id(),
				'value' => 'Singular',
			),
			array(
				'id'    => ag_theme_builder_get_archive_id(),
				'value' => 'Archive',
			),
		);
	}

	/**
	 * Adds or removes list table column headings.
	 *
	 * @param array $columns Array of columns.
	 *
	 * @return array
	 */
	public function column_headings( $columns ) {
		unset( $columns['date'] );

		$columns['ag_theme_builder_display_rules'] = __( 'شرط نمایش', 'parskala' );
		$columns['ag_status'] = __( 'فعال', 'parskala' );
		$columns['date']                             = __( 'تاریخ', 'parskala' );

		return $columns;
	}

	/**
	 * Adds the custom list table column content.
	 *
	 * @param array $column Name of column.
	 * @param int $post_id Post id.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function column_content( $column, $post_id ) {

		if ( 'ag_theme_builder_display_rules' === $column ) {

			$locations = get_post_meta( $post_id, 'ag_theme_builder_target_include_locations', true );
			if ( ! empty( $locations ) ) {
				echo '<div class="ag-advanced-headers-location-wrap" style="margin-bottom: 5px;">';
				echo '<strong>' . __( 'Display: ', 'parskala' ) . '</strong>';
				$this->column_display_location_rules( $locations );
				echo '</div>';
			}

			$locations = get_post_meta( $post_id, 'ag_theme_builder_target_exclude_locations', true );
			if ( ! empty( $locations ) ) {
				echo '<div class="ag-advanced-headers-exclusion-wrap" style="margin-bottom: 5px;">';
				echo '<strong>Exclusion: </strong>';
				$this->column_display_location_rules( $locations );
				echo '</div>';
			}

			$users = get_post_meta( $post_id, 'ag_theme_builder_target_user_roles', true );
			if ( isset( $users ) && is_array( $users ) ) {
				if ( isset( $users[0] ) && ! empty( $users[0] ) ) {
					$user_label = array();
					foreach ( $users as $user ) {
						$user_label[] = Ag_Target_Rules_Fields::get_user_by_key( $user );
					}
					echo '<div class="ag-advanced-headers-users-wrap">';
					echo '<strong>Users: </strong>';
					echo join( ', ', array_map( 'esc_html', $user_label ) );
					echo '</div>';
				}
			}
		}
	}

	/**
	 * Get Markup of Location rules for Display rule column.
	 *
	 * @param array $locations Array of locations.
	 *
	 * @return void
	 */
	public function column_display_location_rules( $locations ) {

		$location_label = array();
		$index          = array_search( 'specifics', $locations['rule'], true );
		if ( false !== $index && ! empty( $index ) ) {
			unset( $locations['rule'][ $index ] );
		}

		if ( isset( $locations['rule'] ) && is_array( $locations['rule'] ) ) {
			foreach ( $locations['rule'] as $location ) {
				$location_label[] = Ag_Target_Rules_Fields::get_location_by_key( $location );
			}
		}
		if ( isset( $locations['specific'] ) && is_array( $locations['specific'] ) ) {
			foreach ( $locations['specific'] as $location ) {
				$location_label[] = Ag_Target_Rules_Fields::get_location_by_key( $location );
			}
		}

		echo join( ', ', array_map( 'esc_html', $location_label ) );
	}

	public function flush_rewrites() {
		$this->ag_theme_builder_post_type();
		flush_rewrite_rules();
	}

	/**
	 * Register Post type for Ag Theme Builder templates
	 */
	public function ag_theme_builder_post_type() {
		$labels = array(
			'name'               => __( 'طرح‌ها', 'parskala' ),
			'singular_name'      => __( 'طرح', 'parskala' ),
			'menu_name'          => __( 'صفحه‌ساز', 'parskala' ), // این بمونه چون منوی اصلیه
			'name_admin_bar'     => __( 'طرح', 'parskala' ),
			'add_new'            => __( 'افزودن طرح', 'parskala' ),
			'add_new_item'       => __( 'افزودن طرح جدید', 'parskala' ),
			'new_item'           => __( 'طرح جدید', 'parskala' ),
			'edit_item'          => __( 'ویرایش طرح', 'parskala' ),
			'view_item'          => __( 'مشاهده طرح', 'parskala' ),
			'all_items'          => __( 'همه طرح‌ها', 'parskala' ),
			'search_items'       => __( 'جستجوی طرح‌ها', 'parskala' ),
			'parent_item_colon'  => __( 'طرح مادر:', 'parskala' ),
			'not_found'          => __( 'هیچ طرحی پیدا نشد.', 'parskala' ),
			'not_found_in_trash' => __( 'هیچ طرحی در زباله‌دان پیدا نشد.', 'parskala' ),
		);

		$args = array(
			'labels'              => $labels,
			'public'              => true,
			'show_ui'             => true,
			'show_in_menu'        => true,
			'rewrite'             => false,
			'query_var'           => false,
			'can_export'          => true,
			'show_in_nav_menus'   => false,
			'exclude_from_search' => false,
			'publicly_queryable' => false,
			'map_meta_cap'        => true,
			'capability_type'     => 'post',
			'hierarchical'        => false,
			'has_archive'         => false,
			'menu_position' => 20, // ← جایگاه چهارم در منوی پیشخوان
			'menu_icon'           => AG_THEME_BUILDER_URL . '/admin/assets/images/ag-themer-icon.svg',
			'supports'            => array( 'elementor' ),
		);

		register_post_type( 'ag-themer', $args );

	}

	public function register_settings_submenus() {

		// Add sub menu
		add_submenu_page(
			'themes.php',
			esc_html__( 'Theme Builder', 'parskala' ),
			esc_html__( 'Theme Builder', 'parskala' ),
			'manage_options',
			'edit.php?post_type=ag-themer'
		);

	}

	public function ag_theme_parse_query($query) {
		if (
			is_admin() &&
			$query->is_main_query() &&
			$query->get('post_type') === 'ag-themer'
		) {
			$query->set('s', false); // غیرفعال کردن جستجو
		}
	}

	/**
	 *** Add elementor support for wpr_templates.
	 **/
	public function add_elementor_cpt_support() {

		if ( ! is_admin() ) {
			return;
		}

		$cpt_support = get_option( 'elementor_cpt_support' );

		if ( ! $cpt_support ) {
			update_option( 'elementor_cpt_support', array( 'post', 'page', 'ag-themer' ) );
		} elseif ( ! in_array( 'ag-themer', $cpt_support, true ) ) {
			$cpt_support[] = 'ag-themer';
			update_option( 'elementor_cpt_support', $cpt_support );
		}

	}

	public function correct_current_active_menu() {

		$screen = get_current_screen();

		if ( 'ag-themer' === $screen->id ) {
			?>
			<script type="text/javascript">
				jQuery(document).ready(function ($) {
					$('#toplevel_page_ag-elementor-addons').addClass('wp-has-current-submenu wp-menu-open menu-top menu-top-first').removeClass('wp-not-current-submenu');
					$('#toplevel_page_ag-elementor-addons > a').addClass('wp-has-current-submenu').removeClass('wp-not-current-submenu');
					$("#toplevel_page_ag-elementor-addons a[href*='edit.php?post_type=ag-themer']").addClass('current');
				});
			</script>
			<?php
		}

	}

	/**
	 * Register settings.
	 */
	public function ag_theme_builder_frontend_settings() {

		$themer_settings = array(
			'public'   => false,
			'status'   => false,
			'expanded' => false,
			'tab'      => 'all-layout',
			'size'     => 500,
			'layout'   => 'list',
		);

		add_option( 'ag_themer_frontend_settings', $themer_settings );

	}


	/**
	 * Markup for Display Rules Tabs.
	 *
	 * @since  1.0.0
	 */
	public function display_rules_tab() {
		// Load Target Rule assets.
		Ag_Target_Rules_Fields::get_instance()->admin_styles();

		$template_type = get_post_meta( get_the_ID(), 'ag_theme_builder_template_type', true );
	    $is_disabled = empty( $template_type ) ? ' hidden' : '';

		$include_locations = get_post_meta( get_the_id(), 'ag_theme_builder_target_include_locations', true );
		$exclude_locations = get_post_meta( get_the_id(), 'ag_theme_builder_target_exclude_locations', true );
		$users             = get_post_meta( get_the_id(), 'ag_theme_builder_target_user_roles', true );
		?>
		<tr class="ag-theme-builder-target-rules-row repeater ag-theme-builder-options-row <?php echo esc_attr( $is_disabled ); ?>">
			<td class="ag-theme-builder-target-rules-row-heading ag-theme-builder-options-row-heading">
				<label><?php esc_html_e( 'شرط نمایش', 'parskala' ); ?></label>
				<i class="ag-theme-builder-target-rules-heading-help dashicons dashicons-editor-help" title="<?php echo esc_attr__( 'Add locations for where this template should appear.', 'parskala' ); ?>"></i>
			</td>
			<td class="ag-theme-builder-target-rules-row-content ag-theme-builder-options-row-content">
				<?php
				Ag_Target_Rules_Fields::target_rule_settings_field(
					'ag-theme-builder-target-rules-location',
					array(
						'title'          => __( 'Display Rules', 'parskala' ),
						'value'          => '[{"type":"basic-global","specific":null}]',
						'tags'           => 'site,enable,target,pages',
						'rule_type'      => 'display',
						'add_rule_label' => __( 'افزودن شرط نمایش', 'parskala' ),
					),
					$include_locations
				);
				?>
			</td>
		</tr>
		<tr class="ag-theme-builder-target-rules-row repeater ag-theme-builder-options-row <?php echo esc_attr( $is_disabled ); ?>">
			<td class="ag-theme-builder-target-rules-row-heading ag-theme-builder-options-row-heading">
				<label><?php esc_html_e( 'شرط عدم نمایش', 'parskala' ); ?></label>
				<i class="ag-theme-builder-target-rules-heading-help dashicons dashicons-editor-help" title="<?php echo esc_attr__( 'Add locations for where this template should not appear.', 'parskala' ); ?>"></i>
			</td>
			<td class="ag-theme-builder-target-rules-row-content ag-theme-builder-options-row-content">
				<?php
				Ag_Target_Rules_Fields::target_rule_settings_field(
					'ag-theme-builder-target-rules-exclusion',
					array(
						'title'          => __( 'Exclude On', 'parskala' ),
						'value'          => '[]',
						'tags'           => 'site,enable,target,pages',
						'add_rule_label' => __( 'افزودن شرط عدم نمایش', 'parskala' ),
						'rule_type'      => 'exclude',
					),
					$exclude_locations
				);
				?>
			</td>
		</tr>
		<tr class="ag-theme-builder-target-rules-row repeater ag-theme-builder-options-row <?php echo esc_attr( $is_disabled ); ?>">
			<td class="ag-theme-builder-target-rules-row-heading ag-theme-builder-options-row-heading">
				<label><?php esc_html_e( 'نقش کاربر', 'parskala' ); ?></label>
				<i class="ag-theme-builder-target-rules-heading-help dashicons dashicons-editor-help" title="<?php echo esc_attr__( 'Display custom template based on user role.', 'parskala' ); ?>"></i>
			</td>
			<td class="ag-theme-builder-target-rules-row-content ag-theme-builder-options-row-content">
				<?php
				Ag_Target_Rules_Fields::target_user_role_settings_field(
					'ag-theme-builder-target-rules-users',
					array(
						'title'          => __( 'Users', 'parskala' ),
						'value'          => '[]',
						'tags'           => 'site,enable,target,pages',
						'add_rule_label' => __( 'افزودن شرط جدید', 'parskala' ),
					),
					$users
				);
				?>
			</td>
		</tr>
		<?php
	}

	public function ag_theme_builder_save_meta( $post_id ) {
		// جلوگیری از ذخیره خودکار
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

		// نانس چک
		if ( ! isset( $_POST['ag_theme_builder_meta_nounce'] ) || ! wp_verify_nonce( $_POST['ag_theme_builder_meta_nounce'], 'ag_theme_builder_meta_nounce' ) ) return;

		// دسترسی کاربر
		if ( ! current_user_can( 'edit_post', $post_id ) ) return;

		// ذخیره نوع قالب
		if ( isset( $_POST['ag_theme_builder_template_type'] ) ) {
			update_post_meta( $post_id, 'ag_theme_builder_template_type', sanitize_text_field( $_POST['ag_theme_builder_template_type'] ) );
		}

		// ذخیره حالت چسبندگی هدر
		if ( isset( $_POST['ag_theme_builder_sticky'] ) ) {
			update_post_meta( $post_id, 'ag_theme_builder_sticky', sanitize_text_field( $_POST['ag_theme_builder_sticky'] ) );
		}

		// ذخیره قوانین هدف‌گیری
		if ( class_exists( '\Ag_Theme_Builder\Lib\Ag_Target_Rules_Fields' ) ) {
			$target_locations = \Ag_Theme_Builder\Lib\Ag_Target_Rules_Fields::get_format_rule_value( $_POST, 'ag-theme-builder-target-rules-location' );
			$target_exclusion = \Ag_Theme_Builder\Lib\Ag_Target_Rules_Fields::get_format_rule_value( $_POST, 'ag-theme-builder-target-rules-exclusion' );
			$target_users     = isset( $_POST['ag-theme-builder-target-rules-users'] ) ? array_map( 'sanitize_text_field', $_POST['ag-theme-builder-target-rules-users'] ) : [];

			update_post_meta( $post_id, 'ag_theme_builder_target_include_locations', $target_locations );
			update_post_meta( $post_id, 'ag_theme_builder_target_exclude_locations', $target_exclusion );
			update_post_meta( $post_id, 'ag_theme_builder_target_user_roles', $target_users );
		}

		// ست کردن نوع قالب برای المنتور
	update_post_meta( $post_id, '_elementor_template_type', 'ag-themer' );
}


	/**
	 * Don't display the elementor Ag Theme Builder templates on the frontend for non edit_posts capable users.
	 *
	 * @since  1.0.0
	 */
	public function block_template_frontend() {
		if ( is_singular( 'ag-themer' ) && ! current_user_can( 'edit_posts' ) ) {
			wp_safe_redirect( site_url(), 301 );
			die;
		}
	}


	/**
	 * Set shortcode column for template list.
	 *
	 * @param array $columns template list columns.
	 */
	public function set_custom_columns( $columns ) {
		$date_column = $columns['date'];

		unset( $columns['date'] );
		$columns['type'] = __( 'نوع', 'parskala' );
		$columns['date'] = $date_column;

		return $columns;
	}

	/**
	 * Display shortcode in template list column.
	 *
	 * @param array $column template list column.
	 * @param int $post_id post id.
	 */
	public function render_custom_column( $column, $post_id ) {

		if ( $column !== 'type' ) return;

		$type = get_post_meta( $post_id, 'ag_theme_builder_template_type', true );

		$labels = [
			'type_header'   => 'هدر',
			'type_footer'   => 'فوتر',
			'type_archive'  => 'آرشیو',
			'type_singular' => 'صفحه تکی',
			'custom'        => 'کد کوتاه',
		];

		$label = $labels[ $type ] ?? 'نامشخص';

		echo '<span class="ag-theme-builder-type-col-wrap">' . esc_html( $label ) . '</span>';
	}

}

Ag_Theme_Builder_Admin::instance();
