<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class IDVE_Core {

    private static $instance = null;
    public $blocks;
    public $renderer;
    public $css_generator;
    public $editor;
    public $frontend;
    public $rest_api;
    public $importer;
    public $ai;

    public static function instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        $this->load_includes();
        $this->init_components();
        $this->register_hooks();
    }

    private function load_includes() {
        $dir = IDVE_PLUGIN_DIR . 'includes/';
        require_once $dir . 'class-idve-blocks.php';
        require_once $dir . 'class-idve-renderer.php';
        require_once $dir . 'class-idve-css-generator.php';
        require_once $dir . 'class-idve-editor.php';
        require_once $dir . 'class-idve-frontend.php';
        require_once $dir . 'class-idve-rest-api.php';
        require_once $dir . 'class-idve-importer.php';
        require_once $dir . 'class-idve-ai.php';
    }

    private function init_components() {
        $this->blocks        = new IDVE_Blocks();
        $this->renderer      = new IDVE_Renderer( $this->blocks );
        $this->css_generator = new IDVE_CSS_Generator();
        $this->importer      = new IDVE_Importer( $this->blocks );

        // AI is a Pro feature.
        if ( idve_is_pro() ) {
            $ai_settings = get_option( 'idve_ai_settings', array() );
            $this->ai    = new IDVE_AI( $ai_settings, $this->blocks );
        }

        $this->editor        = new IDVE_Editor( $this->blocks );
        $this->frontend      = new IDVE_Frontend();
        $this->rest_api      = new IDVE_REST_API( $this->blocks, $this->renderer, $this->css_generator, $this->importer, $this->ai );

        do_action( 'idve_register_blocks', $this->blocks );
    }

    private function register_hooks() {
        add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'admin_init', array( $this, 'handle_export_styles' ) );
        add_action( 'save_post', array( $this, 'save_revision_meta' ), 10, 2 );
        add_action( 'wp_restore_post_revision', array( $this, 'restore_revision_meta' ), 10, 2 );
    }

    public function get_supported_post_types() {
        $settings = get_option( 'idve_settings', array() );
        $types    = isset( $settings['post_types'] ) ? $settings['post_types'] : array( 'post', 'page' );
        return apply_filters( 'idve_supported_post_types', $types );
    }

    public function add_settings_page() {
        add_options_page(
            __( 'ID Visual Editor Settings', 'insight-dezign-visual-editor' ),
            __( 'ID Visual Editor', 'insight-dezign-visual-editor' ),
            'manage_options',
            'idve-settings',
            array( $this, 'render_settings_page' )
        );
    }

    public function register_settings() {
        register_setting( 'idve_settings_group', 'idve_settings', array(
            'sanitize_callback' => array( $this, 'sanitize_settings' ),
        ) );

        if ( idve_is_pro() ) {
            register_setting( 'idve_ai_settings_group', 'idve_ai_settings', array(
                'sanitize_callback' => array( $this, 'sanitize_ai_settings' ),
            ) );
        }
    }

    public function sanitize_settings( $input ) {
        $sanitized = array();
        $sanitized['post_types'] = isset( $input['post_types'] ) && is_array( $input['post_types'] )
            ? array_map( 'sanitize_key', $input['post_types'] )
            : array();
        return $sanitized;
    }

    public function sanitize_ai_settings( $input ) {
        $sanitized = array();
        $allowed_providers = array( 'openai', 'anthropic' );
        $sanitized['provider'] = isset( $input['provider'] ) && in_array( $input['provider'], $allowed_providers, true )
            ? $input['provider']
            : 'openai';
        $sanitized['api_key']       = isset( $input['api_key'] ) ? sanitize_text_field( $input['api_key'] ) : '';
        $sanitized['model']         = isset( $input['model'] ) ? sanitize_text_field( $input['model'] ) : '';
        $sanitized['custom_prompt'] = isset( $input['custom_prompt'] ) ? sanitize_textarea_field( $input['custom_prompt'] ) : '';
        return $sanitized;
    }

    public static function write_global_styles_file( $css ) {
        $upload_dir = wp_upload_dir();
        $file_path  = $upload_dir['basedir'] . '/idve-global-styles.css';

        if ( empty( $css ) ) {
            if ( file_exists( $file_path ) ) {
                wp_delete_file( $file_path );
            }
            return true;
        }

        $result = file_put_contents( $file_path, $css );
        return false !== $result;
    }

    public function handle_export_styles() {
        if ( ! isset( $_POST['idve_export_styles'] ) ) {
            return;
        }
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }
        if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'idve_export_styles' ) ) {
            return;
        }

        $css = get_option( 'idve_global_styles', '' );
        self::write_global_styles_file( $css );
        set_transient( 'idve_export_success', true, 30 );

        wp_safe_redirect( admin_url( 'options-general.php?page=idve-settings' ) );
        exit;
    }

    public function render_settings_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }
        $settings   = get_option( 'idve_settings', array( 'post_types' => array( 'post', 'page' ) ) );
        $enabled    = isset( $settings['post_types'] ) ? $settings['post_types'] : array();
        $post_types = get_post_types( array( 'public' => true ), 'objects' );
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'Insight Dezign Visual Editor Settings', 'insight-dezign-visual-editor' ); ?></h1>
            <form method="post" action="options.php">
                <?php settings_fields( 'idve_settings_group' ); ?>
                <table class="form-table">
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Enabled Post Types', 'insight-dezign-visual-editor' ); ?></th>
                        <td>
                            <?php foreach ( $post_types as $pt ) : ?>
                                <label style="display:block;margin-bottom:6px;">
                                    <input type="checkbox"
                                           name="idve_settings[post_types][]"
                                           value="<?php echo esc_attr( $pt->name ); ?>"
                                           <?php checked( in_array( $pt->name, $enabled, true ) ); ?>>
                                    <?php echo esc_html( $pt->labels->singular_name ); ?>
                                </label>
                            <?php endforeach; ?>
                        </td>
                    </tr>
                </table>
                <?php submit_button(); ?>
            </form>

            <hr>
            <h2><?php esc_html_e( 'Global Styles Export', 'insight-dezign-visual-editor' ); ?></h2>
            <p><?php esc_html_e( 'Write the global stylesheet to a physical CSS file in your uploads directory. The IDVE must-use plugin will keep loading this file even if IDVE is deactivated.', 'insight-dezign-visual-editor' ); ?></p>

            <?php
            $export_success = get_transient( 'idve_export_success' );
            if ( $export_success ) :
                delete_transient( 'idve_export_success' );
                $upload_dir = wp_upload_dir();
            ?>
                <div class="notice notice-success" style="padding:10px 12px;">
                    <p><strong><?php esc_html_e( 'Global styles exported successfully.', 'insight-dezign-visual-editor' ); ?></strong></p>
                    <?php // translators: %s is the file path to the exported CSS file. ?>
                    <p><?php echo esc_html( sprintf( __( 'File: %s', 'insight-dezign-visual-editor' ), $upload_dir['basedir'] . '/idve-global-styles.css' ) ); ?></p>
                </div>
            <?php endif; ?>

            <form method="post">
                <?php wp_nonce_field( 'idve_export_styles' ); ?>
                <input type="hidden" name="idve_export_styles" value="1">
                <?php submit_button( __( 'Export Global Styles', 'insight-dezign-visual-editor' ), 'secondary', 'submit', true ); ?>
            </form>

            <hr>
            <h2><?php esc_html_e( 'AI Assistant', 'insight-dezign-visual-editor' ); ?></h2>
            <p><?php esc_html_e( 'Connect an AI provider to generate pages, add sections, edit elements, and create CSS classes from natural language prompts.', 'insight-dezign-visual-editor' ); ?></p>
            <?php if ( idve_is_pro() ) : ?>
            <?php
            $ai_settings = get_option( 'idve_ai_settings', array() );
            $ai_provider = isset( $ai_settings['provider'] ) ? $ai_settings['provider'] : 'openai';
            $ai_key      = isset( $ai_settings['api_key'] ) ? $ai_settings['api_key'] : '';
            $ai_model    = isset( $ai_settings['model'] ) ? $ai_settings['model'] : '';
            $ai_custom   = isset( $ai_settings['custom_prompt'] ) ? $ai_settings['custom_prompt'] : '';
            ?>
            <form method="post" action="options.php">
                <?php settings_fields( 'idve_ai_settings_group' ); ?>
                <table class="form-table">
                    <tr>
                        <th scope="row"><label for="idve-ai-provider"><?php esc_html_e( 'Provider', 'insight-dezign-visual-editor' ); ?></label></th>
                        <td>
                            <select id="idve-ai-provider" name="idve_ai_settings[provider]">
                                <option value="openai" <?php selected( $ai_provider, 'openai' ); ?>>OpenAI</option>
                                <option value="anthropic" <?php selected( $ai_provider, 'anthropic' ); ?>>Anthropic</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="idve-ai-key"><?php esc_html_e( 'API Key', 'insight-dezign-visual-editor' ); ?></label></th>
                        <td>
                            <div style="display:flex;gap:8px;max-width:400px;">
                                <input type="password" id="idve-ai-key" name="idve_ai_settings[api_key]" value="<?php echo esc_attr( $ai_key ); ?>" class="regular-text" autocomplete="off" />
                                <button type="button" class="button" onclick="var f=document.getElementById('idve-ai-key');f.type=f.type==='password'?'text':'password';this.textContent=f.type==='password'?'<?php echo esc_js( __( 'Show', 'insight-dezign-visual-editor' ) ); ?>':'<?php echo esc_js( __( 'Hide', 'insight-dezign-visual-editor' ) ); ?>';"><?php esc_html_e( 'Show', 'insight-dezign-visual-editor' ); ?></button>
                            </div>
                            <p class="description"><?php esc_html_e( 'Your API key is stored server-side and never exposed to the browser.', 'insight-dezign-visual-editor' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="idve-ai-model"><?php esc_html_e( 'Model', 'insight-dezign-visual-editor' ); ?></label></th>
                        <td>
                            <input type="text" id="idve-ai-model" name="idve_ai_settings[model]" value="<?php echo esc_attr( $ai_model ); ?>" class="regular-text" placeholder="<?php esc_attr_e( 'e.g. gpt-4o or claude-sonnet-4-20250514', 'insight-dezign-visual-editor' ); ?>" />
                            <p class="description"><?php esc_html_e( 'Leave blank for the default model.', 'insight-dezign-visual-editor' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="idve-ai-custom"><?php esc_html_e( 'Custom Instructions', 'insight-dezign-visual-editor' ); ?></label></th>
                        <td>
                            <textarea id="idve-ai-custom" name="idve_ai_settings[custom_prompt]" rows="4" class="large-text"><?php echo esc_textarea( $ai_custom ); ?></textarea>
                            <p class="description"><?php esc_html_e( 'Optional instructions appended to every AI prompt (e.g., brand colors, tone preferences).', 'insight-dezign-visual-editor' ); ?></p>
                        </td>
                    </tr>
                </table>
                <?php submit_button( __( 'Save AI Settings', 'insight-dezign-visual-editor' ), 'primary', 'submit-ai' ); ?>
            </form>
            <?php else : ?>
            <div class="notice notice-info inline" style="padding:12px 16px;margin:12px 0;">
                <p>
                    <strong><?php esc_html_e( 'Pro Feature', 'insight-dezign-visual-editor' ); ?></strong> &mdash;
                    <?php esc_html_e( 'The AI Assistant is available with a Pro license. Generate entire pages, add sections, edit elements, and create CSS classes using natural language prompts.', 'insight-dezign-visual-editor' ); ?>
                </p>
                <?php if ( function_exists( 'idve_fs' ) ) : ?>
                    <p><a href="<?php echo esc_url( idve_fs()->get_upgrade_url() ); ?>" class="button button-primary"><?php esc_html_e( 'Upgrade to Pro', 'insight-dezign-visual-editor' ); ?></a></p>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
        <?php
    }

    public function save_revision_meta( $post_id, $post ) {
        if ( 'revision' !== $post->post_type ) {
            return;
        }
        $parent_id = $post->post_parent;
        $idve_data = get_post_meta( $parent_id, '_idve_data', true );
        if ( $idve_data ) {
            update_metadata( 'post', $post_id, '_idve_data', $idve_data );
        }
    }

    public function restore_revision_meta( $post_id, $revision_id ) {
        $idve_data = get_metadata( 'post', $revision_id, '_idve_data', true );
        if ( $idve_data ) {
            update_post_meta( $post_id, '_idve_data', $idve_data );
        }
    }
}
