<?php
/**
 * Admin Mega Menu Popup
 * @package Softech_Addons_for_Elementor
 * @since 1.0.0
 */

namespace Softech_Addons_for_Elementor\Includes;

if (!defined('ABSPATH')) {
    exit;
}

class Mega_Menu_Settings
{

    // public function __construct() {
    //     add_action('admin_footer-nav-menus.php', [$this, 'render_popup']);
    //     add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
    //     add_action('wp_ajax_softech_create_mega_menu_template', [$this, 'ajax_create_mega_menu_template']);
    //     add_action('wp_ajax_softech_get_mega_menu_template', [$this, 'ajax_get_mega_menu_template']);
    //     add_action('wp_ajax_softech_save_mega_menu_settings', [$this, 'ajax_save_mega_menu_settings']);
    // }

    public function __construct()
    {
        add_action('admin_footer-nav-menus.php', [$this, 'render_popup']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        add_action('wp_ajax_softech_create_mega_menu_template', [$this, 'ajax_create_mega_menu_template']);
        add_action('wp_ajax_softech_create_new_mega_menu_template', [$this, 'ajax_create_new_mega_menu_template']); // NEW
        add_action('wp_ajax_softech_get_mega_menu_template', [$this, 'ajax_get_mega_menu_template']);
        add_action('wp_ajax_softech_save_mega_menu_settings', [$this, 'ajax_save_mega_menu_settings']);
    }

    /**
     * Render popup HTML
     */
    public function render_popup()
    {
        $base_url = SITS_ELEMENTOR_ADDONS_PLUGIN_URL;
        ?>
        <div class="softech-mm-settings-popup-wrap" style="display:none;">
            <div class="softech-mm-settings-popup">
                <input type="hidden" id="softech_mm_current_id" value="">
                <input type="hidden" id="softech_mm_current_depth" value="">
                <input type="hidden" id="softech_mm_current_template_id" value="">

                <div class="softech-mm-settings-popup-header">
                    <img class="softech-mm-popup-logo"
                        src="<?php echo esc_attr($base_url) . 'assets/images/logo-40x40.png'; ?>" />

                    <span><?php esc_html_e('Softech Mega Menu', 'softech-addons-for-elementor'); ?></span>

                    <span class="softech-mm-popup-title">
                        <?php esc_html_e('Menu Item: ', 'softech-addons-for-elementor'); ?><span></span>
                    </span>

                    <span class="dashicons dashicons-no-alt softech-mm-settings-close-popup-btn"></span>
                </div>

                <?php
                $pro_active = (defined('softech_ADDONS_PRO_VERSION') && softech_fs()->can_use_premium_code())
                    ? 'data-pro-active="true"'
                    : 'data-pro-active="false"';
                ?>

                <div class="softech-mm-settings-wrap" <?php echo esc_attr($pro_active); ?>>

                    <h4><?php esc_html_e('General', 'softech-addons-for-elementor'); ?></h4>

                    <div class="softech-mm-setting softech-mm-setting-switcher">
                        <h4><?php esc_html_e('Enable Mega Menu', 'softech-addons-for-elementor'); ?></h4>
                        <input type="checkbox" id="softech_mm_enable">
                        <label for="softech_mm_enable"></label>
                    </div>



                    <!-- <div class="softech-mm-setting">
                        <h4><?php esc_html_e('Mega Menu Content', 'softech-addons-for-elementor'); ?></h4>
                        <div>
                            <div style="margin-bottom: 10px; display:flex; gap:10px;">
                                <label style="display: block; margin-bottom: 5px;">
                                    <input type="radio" name="softech_mm_template_option" value="create" checked>
                                    <?php esc_html_e('Create New Template', 'softech-addons-for-elementor'); ?>
                                </label>
                                <label style="display: block;">
                                    <input type="radio" name="softech_mm_template_option" value="select">
                                    <?php esc_html_e('Select Existing Template', 'softech-addons-for-elementor'); ?>
                                </label>
                            </div>

                            <div id="softech_mm_template_select_wrapper" style="display:none; margin-bottom: 10px;">
                                <select id="softech_mm_template_select" style="width: 100%;">
                                    <option value="0">
                                        <?php esc_html_e('-- Select Template --', 'softech-addons-for-elementor'); ?></option>
                                    <?php
                                    $templates = $this->sitsel_get_elementor_templates_without_default_kit();
                                    if (!empty($templates)):
                                        foreach ($templates as $id => $title): ?>
                                            <option value="<?php echo esc_attr($id); ?>">
                                                <?php echo esc_html($title); ?>
                                            </option>
                                        <?php endforeach;
                                    endif;
                                    ?>
                                </select>
                            </div>

                            <button class="button button-primary softech-edit-mega-menu-btn">
                                <i class="eicon-elementor-square"></i>
                                <?php esc_html_e('Edit with Elementor', 'softech-addons-for-elementor'); ?>
                            </button>

                            <div id="softech_mm_template_status" style="margin-top:10px; color:#666;"></div>
                        </div>
                    </div> -->

                    <!-- Template Type removed - templates are always saved as `container` -->
                    <div class="softech-mm-setting">
                        <h4><?php esc_html_e('Mega Menu Content', 'softech-addons-for-elementor'); ?></h4>


                        <div>
                            <div>

                                <select id="softech_mm_template_select">
                                    <option value="0">
                                        <?php esc_html_e('-- Create New Template --', 'softech-addons-for-elementor'); ?>
                                    </option>
                                    <?php
                                    $templates = $this->sitsel_get_elementor_templates_without_default_kit();
                                    if (!empty($templates)):
                                        foreach ($templates as $id => $title): ?>
                                            <option value="<?php echo esc_attr($id); ?>">
                                                <?php echo esc_html($title); ?>
                                            </option>
                                        <?php endforeach;
                                    endif;
                                    ?>
                                </select>
                            </div>

                            <button class="button button-primary softech-edit-mega-menu-btn">
                                <i class="eicon-elementor-square"></i>
                                <?php esc_html_e('Edit with Elementor', 'softech-addons-for-elementor'); ?>
                            </button>
                            <div id="softech_mm_template_status" style="color:#666;"></div>
                        </div>
                    </div>


                    <!-- Continue with your icon & badge sections unchanged... -->

                </div>

                <div class="softech-mm-settings-popup-footer">
                    <button class="button softech-save-mega-menu-btn">
                        <?php esc_html_e('Save', 'softech-addons-for-elementor'); ?>
                    </button>
                </div>

            </div>
        </div>

        <!-- Editor Popup (Iframe) -->
        <div class="softech-mm-editor-popup-wrap" style="display:none;">
            <div class="softech-mm-editor-popup-iframe"></div>
            <div class="softech-mm-editor-close-popup-btn"><span>&times;</span></div>
        </div>

        <?php
    }

    /**
     * Load JS & CSS only on nav-menus page
     */
    public function enqueue_assets($hook)
    {

        if ($hook !== 'nav-menus.php') {
            return;
        }

        $base_url = SITS_ELEMENTOR_ADDONS_PLUGIN_URL;

        wp_enqueue_script(
            'softech-mega-menu-js',
            $base_url . 'assets/js/mega-menu.js',
            ['jquery'],
            time(),
            true
        );

        // wp_localize_script('softech-mega-menu-js', 'softech_mm', [
        //     'nonce' => wp_create_nonce('softech_mm_nonce'),
        //     'ajaxurl' => admin_url('admin-ajax.php'),
        // ]);
        wp_localize_script('softech-mega-menu-js', 'softech_mm', [
            'nonce' => wp_create_nonce('softech_mm_nonce'),
            'ajaxurl' => admin_url('admin-ajax.php'),
            'admin_url' => admin_url(),
        ]);

        wp_enqueue_style(
            'softech-mega-menu-css',
            $base_url . 'assets/css/mega-menu.css',
            [],
            time()
        );
    }

    /**
     * AJAX handler to create/get an Elementor template for a menu item
     */
    public function ajax_create_mega_menu_template()
    {
        // Security check
        check_ajax_referer('softech_mm_nonce', 'nonce');

        if (!current_user_can('edit_theme_options')) {
            wp_send_json_error(['message' => esc_html__('Unauthorized', 'softech-addons-for-elementor')], 403);
        }

        $menu_item_id = isset($_POST['item_id']) ? absint(wp_unslash($_POST['item_id'])) : 0;
        $menu_item_depth = isset($_POST['item_depth']) ? absint(wp_unslash($_POST['item_depth'])) : 0;

        if (!$menu_item_id) {
            wp_send_json_error(['message' => esc_html__('Missing menu item ID', 'softech-addons-for-elementor')]);
        }

        // Ensure we have a nav_menu_item post
        $menu_item_post = get_post($menu_item_id);
        if (!$menu_item_post || $menu_item_post->post_type !== 'nav_menu_item') {
            wp_send_json_error(['message' => esc_html__('Menu item not found', 'softech-addons-for-elementor')]);
        }

        $template_id = get_post_meta($menu_item_id, '_softech_mega_menu_template_id', true);

        // Always use container type for templates
        $template_type = 'container';

        if (!$template_id) {
            // Create an Elementor library template
            $new_template = wp_insert_post([
                'post_title' => "Softech Mega Menu Template #$menu_item_id",
                //    'post_title'  => 'Mega Menu Template #' . intval($menu_item_id),
                // 'post_title'  => sprintf(__('Mega Menu Template  #%d', 'softech-addons-for-elementor'), $menu_item_id),
                'post_type' => 'elementor_library',
                'post_status' => 'publish',
            ]);

            if (is_wp_error($new_template) || !$new_template) {
                wp_send_json_error(['message' => esc_html__('Failed to create template.', 'softech-addons-for-elementor')]);
            }

            $template_id = $new_template;
            update_post_meta($menu_item_id, '_softech_mega_menu_template_id', $template_id);
            update_post_meta($menu_item_id, '_softech_mm_enable', '1');
            // Don't save template type on menu item; templates always set to 'container'
            update_post_meta($template_id, '_softech_mega_menu_item_id', $menu_item_id);
            update_post_meta($template_id, '_elementor_template_type', 'container');
        }

        $edit_link = admin_url("post.php?post={$template_id}&action=elementor");

        wp_send_json_success([
            'template_id' => (int) $template_id,
            'edit_link' => esc_url_raw($edit_link),
        ]);
    }

    /**
     * AJAX handler to FORCE CREATE a new Elementor template (ignoring existing one)
     */
    public function ajax_create_new_mega_menu_template()
    {
        // Security check
        check_ajax_referer('softech_mm_nonce', 'nonce');

        if (!current_user_can('edit_theme_options')) {
            wp_send_json_error(['message' => esc_html__('Unauthorized', 'softech-addons-for-elementor')], 403);
        }

        $menu_item_id = isset($_POST['item_id']) ? absint(wp_unslash($_POST['item_id'])) : 0;
        $menu_item_depth = isset($_POST['item_depth']) ? absint(wp_unslash($_POST['item_depth'])) : 0;

        if (!$menu_item_id) {
            wp_send_json_error(['message' => esc_html__('Missing menu item ID', 'softech-addons-for-elementor')]);
        }

        // Ensure we have a nav_menu_item post
        $menu_item_post = get_post($menu_item_id);
        if (!$menu_item_post || $menu_item_post->post_type !== 'nav_menu_item') {
            wp_send_json_error(['message' => esc_html__('Menu item not found', 'softech-addons-for-elementor')]);
        }

        // ALWAYS create a NEW template (don't check for existing)
        $timestamp = time();
        $new_template = wp_insert_post([
            'post_title' => "Softech Mega Menu Template #$menu_item_id - $timestamp",
            'post_type' => 'elementor_library',
            'post_status' => 'publish',
        ]);

        if (is_wp_error($new_template) || !$new_template) {
            wp_send_json_error(['message' => esc_html__('Failed to create template.', 'softech-addons-for-elementor')]);
        }

        $template_id = $new_template;

        // Update the menu item meta with NEW template ID (replacing old one)
        update_post_meta($menu_item_id, '_softech_mega_menu_template_id', $template_id);
        update_post_meta($menu_item_id, '_softech_mm_enable', '1');

        // Set template meta
        update_post_meta($template_id, '_softech_mega_menu_item_id', $menu_item_id);
        update_post_meta($template_id, '_elementor_template_type', 'container');

        $edit_link = admin_url("post.php?post={$template_id}&action=elementor");

        wp_send_json_success([
            'template_id' => (int) $template_id,
            'edit_link' => esc_url_raw($edit_link),
            'message' => esc_html__('New template created successfully', 'softech-addons-for-elementor')
        ]);
    }

    /**
     * Return the existing template_id for a nav_menu_item (no creation)
     */
    public function ajax_get_mega_menu_template()
    {
        check_ajax_referer('softech_mm_nonce', 'nonce');

        if (!current_user_can('edit_theme_options')) {
            wp_send_json_error(['message' => esc_html__('Unauthorized', 'softech-addons-for-elementor')], 403);
        }

        $menu_item_id = isset($_POST['item_id']) ? absint(wp_unslash($_POST['item_id'])) : 0;
        if (!$menu_item_id) {
            wp_send_json_error(['message' => esc_html__('Missing menu item ID', 'softech-addons-for-elementor')]);
        }

        $template_id = get_post_meta($menu_item_id, '_softech_mega_menu_template_id', true);
        // Template type not needed; templates are always container.
        $mm_enable = get_post_meta($menu_item_id, '_softech_mm_enable', true) ? true : false;

        wp_send_json_success([
            'template_id' => $template_id ? (int) $template_id : 0,
            'mm_enable' => $mm_enable,
        ]);
    }

    public function ajax_save_mega_menu_settings()
    {
        check_ajax_referer('softech_mm_nonce', 'nonce');

        if (!current_user_can('edit_theme_options')) {
            wp_send_json_error(['message' => esc_html__('Unauthorized', 'softech-addons-for-elementor')], 403);
        }

        $menu_item_id = isset($_POST['item_id']) ? absint(wp_unslash($_POST['item_id'])) : 0;
        if (!$menu_item_id) {
            wp_send_json_error(['message' => esc_html__('Missing menu item ID', 'softech-addons-for-elementor')]);
        }

        $template_id = isset($_POST['template_id']) ? absint(wp_unslash($_POST['template_id'])) : 0;
        // Always container
        $template_type = 'container';
        $enable = isset($_POST['enable']) ? filter_var(wp_unslash($_POST['enable']), FILTER_VALIDATE_BOOLEAN) : false;

        update_post_meta($menu_item_id, '_softech_mega_menu_template_id', $template_id);
        update_post_meta($menu_item_id, '_softech_mm_enable', $enable ? '1' : '0');
        // no menu meta to store for template type; templates are always container
        if ($template_id) {
            update_post_meta($template_id, '_elementor_template_type', 'container');
        }

        wp_send_json_success(['message' => esc_html__('Settings saved', 'softech-addons-for-elementor')]);
    }

    // protected function sitsel_get_elementor_templates_without_default_kit()
    // {
    //     $templates = [];

    //     $query = new \WP_Query([
    //         'post_type' => 'elementor_library',
    //         'post_status' => 'publish',
    //         'posts_per_page' => -1,
    //     ]);

    //     if ($query->have_posts()) {
    //         foreach ($query->posts as $post) {
    //             if ($post->post_title === 'Default Kit') {
    //                 continue;
    //             }
    //             $templates[$post->ID] = $post->post_title;
    //         }
    //     }

    //     wp_reset_postdata();
    //     return $templates;
    // }


    protected function sitsel_get_elementor_templates_without_default_kit()
{
    $templates = [];
    // Get Elementor's internal template source (no DB query, no warnings)
    $source = \Elementor\Plugin::$instance->templates_manager->get_source( 'local' );
    // Fetch all local templates
    $all_templates = $source->get_items();
    foreach ( $all_templates as $template ) {
        // Skip non-container templates
        if ( $template['type'] !== 'container' ) {
            continue;
        }
        // Skip Default Kit
        if ( $template['title'] === 'Default Kit' ) {
            continue;
        }
        $templates[$template['template_id']] = $template['title'];
    }
    return $templates;
}
}

new Mega_Menu_Settings();
