<?php

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

class SEO_Fury_Schema_Templates {

    const POST_TYPE = 'seo_fury_schema_tpl';

    public function __construct() {
        add_action('init', array($this, 'register_post_type'));
        add_action('wp_ajax_seo_fury_save_schema_template',      array($this, 'ajax_save_template'));
        add_action('wp_ajax_seo_fury_get_schema_templates',      array($this, 'ajax_get_templates'));
        add_action('wp_ajax_seo_fury_delete_schema_template',    array($this, 'ajax_delete_template'));
        add_action('wp_ajax_seo_fury_prepare_template_editor',   array($this, 'ajax_prepare_template_editor'));
        add_filter('manage_' . self::POST_TYPE . '_posts_columns',       array($this, 'set_columns'));
        add_action('manage_' . self::POST_TYPE . '_posts_custom_column', array($this, 'render_column'), 10, 2);
        add_filter('post_row_actions',       array($this, 'replace_edit_action'), 10, 2);
        add_action('admin_menu',             array($this, 'register_editor_page'));
        add_action('admin_enqueue_scripts',  array($this, 'enqueue_editor_assets'));
        add_action('load-post-new.php',      array($this, 'redirect_add_new'));
    }

    public function register_post_type() {
        $labels = array(
            'name'               => __('Schema Templates', 'seo-fury'),
            'singular_name'      => __('Schema Template', 'seo-fury'),
            'add_new'            => __('Add New', 'seo-fury'),
            'add_new_item'       => __('Add New Schema Template', 'seo-fury'),
            'edit_item'          => __('Edit Schema Template', 'seo-fury'),
            'new_item'           => __('New Schema Template', 'seo-fury'),
            'all_items'          => __('Schema Templates', 'seo-fury'),
            'search_items'       => __('Search Schema Templates', 'seo-fury'),
            'not_found'          => __('No schema templates found', 'seo-fury'),
            'not_found_in_trash' => __('No schema templates found in trash', 'seo-fury'),
            'menu_name'          => __('Schema Templates', 'seo-fury'),
        );

        register_post_type(self::POST_TYPE, array(
            'labels'          => $labels,
            'public'          => false,
            'show_ui'         => true,
            'show_in_menu'    => false,
            'capability_type' => 'post',
            'supports'        => array('title'),
            'rewrite'         => false,
            'query_var'       => false,
        ));
    }

    public function set_columns($columns) {
        return array(
            'cb'          => $columns['cb'],
            'title'       => __('Name', 'seo-fury'),
            'schema_type' => __('Schema Type', 'seo-fury'),
            'schema_mode' => __('Mode', 'seo-fury'),
            'date'        => __('Date', 'seo-fury'),
        );
    }

    public function render_column($column, $post_id) {
        if ($column === 'schema_type') {
            echo esc_html(get_post_meta($post_id, '_seo_fury_tpl_type', true) ?: '—');
        } elseif ($column === 'schema_mode') {
            $mode   = get_post_meta($post_id, '_seo_fury_tpl_mode', true) ?: '—';
            $labels = array(
                'generator'      => __('Generator', 'seo-fury'),
                'custom'         => __('Custom JSON-LD', 'seo-fury'),
                'custom_builder' => __('Constructor', 'seo-fury'),
            );
            echo esc_html($labels[$mode] ?? $mode);
        }
    }

    public function ajax_save_template() {
        check_ajax_referer('seo_fury_schema_templates_nonce', 'nonce');
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => 'Permission denied'));
        }

        $name        = sanitize_text_field(wp_unslash($_POST['name'] ?? ''));
        $mode        = sanitize_text_field(wp_unslash($_POST['mode'] ?? 'generator'));
        $type        = sanitize_text_field(wp_unslash($_POST['type'] ?? 'none'));
        $data        = wp_unslash($_POST['data'] ?? '{}');
        $custom      = wp_unslash($_POST['custom'] ?? '');
        $builder_raw = wp_unslash($_POST['builder_data'] ?? '');
        $template_id = intval($_POST['template_id'] ?? 0);

        if (empty($name)) {
            wp_send_json_error(array('message' => __('Template name is required', 'seo-fury')));
        }

        // Validate JSON data field
        if ($data && $data !== '{}') {
            json_decode($data);
            if (json_last_error() !== JSON_ERROR_NONE) {
                $data = '{}';
            }
        }

        if ($template_id > 0) {
            $post = get_post($template_id);
            if (!$post || $post->post_type !== self::POST_TYPE) {
                wp_send_json_error(array('message' => 'Invalid template'));
            }
            wp_update_post(array('ID' => $template_id, 'post_title' => $name, 'post_status' => 'publish'));
        } else {
            $template_id = wp_insert_post(array(
                'post_title'  => $name,
                'post_type'   => self::POST_TYPE,
                'post_status' => 'publish',
            ));
        }

        if (!$template_id || is_wp_error($template_id)) {
            wp_send_json_error(array('message' => __('Failed to save template', 'seo-fury')));
        }

        update_post_meta($template_id, '_seo_fury_tpl_mode',   $mode);
        update_post_meta($template_id, '_seo_fury_tpl_type',   $type);
        update_post_meta($template_id, '_seo_fury_tpl_data',   $data);
        update_post_meta($template_id, '_seo_fury_tpl_custom', $custom);
        if (!empty($builder_raw)) {
            update_post_meta($template_id, '_seo_fury_tpl_builder_data', $builder_raw);
        }

        wp_send_json_success(array('id' => $template_id, 'name' => $name));
    }

    public function ajax_get_templates() {
        check_ajax_referer('seo_fury_schema_templates_nonce', 'nonce');
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => 'Permission denied'));
        }

        $posts = get_posts(array(
            'post_type'   => self::POST_TYPE,
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby'     => 'title',
            'order'       => 'ASC',
        ));

        $templates = array();
        foreach ($posts as $post) {
            $templates[] = array(
                'id'           => $post->ID,
                'name'         => $post->post_title,
                'mode'         => get_post_meta($post->ID, '_seo_fury_tpl_mode', true) ?: 'generator',
                'type'         => get_post_meta($post->ID, '_seo_fury_tpl_type', true) ?: 'none',
                'data'         => get_post_meta($post->ID, '_seo_fury_tpl_data', true) ?: '{}',
                'custom'       => get_post_meta($post->ID, '_seo_fury_tpl_custom', true) ?: '',
                'builder_data' => get_post_meta($post->ID, '_seo_fury_tpl_builder_data', true) ?: '',
                'date'         => get_the_date('', $post),
            );
        }

        wp_send_json_success(array('templates' => $templates));
    }

    public function ajax_delete_template() {
        check_ajax_referer('seo_fury_schema_templates_nonce', 'nonce');
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => 'Permission denied'));
        }

        $template_id = intval($_POST['template_id'] ?? 0);
        if (!$template_id) {
            wp_send_json_error(array('message' => 'Invalid template ID'));
        }

        $post = get_post($template_id);
        if (!$post || $post->post_type !== self::POST_TYPE) {
            wp_send_json_error(array('message' => 'Invalid template'));
        }

        wp_delete_post($template_id, true);
        wp_send_json_success();
    }

    /**
     * Prepare (or create) a template and return its data for the inline editor modal.
     */
    public function ajax_prepare_template_editor() {
        check_ajax_referer('seo_fury_schema_templates_nonce', 'nonce');
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => 'Permission denied'));
        }

        $template_id = intval($_POST['template_id'] ?? 0);
        $is_new      = false;

        if (!$template_id) {
            $template_id = wp_insert_post(array(
                'post_title'  => __('New Schema Template', 'seo-fury'),
                'post_type'   => self::POST_TYPE,
                'post_status' => 'draft',
            ));
            if (!$template_id || is_wp_error($template_id)) {
                wp_send_json_error(array('message' => __('Failed to create template', 'seo-fury')));
            }
            $is_new = true;
        }

        $post = get_post($template_id);
        if (!$post || $post->post_type !== self::POST_TYPE) {
            wp_send_json_error(array('message' => 'Invalid template'));
        }

        $mode        = get_post_meta($template_id, '_seo_fury_tpl_mode', true) ?: 'generator';
        $type        = get_post_meta($template_id, '_seo_fury_tpl_type', true) ?: 'none';
        $data_raw    = get_post_meta($template_id, '_seo_fury_tpl_data', true) ?: '{}';
        $custom      = get_post_meta($template_id, '_seo_fury_tpl_custom', true) ?: '';
        $builder_raw = get_post_meta($template_id, '_seo_fury_tpl_builder_data', true) ?: '';

        $data_array = json_decode($data_raw, true);
        if (!is_array($data_array)) {
            $data_array = array();
        }

        $schema_item_id = 'tpl_' . $template_id;
        $schema_item = array(
            'id'     => $schema_item_id,
            'type'   => $type,
            'mode'   => $mode,
            'label'  => $post->post_title,
            'data'   => $data_array,
            'custom' => $custom,
        );
        if (!empty($builder_raw)) {
            $bd = json_decode($builder_raw, true);
            if (is_array($bd)) {
                $schema_item['builder_data'] = $bd;
            }
        }

        wp_send_json_success(array(
            'templateId'        => $template_id,
            'templateName'      => $post->post_title,
            'schemaItemId'      => $schema_item_id,
            'schemaItems'       => $type !== 'none' ? array($schema_item) : array(),
            'initialSchemaType' => $type,
            'isNew'             => $is_new,
        ));
    }

    /**
     * Redirect the standard WP "Add New" screen for this CPT to our custom editor.
     */
    public function redirect_add_new() {
        if (isset($_GET['post_type']) && $_GET['post_type'] === self::POST_TYPE) {
            wp_safe_redirect(admin_url('admin.php?page=seo-fury-edit-schema-template'));
            exit;
        }
    }

    /**
     * Replace the default WP "Edit" row action with a link to our custom editor page.
     */
    public function replace_edit_action($actions, $post) {
        if ($post->post_type !== self::POST_TYPE) {
            return $actions;
        }
        $edit_url = admin_url('admin.php?page=seo-fury-edit-schema-template&id=' . $post->ID);
        $actions['edit'] = '<a href="' . esc_url($edit_url) . '">' . __('Edit', 'seo-fury') . '</a>';
        return $actions;
    }

    /**
     * Register the hidden admin page used as the schema template editor.
     */
    public function register_editor_page() {
        $hook = add_submenu_page(
            '',
            __('Edit Schema Template', 'seo-fury'),
            __('Edit Schema Template', 'seo-fury'),
            'edit_posts',
            'seo-fury-edit-schema-template',
            array($this, 'render_editor_page')
        );

        if ($hook) {
            add_action("load-{$hook}", function() {
                global $title;
                if (null === $title) {
                    $title = __('Edit Schema Template', 'seo-fury');
                }
            });
        }
    }

    /**
     * Enqueue scripts and styles on the template editor page or list page (inline mode).
     */
    public function enqueue_editor_assets($hook) {
        $is_editor_page = ($hook === 'admin_page_seo-fury-edit-schema-template');
        $is_list_page   = ($hook === 'toplevel_page_seo-fury'
                           && isset($_GET['tab']) && $_GET['tab'] === 'schema_templates');

        if (!$is_editor_page && !$is_list_page) {
            return;
        }

        // --- Standalone editor page: validate template ---
        $template_id    = 0;
        $schema_item_id = '';
        $type           = 'none';
        $schema_items_json = '[]';
        $list_url       = '';

        if ($is_editor_page) {
            $template_id    = intval($_GET['id'] ?? 0);
            $template       = $template_id ? get_post($template_id) : null;
            if (!$template || $template->post_type !== self::POST_TYPE) {
                return;
            }

            $return_url_raw  = isset($_GET['return_url']) ? wp_unslash($_GET['return_url']) : '';
            $safe_return_url = $return_url_raw ? wp_validate_redirect($return_url_raw, '') : '';
            $list_url        = $safe_return_url ?: admin_url('admin.php?page=seo-fury&tab=schema_templates');

            $mode         = get_post_meta($template_id, '_seo_fury_tpl_mode', true) ?: 'generator';
            $type         = get_post_meta($template_id, '_seo_fury_tpl_type', true) ?: 'none';
            $data_raw     = get_post_meta($template_id, '_seo_fury_tpl_data', true) ?: '{}';
            $custom       = get_post_meta($template_id, '_seo_fury_tpl_custom', true) ?: '';
            $builder_raw  = get_post_meta($template_id, '_seo_fury_tpl_builder_data', true) ?: '';

            $data_array = json_decode($data_raw, true);
            if (!is_array($data_array)) {
                $data_array = array();
            }

            $schema_item_id = 'tpl_' . $template_id;
            $schema_item = array(
                'id'     => $schema_item_id,
                'type'   => $type,
                'mode'   => $mode,
                'label'  => $template->post_title,
                'data'   => $data_array,
                'custom' => $custom,
            );
            if (!empty($builder_raw)) {
                $bd = json_decode($builder_raw, true);
                if (is_array($bd)) {
                    $schema_item['builder_data'] = $bd;
                }
            }
            $schema_items_json = wp_json_encode($type !== 'none' ? array($schema_item) : array());
        }

        // --- Shared assets ---
        wp_enqueue_style('dashicons');
        wp_enqueue_style(
            'seo-fury-post-meta',
            SEO_FURY_URL . 'assets/post-meta.css',
            array(),
            SEO_FURY_VERSION
        );

        wp_enqueue_script('jquery');
        wp_enqueue_script(
            'seo-fury-schema-builder',
            SEO_FURY_URL . 'assets/schema-builder.js',
            array('jquery'),
            SEO_FURY_VERSION,
            true
        );
        wp_enqueue_script(
            'seo-fury-post-meta',
            SEO_FURY_URL . 'assets/post-meta.js',
            array('jquery', 'seo-fury-schema-builder'),
            SEO_FURY_VERSION,
            true
        );

        // Provide seoFuryData required by post-meta.js
        wp_localize_script('seo-fury-post-meta', 'seoFuryData', array(
            'siteName'            => get_bloginfo('name'),
            'separator'           => get_option('seo_fury_title_separator', '—'),
            'postTitle'           => '',
            'postExcerpt'         => '',
            'postId'              => 0,
            'postPermalink'       => '',
            'postStatus'          => '',
            'postAuthor'          => '',
            'postDate'            => '',
            'postModified'        => '',
            'postThumbnail'       => '',
            'defaultSchemaType'   => '',
            'ajaxUrl'             => admin_url('admin-ajax.php'),
            'nonce'               => wp_create_nonce('seo_fury_nonce'),
            'internalLinksNonce'  => wp_create_nonce('seo_fury_internal_links_nonce'),
            'schemaTemplatesNonce'=> wp_create_nonce('seo_fury_schema_templates_nonce'),
            'i18n'                => array(
                'customJsonLd'          => __('Custom JSON-LD', 'seo-fury'),
                'noSchemaSelected'      => __('No schema type selected.', 'seo-fury'),
                'enterTemplateName'     => __('Enter a name for this template:', 'seo-fury'),
                'templateSaved'         => __('Template saved successfully.', 'seo-fury'),
                'templateSaveError'     => __('Failed to save template.', 'seo-fury'),
                'confirmDeleteTemplate' => __('Delete this saved template?', 'seo-fury'),
                'loadingTemplates'      => __('Loading...', 'seo-fury'),
                'noSavedTemplates'      => __('No saved templates yet.', 'seo-fury'),
                'applyTemplate'         => __('Apply', 'seo-fury'),
                'pasteJsonLd'           => __('// Paste your JSON-LD here', 'seo-fury'),
            ),
            'shortcodeVariables'  => class_exists('SEO_Fury_Shortcode_Variables')
                ? SEO_Fury_Shortcode_Variables::get_variables()
                : array(),
        ));

        wp_enqueue_script(
            'seo-fury-schema-template-editor',
            SEO_FURY_URL . 'assets/schema-template-editor.js',
            array('seo-fury-post-meta'),
            SEO_FURY_VERSION,
            true
        );

        $i18n = array(
            'saving'            => __('Saving...', 'seo-fury'),
            'saved'             => __('Template saved successfully!', 'seo-fury'),
            'saveError'         => __('Failed to save template.', 'seo-fury'),
            'save'              => __('Save Changes', 'seo-fury'),
            'enterTemplateName' => __('Please enter a template name before saving.', 'seo-fury'),
            'noSchemaSelected'  => __('Please select a schema type and edit it before saving.', 'seo-fury'),
        );

        if ($is_editor_page) {
            wp_localize_script('seo-fury-schema-template-editor', 'seoFuryTemplateEditor', array(
                'mode'              => 'standalone',
                'templateId'        => $template_id,
                'schemaItemId'      => $schema_item_id,
                'initialSchemaType' => $type,
                'schemaItems'       => $schema_items_json,
                'ajaxUrl'           => admin_url('admin-ajax.php'),
                'nonce'             => wp_create_nonce('seo_fury_schema_templates_nonce'),
                'listUrl'           => $list_url,
                'i18n'              => $i18n,
            ));
        } else {
            // Inline mode: modal lives on the list page
            wp_localize_script('seo-fury-schema-template-editor', 'seoFuryTemplateEditor', array(
                'mode'              => 'inline',
                'templateId'        => 0,
                'schemaItemId'      => '',
                'initialSchemaType' => 'none',
                'schemaItems'       => '[]',
                'ajaxUrl'           => admin_url('admin-ajax.php'),
                'nonce'             => wp_create_nonce('seo_fury_schema_templates_nonce'),
                'listUrl'           => '',
                'i18n'              => $i18n,
            ));
        }
    }

    /**
     * Render the custom schema template editor admin page.
     */
    public function render_editor_page() {
        $template_id    = intval($_GET['id'] ?? 0);
        $return_url_raw = isset($_GET['return_url']) ? wp_unslash($_GET['return_url']) : '';
        $safe_return    = $return_url_raw ? wp_validate_redirect($return_url_raw, '') : '';

        if (!$template_id) {
            $new_id = wp_insert_post(array(
                'post_title'  => __('New Schema Template', 'seo-fury'),
                'post_type'   => self::POST_TYPE,
                'post_status' => 'draft',
            ));
            if (!$new_id || is_wp_error($new_id)) {
                wp_die(esc_html__('Failed to create template', 'seo-fury'));
            }
            $redirect = admin_url('admin.php?page=seo-fury-edit-schema-template&id=' . $new_id);
            if ($safe_return) {
                $redirect .= '&return_url=' . rawurlencode($safe_return);
            }
            wp_safe_redirect($redirect);
            exit;
        }

        $template = get_post($template_id);
        if (!$template || $template->post_type !== self::POST_TYPE) {
            wp_die(esc_html__('Template not found', 'seo-fury'));
        }

        $mode         = get_post_meta($template_id, '_seo_fury_tpl_mode', true) ?: 'generator';
        $type         = get_post_meta($template_id, '_seo_fury_tpl_type', true) ?: 'none';
        $data_raw     = get_post_meta($template_id, '_seo_fury_tpl_data', true) ?: '{}';
        $custom       = get_post_meta($template_id, '_seo_fury_tpl_custom', true) ?: '';
        $builder_raw  = get_post_meta($template_id, '_seo_fury_tpl_builder_data', true) ?: '';

        $data_array = json_decode($data_raw, true);
        if (!is_array($data_array)) {
            $data_array = array();
        }

        $schema_item_id = 'tpl_' . $template_id;
        $schema_item = array(
            'id'     => $schema_item_id,
            'type'   => $type,
            'mode'   => $mode,
            'label'  => $template->post_title,
            'data'   => $data_array,
            'custom' => $custom,
        );
        if (!empty($builder_raw)) {
            $bd = json_decode($builder_raw, true);
            if (is_array($bd)) {
                $schema_item['builder_data'] = $bd;
            }
        }

        $mode_labels = array(
            'generator'      => __('Generator', 'seo-fury'),
            'custom'         => __('Custom JSON-LD', 'seo-fury'),
            'custom_builder' => __('Constructor', 'seo-fury'),
        );

        $list_url = $safe_return ?: admin_url('admin.php?page=seo-fury&tab=schema_templates');
        ?>
        <div class="wrap">
            <h1 class="wp-heading-inline">
                <?php echo esc_html(
                    /* translators: %s: template name */
                    sprintf(__('Edit Schema Template: %s', 'seo-fury'), $template->post_title)
                ); ?>
            </h1>
            <a href="<?php echo esc_url($list_url); ?>" class="page-title-action">
                &larr; <?php esc_html_e('Back to Templates', 'seo-fury'); ?>
            </a>
            <hr class="wp-header-end">

            <div id="sf-template-editor-notices"></div>

            <div style="max-width:720px; background:var(--sf-white,#fff); border:1px solid var(--sf-gray-200,#c3c4c7); box-shadow:var(--sf-shadow,0 1px 1px rgba(0,0,0,.04)); padding:16px 24px; margin-top:20px; border-radius:var(--sf-radius,4px); display:flex; align-items:center; gap:12px; flex-wrap:wrap;">
                <div style="flex:1; min-width:200px;">
                    <label for="sf-template-name-input" style="font-weight:600; margin-right:8px;"><?php esc_html_e('Template Name:', 'seo-fury'); ?></label>
                    <input type="text" id="sf-template-name-input" class="regular-text"
                           value="<?php echo esc_attr($template->post_title); ?>"
                           placeholder="<?php echo esc_attr__('Enter template name...', 'seo-fury'); ?>">
                </div>
                <button type="button" id="sf-open-schema-generator" class="button button-primary">
                    <span class="dashicons dashicons-admin-generic" style="margin-top:3px;"></span>
                    <?php esc_html_e('Open Schema Generator', 'seo-fury'); ?>
                </button>
            </div>

            <!-- Hidden inputs that post-meta.js reads to initialise schemaItems -->
            <input type="hidden" id="seo_fury_schema_items"
                   value="<?php echo esc_attr(wp_json_encode($type !== 'none' ? array($schema_item) : array())); ?>">
            <input type="hidden" id="seo_fury_schema_active"
                   value="<?php echo esc_attr($type !== 'none' ? $schema_item_id : ''); ?>">
        </div>
        <?php

        // Render the generator + editor modals for template creation/editing
        if (class_exists('SEO_Fury_Post_Meta_Schema')) {
            $schema_handler = new SEO_Fury_Post_Meta_Schema();
            $schema_handler->render_template_generator_html($schema_item);
        }
    }
}
