<?php
/**
 * Schemafy Gutenberg Integration Class
 *
 * Handles Gutenberg block editor sidebar panel, post meta registration,
 * and script enqueuing for the block editor
 *
 * @package Schemafy
 * @since 2.0.0
 * @author SCHEMAFY
 */

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

class SCHEMAFY_Gutenberg {

    /**
     * Database instance
     * @var SCHEMAFY_Database
     */
    private $database;

    /**
     * Supported post types
     * @var array
     */
    private $supported_post_types = array('post', 'page', 'product');

    /**
     * Post meta keys to register
     * Keys must match what class-schemafy-schema-injector.php and class-schemafy-seo-detector.php read.
     * @var array
     */
    private $meta_keys = array(
        // These are the canonical keys read by the injector
        '_schemafy_custom_meta_title' => array(
            'type'    => 'string',
            'default' => ''
        ),
        '_schemafy_custom_meta_description' => array(
            'type'    => 'string',
            'default' => ''
        ),
        '_schemafy_focus_keyword' => array(
            'type'    => 'string',
            'default' => ''
        ),
        '_schemafy_og_title' => array(
            'type'    => 'string',
            'default' => ''
        ),
        '_schemafy_og_description' => array(
            'type'    => 'string',
            'default' => ''
        ),
        '_schemafy_og_image' => array(
            'type'    => 'string',
            'default' => ''
        ),
        '_schemafy_og_type' => array(
            'type'    => 'string',
            'default' => 'website'
        ),
        '_schemafy_twitter_card' => array(
            'type'    => 'string',
            'default' => 'summary_large_image'
        ),
        '_schemafy_twitter_title' => array(
            'type'    => 'string',
            'default' => ''
        ),
        '_schemafy_twitter_description' => array(
            'type'    => 'string',
            'default' => ''
        ),
        '_schemafy_twitter_image' => array(
            'type'    => 'string',
            'default' => ''
        ),
        '_schemafy_twitter_creator' => array(
            'type'    => 'string',
            'default' => ''
        )
    );

    /**
     * Constructor
     *
     * @param SCHEMAFY_Database|null $database Database instance
     */
    public function __construct($database = null) {
        $this->database = $database;

        // Register hooks
        add_action('init', array($this, 'register_post_meta'));
        add_action('enqueue_block_editor_assets', array($this, 'enqueue_sidebar_assets'));
    }

    /**
     * Register post meta for REST API access
     */
    public function register_post_meta() {
        foreach ($this->supported_post_types as $post_type) {
            foreach ($this->meta_keys as $meta_key => $config) {
                register_post_meta($post_type, $meta_key, array(
                    'show_in_rest' => true,
                    'single' => true,
                    'type' => $config['type'],
                    'default' => $config['default'],
                    // Gate on the post being edited, not on the generic
                    // "can this user edit anything" capability. edit_post is a
                    // meta capability, so it accounts for ownership, published
                    // status and edit_others_posts; edit_posts alone is true for
                    // every contributor and says nothing about THIS post.
                    'auth_callback' => function($allowed, $meta_key, $post_id) {
                        return current_user_can('edit_post', $post_id);
                    }
                ));
            }
        }
    }

    /**
     * Enqueue Gutenberg sidebar assets
     */
    public function enqueue_sidebar_assets() {
        // Only load on supported post types
        $screen = get_current_screen();
        if (!$screen || !in_array($screen->post_type, $this->supported_post_types)) {
            return;
        }

        // Check if we're in the block editor
        if (!$screen->is_block_editor()) {
            return;
        }

        $asset_file = SCHEMAFY_PLUGIN_PATH . 'assets/js/gutenberg/schemafy-sidebar.asset.php';

        // Default dependencies if asset file doesn't exist
        $dependencies = array(
            'wp-plugins',
            'wp-edit-post',
            'wp-element',
            'wp-components',
            'wp-data',
            'wp-core-data',
            'wp-editor',
            'wp-api-fetch',
            'wp-i18n',
            'wp-url',
            'wp-notices',
            'wp-blocks'
        );
        $version = SCHEMAFY_VERSION;

        // Use generated asset file if it exists (from wp-scripts build)
        if (file_exists($asset_file)) {
            $asset = require $asset_file;
            $dependencies = $asset['dependencies'];
            $version = $asset['version'];
        }

        // Enqueue sidebar script
        wp_enqueue_script(
            'schemafy-gutenberg-sidebar',
            SCHEMAFY_PLUGIN_URL . 'assets/js/gutenberg/schemafy-sidebar.js',
            $dependencies,
            $version,
            true
        );

        // Enqueue sidebar styles
        wp_enqueue_style(
            'schemafy-gutenberg-sidebar',
            SCHEMAFY_PLUGIN_URL . 'assets/css/gutenberg-sidebar.css',
            array('wp-components'),
            SCHEMAFY_VERSION
        );

        // Get current post data
        $post_id = get_the_ID();
        $post_url = get_permalink($post_id);

        // Localize script with necessary data
        wp_localize_script('schemafy-gutenberg-sidebar', 'schemafyGutenberg', array(
            'restUrl'       => rest_url('schemafy/v1/'),
            'nonce'         => wp_create_nonce('wp_rest'),
            'postId'        => $post_id,
            'postUrl'       => $post_url ? $post_url : '',
            'siteUrl'       => home_url(),
            'siteName'      => get_bloginfo('name'),
            'pluginUrl'     => SCHEMAFY_PLUGIN_URL,
            'adminUrl'      => admin_url('admin.php?page=schemafy-custom-schema'),
            'version'       => SCHEMAFY_VERSION,
            'hasWooCommerce' => class_exists('WooCommerce'),
            // When an SEO plugin owns the meta fields its own panel is right
            // here in the same editor, so Schemafy does not draw a second copy
            // of the same two inputs. 'metaOwnerValues' keeps the Google preview
            // showing the real, shared values.
            'metaOwner'      => SCHEMAFY_Meta_Store::owner_name(),
            'metaOwnerValues' => array_combine(
                array('title', 'description'),
                SCHEMAFY_Meta_Store::get($post_id)
            ),
            'schemaTypes'   => $this->get_schema_types(),
            'i18n'          => $this->get_i18n_strings()
        ));

        // Set script translations
        wp_set_script_translations(
            'schemafy-gutenberg-sidebar',
            'schemafy',
            SCHEMAFY_PLUGIN_PATH . 'languages'
        );

    }

    /**
     * Get available schema types
     *
     * @return array Schema types with labels
     */
    private function get_schema_types() {
        return array(
            array('value' => 'Article', 'label' => 'Article', 'icon' => '📝'),
            array('value' => 'Product', 'label' => 'Product', 'icon' => '🛍️'),
            array('value' => 'LocalBusiness', 'label' => 'Local Business', 'icon' => '🏢'),
            array('value' => 'Organization', 'label' => 'Organization', 'icon' => '🏛️'),
            array('value' => 'Person', 'label' => 'Person', 'icon' => '👤'),
            array('value' => 'Event', 'label' => 'Event', 'icon' => '📅'),
            array('value' => 'Recipe', 'label' => 'Recipe', 'icon' => '🍳'),
            array('value' => 'Review', 'label' => 'Review', 'icon' => '⭐'),
            array('value' => 'FAQ', 'label' => 'FAQ', 'icon' => '❓'),
            array('value' => 'HowTo', 'label' => 'How-To', 'icon' => '📋'),
            array('value' => 'VideoObject', 'label' => 'Video', 'icon' => '🎥'),
            array('value' => 'Course', 'label' => 'Course', 'icon' => '🎓'),
            array('value' => 'JobPosting', 'label' => 'Job Posting', 'icon' => '💼'),
            array('value' => 'Service', 'label' => 'Service', 'icon' => '🔧'),
            array('value' => 'WebPage', 'label' => 'Web Page', 'icon' => '📄'),
            array('value' => 'BreadcrumbList', 'label' => 'Breadcrumb', 'icon' => '🔗')
        );
    }

    /**
     * Get i18n strings for JavaScript
     *
     * @return array Translated strings
     */
    private function get_i18n_strings() {
        return array(
            'seo' => __('SEO', 'schemafy'),
            'schema' => __('Schema', 'schemafy'),
            'focusKeyword' => __('Focus Keyword', 'schemafy'),
            'focusKeywordHelp' => __('Enter your target keyword to analyze', 'schemafy'),
            'seoScore' => __('SEO Score', 'schemafy'),
            'excellent' => __('Excellent', 'schemafy'),
            'good' => __('Good', 'schemafy'),
            'needsImprovement' => __('Needs Improvement', 'schemafy'),
            'poor' => __('Poor', 'schemafy'),
            'googlePreview' => __('Google Preview', 'schemafy'),
            'metaTitle' => __('Meta Title', 'schemafy'),
            'metaDescription' => __('Meta Description', 'schemafy'),
            'selectImage' => __('Select Image', 'schemafy'),
            'removeImage' => __('Remove Image', 'schemafy'),
            'schemas' => __('Schemas', 'schemafy'),
            'noSchemas' => __('No schemas found for this page.', 'schemafy'),
            'addSchema' => __('Add Schema', 'schemafy'),
            'editSchema' => __('Edit Schema', 'schemafy'),
            'deleteSchema' => __('Delete Schema', 'schemafy'),
            'schemaType' => __('Schema Type', 'schemafy'),
            'schemaName' => __('Schema Name', 'schemafy'),
            'active' => __('Active', 'schemafy'),
            'inactive' => __('Inactive', 'schemafy'),
            'save' => __('Save', 'schemafy'),
            'cancel' => __('Cancel', 'schemafy'),
            'update' => __('Update', 'schemafy'),
            'delete' => __('Delete', 'schemafy'),
            'confirmDelete' => __('Are you sure you want to delete this schema?', 'schemafy'),
            'saving' => __('Saving...', 'schemafy'),
            'saved' => __('Saved!', 'schemafy'),
            'error' => __('Error', 'schemafy'),
            'visualBuilder' => __('Visual Builder', 'schemafy'),
            'codeEditor' => __('Code Editor', 'schemafy'),
            'desktop' => __('Desktop', 'schemafy'),
            'mobile' => __('Mobile', 'schemafy'),
            'characters' => __('characters', 'schemafy'),
            'optimal' => __('optimal', 'schemafy'),
            'tooShort' => __('too short', 'schemafy'),
            'tooLong' => __('too long', 'schemafy')
        );
    }
}
