<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://ristrettoapps.com
 * @since      1.0.0
 *
 * @package    Spawnster
 * @subpackage Spawnster/admin
 */

use RistrettoApps\Spawnster\Base\Constants;
use RistrettoApps\Spawnster\BaseController;
use RistrettoApps\Spawnster\Helpers\ComponentView;
use RistrettoApps\Spawnster\Helpers\HTMLTagFormatter;
use RistrettoApps\Spawnster\Helpers\TemplateView;
use RistrettoApps\Spawnster\Services\AjaxHandler;
use RistrettoApps\Spawnster\Services\EnhanceContent;
use RistrettoApps\Spawnster\Services\GenerateContent;
use RistrettoApps\Spawnster\Services\GenerateDescription;
use RistrettoApps\Spawnster\Services\PublishPages;

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Spawnster
 * @subpackage Spawnster/admin
 * @author     Ristretto Apps
 */
class Spawnster_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

    /**
     * Template to be used in displaying the admin pages.
     *
     * @since    1.0.0
     * @access   private
     * @var TemplateView
     */
    private TemplateView $template;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version, TemplateView $template ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;
        $this->template = $template;

		add_action('admin_menu', array($this, 'add_plugin_admin_menu'));
        add_action('admin_menu', array($this, 'add_hidden_admin_pages'));
        add_action('wp_ajax_nopriv_generate_content', array($this, 'ajax_generate_content'));
        add_action('wp_ajax_generate_content', array($this, 'ajax_generate_content'));
        add_action('wp_ajax_nopriv_generate_description', array($this, 'ajax_generate_description'));
        add_action('wp_ajax_generate_description', array($this, 'ajax_generate_description'));
        add_action('wp_ajax_nopriv_view_content', array($this, 'ajax_view_content'));
        add_action('wp_ajax_view_content', array($this, 'ajax_view_content'));
        add_action('wp_ajax_nopriv_update_content', array($this, 'ajax_update_content'));
        add_action('wp_ajax_update_content', array($this, 'ajax_update_content'));
        add_action('wp_ajax_nopriv_publish_pages', array($this, 'ajax_publish_pages'));
        add_action('wp_ajax_publish_pages', array($this, 'ajax_publish_pages'));
        add_action('wp_ajax_nopriv_get_progress', array($this, 'ajax_get_progress'));
        add_action('wp_ajax_get_progress', array($this, 'ajax_get_progress'));
        add_action('wp_ajax_nopriv_enhance_content', array($this, 'ajax_enhance_content'));
        add_action('wp_ajax_enhance_content', array($this, 'ajax_enhance_content'));
        add_action('wp_ajax_nopriv_accept_content', array($this, 'ajax_accept_content'));
        add_action('wp_ajax_accept_content', array($this, 'ajax_accept_content'));
        add_action('wp_ajax_nopriv_reject_content', array($this, 'ajax_reject_content'));
        add_action('wp_ajax_reject_content', array($this, 'ajax_reject_content'));
        add_action('wp_ajax_nopriv_edit_menu', array($this, 'ajax_edit_menu'));
        add_action('wp_ajax_edit_menu', array($this, 'ajax_edit_menu'));

        add_action('init', array('RistrettoApps\Spawnster\BaseController', 'shouldRedirect'));
        add_action('admin_post_setup_website_form_submit', array('RistrettoApps\Spawnster\BaseController', 'handle_setup_your_website_submission'));
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Spawnster_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Spawnster_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

        $nonce = isset($_REQUEST['_wpnonce']) ? sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])) : null;

		wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/spawnster-admin.css', array(), $this->version, 'all' );

        if ( wp_verify_nonce( $nonce, 'spawnster-nonce' ) && isset( $_GET['page']) && $_GET['page'] == 'spawnster' ) {
            wp_enqueue_style( $this->plugin_name . '-tailwindcss', plugin_dir_url( __FILE__ ) . 'css/style.css', array(), $this->version, 'all' );
            wp_enqueue_style( $this->plugin_name . '-welcome', plugin_dir_url( __FILE__ ) . 'css/spawnster-welcome.css', array(), $this->version, 'all' );
        }
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Spawnster_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Spawnster_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
         * 
		 */


        // Enqueue David AI Minified JS
        wp_enqueue_script( 'david-ai-js', plugin_dir_url( __FILE__ ) . 'js/david-ai.min.js', array( 'jquery' ), $this->version, false );
        wp_add_inline_script( // Add David AI Minified JS to the head of the page
            'david-ai-js',
            'var plugin_dir_url = ' . wp_json_encode( plugins_url( '', __FILE__ ) . '/' ) . ';',
            'before'
        );

		wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/spawnster-admin.js', array( 'jquery', 'wp-util' ), $this->version, false );
        wp_enqueue_script( 'flowbite-js', plugin_dir_url(__FILE__) . 'js/flow-bite.min.js', array( 'jquery' ), $this->version, false );
        wp_localize_script( $this->plugin_name, 'spawnster', array(
            'ajax_url' => admin_url('admin-ajax.php')
        ));
		wp_register_style('spawnster_dashicons', plugin_dir_url( __FILE__ ) .'css/spawnster-dashicon.css', array(), $this->version, 'all');
		wp_enqueue_style('spawnster_dashicons');

	}

	/**
     * Register the menu item for the admin area.
     *
     * @since    1.0.0
     */
    public function add_plugin_admin_menu() {
        $nonce = wp_create_nonce( 'spawnster-nonce' );
        add_menu_page(
            'Spawnster Settings', // Page title
            'Spawnster',          // Menu title
            'manage_options',     // Capability
            $this->plugin_name,   // Menu slug
            array($this, 'display_plugin_admin_page'), // Callback function
            'dashicons-spawnster', // Icon URL
            26                     // Position
        );

        // Add welcome page as first submenu item
        add_submenu_page( $this->plugin_name, 'Spawnster Dashboard', 'Spawnster',
            'manage_options', 'admin.php?page=spawnster&view=welcome&_wpnonce=' . $nonce );

        add_submenu_page( $this->plugin_name, 'Instant Site Builder', 'Instant Site Builder',
            'manage_options', 'admin.php?page=spawnster&view=setup-your-website&_wpnonce=' . $nonce );

        add_submenu_page( $this->plugin_name, 'Auto-Writing Jobs', 'Auto-Writing Jobs',
            'manage_options', 'edit.php?post_type=spawnster_job' );

        // Removing Writing Jobs Settings - we don't need it for now
        // add_submenu_page( $this->plugin_name, 'Writing Jobs Settings', 'Writing Jobs Settings',
        //     'manage_options', 'spawnster-jobs-settings', array( $this, 'jobs_settings_page_content' ) );

        add_submenu_page( $this->plugin_name, 'Settings', 'Settings',
            'manage_options', 'admin.php?page=spawnster&view=settings&_wpnonce=' . $nonce );

        // Remove the automatically created submenu item that duplicates the main menu
        remove_submenu_page( $this->plugin_name, $this->plugin_name );
    }

    /**
     * Register hidden admin pages that aren't in the menu but are accessible.
     */
    public function add_hidden_admin_pages(): void {
        // This method is no longer needed as the hidden page is removed.
        // Keeping it here for now, but it will be removed in a subsequent edit.
    }


    /**
     * Display the admin settings page.
     *
     * @since    1.0.0
     */
    public function display_plugin_admin_page()
    {
        $nonce = isset($_REQUEST['_wpnonce']) ? sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])) : null;

        if ( ! wp_verify_nonce( $nonce, 'spawnster-nonce' ) ) {
            return;
        } else {
            // Hide admin notices on Spawnster pages for clean UI
            $this->hide_admin_notices();
            
            $step = isset($_GET['view']) ? sanitize_text_field( wp_unslash ( $_GET['view'] ) ) : 'welcome';
            $baseController = new BaseController($this->template);

            // Always proceed with the normal flow, regardless of API key status
            switch ($step) {
                case 'welcome':
                    $baseController->welcome();
                    break;
                case 'setup-your-pages':
                    $baseController->setupYourPages([]);
                    break;
                case 'setup-your-website':
                    $baseController->setupYourWebsite();
                    break;
                case 'settings':
                    $baseController->settings();
                    break;
                case 'check-generated-content':
                    $baseController->checkGeneratedContent();
                    break;
                default:
                    $baseController->welcome();
            }
        }
    }

    /**
     * Hide WordPress admin notices on Spawnster admin pages for cleaner UI.
     *
     * @since    1.0.0
     */
    private function hide_admin_notices()
    {
        // Remove all admin notices and update notices
        remove_all_actions('admin_notices');
        remove_all_actions('all_admin_notices');
        
        // Also remove user admin notices
        remove_all_actions('user_admin_notices');
        
        // Remove network admin notices if multisite
        if (is_multisite()) {
            remove_all_actions('network_admin_notices');
        }
        
        // Add CSS to hide any remaining notices that might slip through
        add_action('admin_head', array($this, 'hide_admin_notices_css'));
    }

    /**
     * Add CSS to hide any remaining admin notices.
     *
     * @since    1.0.0
     */
    public function hide_admin_notices_css()
    {
        echo '<style>
            .notice, .error, .updated, .update-nag, 
            .notice-error, .notice-warning, .notice-success, .notice-info,
            #message, .wrap > .notice, .wrap > .error, .wrap > .updated,
            .settings-error, .update-message {
                display: none !important;
            }
        </style>';
    }

    /**
     * The AJAX endpoint to when generating page content.
     *
     * @return bool|null
     *
     * @since 1.0.0
     */
    public function ajax_generate_content(): ?bool
    {
        // Add debug logging
        error_log('AJAX generate_content called - Enhanced error handling v1.1.4');
        
        try {
            if ( isset($_POST['data']) ) {
                parse_str( wp_kses_post( wp_unslash( $_POST['data'] ) ),$postData);
            }

            $nonce = isset($postData['_wpnonce']) ? sanitize_text_field( wp_unslash( $postData['_wpnonce'] ) ) : null;

            if ( ! wp_verify_nonce( $nonce, 'content-generation-wizard' ) ) {
                error_log('Security check failed in ajax_generate_content');
                wp_send_json_error('Security check failed');
                return false;
            } else {
                if (!empty($postData)) {

                    $postData['page_name'] = $postData['amp;page_name'] ?? null;
                    $postData['page_description'] = $postData['amp;page_description'] ?? null;
                    $pageId = $postData['amp;page_id'] ?? null;

                    foreach ($pageId as $pKey => $pId) {
                        if (boolval($pId)) {
                            unset($postData['page_name'][$pKey]);
                            unset($postData['page_description'][$pKey]);
                        }
                    }

                    $this->savePageNameRequest($postData['page_name']);
                    $this->savePageDescriptionRequest($postData['page_description']);

                    $generateContent = new GenerateContent();

                    error_log('About to call GenerateContent->handle()');
                    return $generateContent->handle($postData);
                } else {
                    error_log('No data provided in ajax_generate_content');
                    wp_send_json_error('No data provided');
                    return false;
                }
            }
        } catch (\Exception $e) {
            // Log the error for debugging
            error_log('AJAX Generate Content Error: ' . $e->getMessage());
            error_log('Stack trace: ' . $e->getTraceAsString());
            
            // Return a JSON error response
            wp_send_json_error('Content generation failed: ' . $e->getMessage());
            return false;
        } catch (\Throwable $e) {
            // Catch any other errors including fatal errors
            error_log('AJAX Generate Content Fatal Error: ' . $e->getMessage());
            error_log('Stack trace: ' . $e->getTraceAsString());
            
            wp_send_json_error('A critical error occurred: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * AJAX endpoint to generate description.
     *
     *
     * @since 1.0.0
     */
    public function ajax_generate_description(): void
    {
        $nonce = isset($_REQUEST['_wpnonce']) ? sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])) : null;

        if ( ! wp_verify_nonce( $nonce, 'spawnster-nonce' ) ) {
            wp_die('Security check failed');
        } else {
            if ( isset($_POST['website_name']) ) {
                $generateDescription = new GenerateDescription();

                $response = $generateDescription->handle( sanitize_text_field( wp_unslash( $_POST['website_name'] ) ) );

                wp_send_json_success($response);
            }

        }
    }

    /**
     * AJAX endpoint for editing content.
     *
     * @return string
     */
    public function ajax_view_content(): void
    {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : null;

        if ( ! wp_verify_nonce( $nonce, 'spawnster-nonce' ) ) {
            wp_die('Security check failed');
        } else {
            if (!empty($_POST['id'])) {

                $data = get_option(Constants::SPAWNSTER_UPDATED_CONTENT_KEY . wp_kses_post( wp_unslash( $_POST['id'] ) ));

                die(wp_kses_post(HTMLTagFormatter::format(stripcslashes($data))));
            }
        }
    }

    /**
     * AJAX endpoint for updating content request.
     *
     * @return void
     */
    public function ajax_update_content(): void
    {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : null;

        if ( ! wp_verify_nonce( $nonce, 'spawnster-nonce' ) ) {
            wp_die('Security check failed');
        } else {
            if (!empty($_POST['data'])) {
                parse_str( wp_kses_post ( wp_unslash( $_POST['data'] ) ), $postData);

                $id = $postData['amp;edit_modal_id'];

                $key = Constants::SPAWNSTER_UPDATED_CONTENT_KEY . $id;
                $content = $postData['edit_content_modal'];

                update_option($key, $content);

                die(wp_kses_post(HTMLTagFormatter::format(stripcslashes($content))));
            }
        }
    }

    /**
     * AJAX endpoint for publish pages request.
     *
     * @return void
     */
    public function ajax_publish_pages(): void
    {
        PublishPages::handle();
        wp_send_json_success();
    }

    /**
     * Get the progress of the AI content generation
     *
     * @return int
     */
    public function ajax_get_progress(): int
    {
        die(wp_kses(get_option('spawnster-generated-progress'), []) ?? 0);
    }

    /**
     * Save page request name in JSON encoded format.
     *
     * @param $postData
     * @return void
     */
    protected function savePageNameRequest($postData): void
    {
        if (get_option(Constants::SPAWNSTER_PAGE_NAME_REQUEST)) {
            update_option(Constants::SPAWNSTER_PAGE_NAME_REQUEST, serialize($postData));
        } else {
            add_option(Constants::SPAWNSTER_PAGE_NAME_REQUEST, serialize($postData));
        }
    }

    /**
     * Save page request name in JSON encoded format.
     *
     * @param $postData
     * @return void
     */
    protected function savePageDescriptionRequest($postData): void
    {
        if (get_option(Constants::SPAWNSTER_PAGE_DESCRIPTION_REQUEST)) {
            update_option(Constants::SPAWNSTER_PAGE_DESCRIPTION_REQUEST, serialize($postData));
        } else {
            add_option(Constants::SPAWNSTER_PAGE_DESCRIPTION_REQUEST, serialize($postData));
        }
    }

    public function ajax_enhance_content(): void
    {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : null;

        if ( ! wp_verify_nonce( $nonce, 'spawnster-nonce' ) ) {
            wp_die('Security check failed');
        } else {
            if (!empty($_POST['content']) && !empty($_POST['context']) && !empty($_POST['id'])) {

                $enhance_content = new EnhanceContent();
                $enhance_content->content = sanitize_text_field( wp_unslash( $_POST['content'] ) );
                $enhance_content->context = sanitize_text_field( wp_unslash( $_POST['context'] ) );
                $response = $enhance_content->handle();

                $updated_key = Constants::SPAWNSTER_UPDATED_CONTENT_KEY . sanitize_text_field( wp_unslash( $_POST['id'] ) );

                if (get_option($updated_key)) {
                    update_option($updated_key, $response);
                } else {
                    add_option($updated_key, $response);
                }

                die(wp_kses_post($response));
            }
        }
    }

    public function ajax_accept_content(): void
    {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : null;

        if ( ! wp_verify_nonce( $nonce, 'spawnster-nonce' ) ) {
            wp_die('Security check failed');
        } else {
            if (!empty($_POST['id'])) {
                $id = sanitize_text_field( wp_unslash( $_POST['id'] ) );
                $ids = explode('-', $id);

                $updated = get_option(Constants::SPAWNSTER_UPDATED_CONTENT_KEY . $id);
                $current = unserialize(get_option(Constants::SPAWNSTER_GENERATED_CONTENT_KEY . $ids[1]));
                $current[$ids[0]] = '<p>' . $updated . '</p>';

                update_option(
                    Constants::SPAWNSTER_GENERATED_CONTENT_KEY . $ids[1],
                    serialize($current)
                );

                delete_option(Constants::SPAWNSTER_UPDATED_CONTENT_KEY . $id);

                die(wp_kses_post($updated));
            }
        }
    }

    public function ajax_reject_content(): void
    {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : null;

        if ( ! wp_verify_nonce( $nonce, 'spawnster-nonce' ) ) {
            wp_die('Security check failed');
        } else {
            if (!empty($_POST['id'])) {
                $id = sanitize_text_field( wp_unslash( $_POST['id'] ) );

                delete_option(Constants::SPAWNSTER_UPDATED_CONTENT_KEY . $id);

                wp_send_json_success();
            }
        }
    }

    /**
     * AJAX endpoint
     * @return void
     */
    public function ajax_edit_menu()
    {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : null;

        if ( ! wp_verify_nonce( $nonce, 'spawnster-nonce' ) ) {
            wp_die('Security check failed');
        } else {
            if (!empty($_POST['id']) && !empty($_POST['menu'])) {

                $id = (int) sanitize_text_field( wp_unslash( $_POST['id'] ) );
                $value = sanitize_text_field( wp_unslash( $_POST['menu']) );

                // update the menu
                AjaxHandler::updateMenu($id, $value);

                wp_send_json_success();
            }
        }
    }

    /**
     * Handle AJAX request to toggle logging setting.
     */
    public function ajax_toggle_logging(): void {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : null;

        if (!wp_verify_nonce($nonce, 'spawnster-nonce')) {
            wp_send_json_error('Security check failed');
            return;
        }

        if (isset($_POST['enabled'])) {
            $enabled = filter_var($_POST['enabled'], FILTER_VALIDATE_BOOLEAN);
            update_option(\RistrettoApps\Spawnster\Base\Constants::SPAWNSTER_OPTION_LOGGING_ENABLED, $enabled);
            
            wp_send_json_success([
                'enabled' => $enabled,
                'message' => $enabled ? 'Logging enabled' : 'Logging disabled'
            ]);
        } else {
            wp_send_json_error('Invalid request');
        }
    }

    /**
     * Register the writing job post type.
     */
    public function register_writing_job_post_type(): void {
        $labels = array(
            'name'                       => _x( 'Writing Jobs', 'Post Type General Name', 'spawnster' ),
            'singular_name'              => _x( 'Writing Job', 'Post Type Singular Name', 'spawnster' ),
            'menu_name'                  => __( 'Writing Jobs', 'spawnster' ),
            'all_items'                  => __( 'All Writing Jobs', 'spawnster' ),
            'view_item'                  => __( 'View Writing Job', 'spawnster' ),
            'add_new_item'               => __( 'Add New Writing Job', 'spawnster' ),
            'add_new'                    => __( 'Add New', 'spawnster' ),
            'new_item'                   => __( 'New Writing Job', 'spawnster' ),
            'view_items'                 => __( 'View Writing Jobs', 'spawnster' ),
            'edit_item'                  => __( 'Edit Writing Job', 'spawnster' ),
            'update_item'                => __( 'Update Writing Job', 'spawnster' ),
            'separate_items_with_commas' => __( 'Separate Writing Jobs with commas', 'spawnster' ),
            'not_found'                  => __( 'No Writing Jobs found', 'spawnster' ),
            'not_found_in_trash'         => __( 'No Writing Jobs found in Trash', 'spawnster' ),
            'items_list'                 => __( 'Writing Jobs list', 'spawnster' ),
            'items_list_navigation'      => __( 'Writing Jobs list navigation', 'spawnster' ),
            'search_items'               => __( 'Search Writing Jobs', 'spawnster' ),
            'name_admin_bar'             => __( 'Writing Jobs', 'spawnster' ),
            'archives'                   => __( 'Writing Job Archives', 'spawnster' ),
            'attributes'                 => __( 'Writing Job Attributes', 'spawnster' ),
            'parent_item_colon'          => __( 'Parent Writing Job:', 'spawnster' ),
            'insert_into_item'           => __( 'Insert into Writing Job', 'spawnster' ),
            'uploaded_to_this_item'      => __( 'Uploaded to this Writing Job', 'spawnster' ),
            'filter_items_list'          => __( 'Filter Writing Jobs list', 'spawnster' ),
        );
        
        $args = array(
            'label'         => __( 'Writing Jobs', 'spawnster' ),
            'description'   => __( 'Manage your automated content writing jobs here.', 'spawnster' ),
            'labels'        => $labels,
            'public'        => true,
            'show_ui'       => true,
            'show_in_menu'  => false,
            'capability_type' => 'post',
            'hierarchical'  => false,
            'supports'      => array( 'title', 'author' ), // Removed 'editor' support
            'has_archive'   => false,
            'rewrite'       => false,
            'query_var'     => false,
            'can_export'    => false,
            'show_in_rest'  => false, // Disable REST API support to prevent block editor
        );
        
        register_post_type( 'spawnster_job', $args );
    }

    /**
     * Initialize writing jobs functionality.
     */
    public function init_writing_jobs(): void {
        // Add custom columns for the writing jobs list
        add_filter( 'manage_spawnster_job_posts_columns', array( $this, 'add_writing_job_columns' ) );
        add_action( 'manage_spawnster_job_posts_custom_column', array( $this, 'display_writing_job_columns' ), 10, 2 );
        
        // Add meta boxes for editing
        add_action( 'add_meta_boxes', array( $this, 'add_writing_job_meta_boxes' ) );
        add_action( 'save_post', array( $this, 'save_writing_job_meta' ) );
        
        // Add custom CSS for meta boxes
        add_action( 'admin_head', array( $this, 'add_writing_job_admin_styles' ) );
        
        // Disable block editor for spawnster_job post type
        add_filter( 'use_block_editor_for_post_type', array( $this, 'disable_block_editor_for_writing_jobs' ), 10, 2 );
        
        // Highlight parent menu for spawnster_job screens
        add_filter( 'parent_file', array( $this, 'highlight_parent_menu_for_writing_jobs' ) );
        add_filter( 'submenu_file', array( $this, 'highlight_submenu_for_writing_jobs' ) );
    }

    /**
     * Disable block editor for writing jobs post type.
     */
    public function disable_block_editor_for_writing_jobs( $use_block_editor, $post_type ): bool {
        if ( 'spawnster_job' === $post_type ) {
            return false;
        }
        return $use_block_editor;
    }

    /**
     * Highlight parent menu for writing jobs screens.
     */
    public function highlight_parent_menu_for_writing_jobs( $parent_file ): string {
        global $post_type, $pagenow;
        
        if ( 'spawnster_job' === $post_type || 
             ( 'edit.php' === $pagenow && isset( $_GET['post_type'] ) && 'spawnster_job' === $_GET['post_type'] ) ||
             ( 'post.php' === $pagenow && isset( $_GET['post'] ) && 'spawnster_job' === get_post_type( $_GET['post'] ) ) ||
             ( 'post-new.php' === $pagenow && isset( $_GET['post_type'] ) && 'spawnster_job' === $_GET['post_type'] ) ) {
            return 'spawnster';
        }
        
        return $parent_file;
    }

    /**
     * Highlight submenu for writing jobs screens.
     */
    public function highlight_submenu_for_writing_jobs( $submenu_file ) {
        global $post_type, $pagenow;
        
        if ( 'spawnster_job' === $post_type || 
             ( 'edit.php' === $pagenow && isset( $_GET['post_type'] ) && 'spawnster_job' === $_GET['post_type'] ) ||
             ( 'post.php' === $pagenow && isset( $_GET['post'] ) && 'spawnster_job' === get_post_type( $_GET['post'] ) ) ||
             ( 'post-new.php' === $pagenow && isset( $_GET['post_type'] ) && 'spawnster_job' === $_GET['post_type'] ) ) {
            return 'edit.php?post_type=spawnster_job';
        }
        
        return $submenu_file;
    }

    /**
     * Add meta boxes for writing job editing.
     */
    public function add_writing_job_meta_boxes(): void {
        add_meta_box(
            'spawnster_job_details',
            __( 'Writing Job Details', 'spawnster' ),
            array( $this, 'render_writing_job_meta_box' ),
            'spawnster_job',
            'normal',
            'high'
        );
    }

    /**
     * Render the writing job meta box.
     */
    public function render_writing_job_meta_box( $post ): void {
        wp_nonce_field( 'spawnster_job_meta', 'spawnster_job_meta_nonce' );
        
        $specific_topic = get_post_meta( $post->ID, 'specificTopic', true );
        $topic_category = get_post_meta( $post->ID, 'topicCategory', true );
        $word_count_goal = get_post_meta( $post->ID, 'wordCountGoal', true ) ?: 1000;
        $past_articles = get_post_meta( $post->ID, 'pastArticles', true ) ?: 5;
        $repeat = get_post_meta( $post->ID, 'repeat', true );
        $repeat_type = get_post_meta( $post->ID, 'repeatType', true ) ?: 'daily';
        $delay_publish = get_post_meta( $post->ID, 'delayPublish', true ) ?: 0;
        $notify_admin = get_post_meta( $post->ID, 'notifyAdmin', true );
        
        include plugin_dir_path( __FILE__ ) . 'partials/spawnster-admin-edit-job-meta-box.php';
    }

    /**
     * Save writing job meta data.
     */
    public function save_writing_job_meta( $post_id ): void {
        // Security checks
        if ( ! isset( $_POST['spawnster_job_meta_nonce'] ) || 
             ! wp_verify_nonce( $_POST['spawnster_job_meta_nonce'], 'spawnster_job_meta' ) ) {
            return;
        }
        
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }
        
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }
        
        if ( 'spawnster_job' !== $_POST['post_type'] ) {
            return;
        }
        
        // Save meta data
        if ( isset( $_POST['specificTopic'] ) ) {
            update_post_meta( $post_id, 'specificTopic', sanitize_text_field( $_POST['specificTopic'] ) );
        }
        if ( isset( $_POST['topicCategory'] ) ) {
            update_post_meta( $post_id, 'topicCategory', (int) $_POST['topicCategory'] );
        }
        if ( isset( $_POST['wordCountGoal'] ) ) {
            update_post_meta( $post_id, 'wordCountGoal', (int) $_POST['wordCountGoal'] );
        }
        if ( isset( $_POST['pastArticles'] ) ) {
            update_post_meta( $post_id, 'pastArticles', (int) $_POST['pastArticles'] );
        }
        
        // Handle checkboxes properly - they only exist in $_POST when checked
        update_post_meta( $post_id, 'repeat', isset( $_POST['repeat'] ) ? true : false );
        update_post_meta( $post_id, 'notifyAdmin', isset( $_POST['notifyAdmin'] ) ? true : false );
        
        if ( isset( $_POST['repeatType'] ) ) {
            update_post_meta( $post_id, 'repeatType', sanitize_text_field( $_POST['repeatType'] ) );
        }
        if ( isset( $_POST['delayPublish'] ) ) {
            update_post_meta( $post_id, 'delayPublish', (int) $_POST['delayPublish'] );
        }
        
        // Handle scheduling updates - wrap in try-catch to prevent fatal errors
        try {
            if ( class_exists( '\RistrettoApps\Spawnster\Services\ScheduledContentService' ) ) {
                $scheduled_content_service = new \RistrettoApps\Spawnster\Services\ScheduledContentService(
                    new \RistrettoApps\Spawnster\Services\OpenAiService(),
                    new \RistrettoApps\Spawnster\Services\ContentResearchService(
                        new \RistrettoApps\Spawnster\Services\GoogleSearchService(),
                        new \RistrettoApps\Spawnster\Services\OpenAiService()
                    ),
                    new \RistrettoApps\Spawnster\Services\PostVectorTableService()
                );
                
                $scheduled_content_service->clear_scheduled_job( $post_id );
                
                // Check if repeat is enabled for scheduling
                $repeat_enabled = isset( $_POST['repeat'] ) ? true : false;
                if ( $repeat_enabled ) {
                    $repeat_type = sanitize_text_field( $_POST['repeatType'] );
                    $delay_publish = (int) $_POST['delayPublish'];
                    $scheduled_content_service->schedule_job( $post_id, $repeat_type, $delay_publish );
                }
            }
        } catch ( Exception $e ) {
            // Log error but don't break the save process
            error_log( 'Spawnster: Error updating scheduled job: ' . $e->getMessage() );
        }
    }

    /**
     * Add custom columns for writing jobs list.
     */
    public function add_writing_job_columns( array $columns ): array {
        $new_columns = array();
        $new_columns['cb'] = $columns['cb'];
        $new_columns['title'] = $columns['title'];
        $new_columns['topic'] = __( 'Topic', 'spawnster' );
        $new_columns['category'] = __( 'Category', 'spawnster' );
        $new_columns['schedule'] = __( 'Schedule', 'spawnster' );
        $new_columns['last_generated'] = __( 'Last Generated', 'spawnster' );
        $new_columns['author'] = $columns['author'];
        $new_columns['date'] = $columns['date'];
        
        return $new_columns;
    }

    /**
     * Display custom column content.
     */
    public function display_writing_job_columns( string $column, int $post_id ): void {
        switch ( $column ) {
            case 'topic':
                $topic = get_post_meta( $post_id, 'specificTopic', true );
                echo esc_html( $topic ?: '—' );
                break;
                
            case 'category':
                $category_id = get_post_meta( $post_id, 'topicCategory', true );
                if ( $category_id ) {
                    $category = get_term( $category_id, 'category' );
                    echo esc_html( $category ? $category->name : '—' );
                } else {
                    echo '—';
                }
                break;
                
            case 'schedule':
                $repeat = get_post_meta( $post_id, 'repeat', true );
                if ( $repeat ) {
                    $repeat_type = get_post_meta( $post_id, 'repeatType', true );
                    echo esc_html( ucfirst( $repeat_type ) );
                } else {
                    echo __( 'Manual', 'spawnster' );
                }
                break;
                
            case 'last_generated':
                $last_generated = get_post_meta( $post_id, 'last_generated', true );
                if ( $last_generated ) {
                    echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $last_generated ) ) );
                } else {
                    echo '—';
                }
                break;
        }
    }

    /**
     * Display the content for the jobs settings page.
     */
    public function jobs_settings_page_content(): void {
        // Save settings if form is submitted
        if ( isset( $_POST['submit'] ) && wp_verify_nonce( $_POST['spawnster_nonce'], 'spawnster_nonce' ) ) {
            $settings = array(
                'spawnster_google_api_key' => sanitize_text_field( $_POST['spawnster_google_api_key'] ),
                'spawnster_google_search_engine_id' => sanitize_text_field( $_POST['spawnster_google_search_engine_id'] ),
            );
            
            update_option( 'spawnster_settings', $settings );
            echo '<div class="notice notice-success"><p>' . __( 'Settings saved successfully!', 'spawnster' ) . '</p></div>';
        }

        $current_settings = get_option( 'spawnster_settings', array() );
        ?>
        <div class="wrap">
            <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
            
            <form method="post" action="">
                <?php wp_nonce_field( 'spawnster_nonce', 'spawnster_nonce' ); ?>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="spawnster_google_api_key"><?php _e( 'Google API Key', 'spawnster' ); ?></label>
                        </th>
                        <td>
                            <input type="text" id="spawnster_google_api_key" name="spawnster_google_api_key" 
                                   class="regular-text" value="<?php echo esc_attr( $current_settings['spawnster_google_api_key'] ?? '' ); ?>">
                            <p class="description"><?php _e( 'Enter your Google Custom Search API key.', 'spawnster' ); ?></p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="spawnster_google_search_engine_id"><?php _e( 'Search Engine ID', 'spawnster' ); ?></label>
                        </th>
                        <td>
                            <input type="text" id="spawnster_google_search_engine_id" name="spawnster_google_search_engine_id" 
                                   class="regular-text" value="<?php echo esc_attr( $current_settings['spawnster_google_search_engine_id'] ?? '' ); ?>">
                            <p class="description"><?php _e( 'Enter your Google Custom Search Engine ID.', 'spawnster' ); ?></p>
                        </td>
                    </tr>
                </table>
                
                <p class="submit">
                    <input type="submit" name="submit" class="button button-primary" value="<?php _e( 'Save Settings', 'spawnster' ); ?>">
                </p>
            </form>
        </div>
        <?php
    }

    /**
     * Add custom styles for writing job meta boxes.
     */
    public function add_writing_job_admin_styles(): void {
        $screen = get_current_screen();
        if ( $screen && $screen->post_type === 'spawnster_job' ) {
            echo '<style>
                .repeat-options {
                    background-color: #f9f9f9;
                }
                .form-table th {
                    width: 200px;
                }
            </style>';
        }
    }
}