<?php

// The core plugin class.
class WDPOP {
	
	private $settings;
	private $enable_mc;
	private $enable_templates;
	
	public function __construct() {
		
		$this->load_dependencies();
		
		$this->init_variables();
		
		$this->run_the_wing_popup_plugin();
		
		// add_action( 'template_redirect', function() {
		// 	if ( is_singular( 'wdpop_template' ) ) {
		// 		wp_redirect( home_url() );
		// 		exit;
		// 	}
		// });
		
	}
	function init_variables(){
		$this->settings = WDPOP_Helper::get_settings();
        $this->enable_mc = !empty($this->settings['enable_mailchimp']) ?? false;
        $this->enable_templates = !empty($this->settings['enable_templates']) ?? false;		
	}
	
	function run_the_wing_popup_plugin(){
		
		if( $this->enable_templates ){
			add_action( 'init', [$this, 'add_templates_cpt'] );	
			add_action( 'admin_menu', [$this, 'change_cpt_submenu_position'], 999 );
			
		}
		
		$this->handle_group_id_update();
		
		new WDPOP_Admin();
		new WDPOP_Public();
		
		// new WDPOP_Template();
	}
	
	function handle_group_id_update(){
		$group_options = ['wdpops_settings']; // wdpops
		foreach ( $group_options as $group_option ) {
			add_filter( 'wdpop_core_'. $group_option .'_save', [$this, 'wdpop_update_group_id']);
		}
	}
	
	function wdpop_update_group_id($data){
		// error_log('save_filter_run init');
		$last_group  = (int) get_option( 'wdpop_core_last_group', 0 );
		
		$group_field_ids = ['mc_form_item']; // wdpop_item
		foreach ( $group_field_ids as $group_field_id ) {
			if ( isset( $data[$group_field_id] ) && is_array( $data[$group_field_id] ) ) {
				$max_id = 0;
				foreach ( $data[$group_field_id] as $group ) {
					if ( isset( $group['__group_id'] ) && $group['__group_id'] > $max_id ) {
						$max_id = (int) $group['__group_id'];
						// error_log('save_filter_run');
					}
				}
				if ( $max_id > 0 && $max_id > $last_group) {
					update_option( 'wdpop_core_last_group', $max_id );
					// error_log('save_filter_run: id updated');
				}
			}			
		}
		return $data;
	}
	
	private function load_dependencies() {
		
		require_once WDPOP_DIR . 'includes/class-wing-popup-helper.php';		
		require_once WDPOP_DIR . 'admin/class-wing-popup-admin.php';
		require_once WDPOP_DIR . 'public/class-wing-popup-public.php';
		require_once WDPOP_DIR . 'includes/features/template.php';

	}
	function add_templates_cpt() {

		$labels = array(
			'name'                     => __( 'Templates', 'wing-popup' ),
			'singular_name'            => __( 'Template', 'wing-popup' ),
			'add_new'                  => __( 'Add New', 'wing-popup' ),
			'add_new_item'             => __( 'Add New Template', 'wing-popup' ),
			'edit_item'                => __( 'Edit Template', 'wing-popup' ),
			'new_item'                 => __( 'New Template', 'wing-popup' ),
			'view_item'                => __( 'View Template', 'wing-popup' ),
			'view_items'               => __( 'View Templates', 'wing-popup' ),
			'search_items'             => __( 'Search Templates', 'wing-popup' ),
			'not_found'                => __( 'No Templates found.', 'wing-popup' ),
			'not_found_in_trash'       => __( 'No Templates found in Trash.', 'wing-popup' ),
			'parent_item_colon'        => __( 'Parent Template:', 'wing-popup' ),
			'all_items'                => __( 'Templates', 'wing-popup' ),
			'archives'                 => __( 'Template Archives', 'wing-popup' ),
			'attributes'               => __( 'Template Attributes', 'wing-popup' ),
			'insert_into_item'         => __( 'Insert into Template', 'wing-popup' ),
			'uploaded_to_this_item'    => __( 'Uploaded to this Template', 'wing-popup' ),
			'featured_image'           => __( 'Featured Image', 'wing-popup' ),
			'set_featured_image'       => __( 'Set featured image', 'wing-popup' ),
			'remove_featured_image'    => __( 'Remove featured image', 'wing-popup' ),
			'use_featured_image'       => __( 'Use as featured image', 'wing-popup' ),
			'menu_name'                => __( 'Templates', 'wing-popup' ),
			'filter_items_list'        => __( 'Filter Templates list', 'wing-popup' ),
			'filter_by_date'           => __( 'Filter by date', 'wing-popup' ),
			'items_list_navigation'    => __( 'Templates list navigation', 'wing-popup' ),
			'items_list'               => __( 'Templates list', 'wing-popup' ),
			'item_published'           => __( 'Template saved.', 'wing-popup' ),
			'item_updated'             => __( 'Template updated.', 'wing-popup' ),
			'item_link'                => __( 'Template Link', 'wing-popup' ),
			'item_link_description'    => __( 'A link to an Template.', 'wing-popup' ),
		);

		$args = array(
			'labels'              => $labels,
			'description'         => __( 'Manage Templates to use via shortcode or menus', 'wing-popup' ),
			'public'              => true,
			'publicly_queryable'  => true,   // ✅ Allow frontend preview (needed for Elementor)
			'exclude_from_search' => true,   // ✅ Still not searchable
			'show_ui'             => true,
			'show_in_menu'        => 'wdpop_home',
			'show_in_nav_menus'   => false,
			'show_in_admin_bar'   => false,
			'show_in_rest'        => true,   // ✅ Gutenberg + Elementor REST support
			'menu_position'       => 95,
			'capability_type'     => 'post',
			'supports'            => array( 'title', 'editor', 'thumbnail' ),
			'has_archive'         => false,
			'rewrite'             => array( 'slug' => 'wdpop_template' ), // ✅ Give it a URL for preview
			'query_var'           => true,
			'can_export'          => true,
			'delete_with_user'    => false,
		);

		
		register_post_type( 'wdpop_template', $args );

	}
	function change_cpt_submenu_position() {
		$this->change_the_cpt_sub_menu_position('wdpop_template', 'wdpop_home', 3);
	}
	
	function change_the_cpt_sub_menu_position($cpt, $parent_slug, $position = 2) {
		global $submenu;

		$cpt_slug    = 'edit.php?post_type='. $cpt; // CPT menu slug

		if ( isset( $submenu[$parent_slug] ) ) {
			// Find the CPT submenu item
			foreach ( $submenu[$parent_slug] as $index => $item ) {
				if ( $item[2] === $cpt_slug ) {
					$cpt_item = $item;
					unset( $submenu[$parent_slug][$index] );
					break;
				}
			}

			// Insert CPT item at the 3rd position (array index starts at 0)
			// array_slice + array_merge reorders it cleanly
			$position = $position; // 3rd item
			$submenu[$parent_slug] = array_merge(
				array_slice( $submenu[$parent_slug], 0, $position, true ),
				array( $cpt_item ),
				array_slice( $submenu[$parent_slug], $position, null, true )
			);
		}
	}

}
