<?php
/**
 * Gutenberg block editor support
 */

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

class BW_Expiry_Gutenberg {

    private static $instance = null;

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

    /**
     * Track which post types we've registered meta for
     */
    private $registered_meta_types = array();

    private function __construct() {
        add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_editor_assets' ) );

        // Register meta for existing post types
        $this->register_meta();

        // Also register meta for post types registered after us (e.g., from other plugins)
        add_action( 'registered_post_type', array( $this, 'register_meta_for_post_type' ), 10, 2 );
    }

    /**
     * Register post meta for REST API access
     *
     * Note: Meta is registered for ALL public post types so the data can be saved
     * via Gutenberg/REST API. The actual expiry functionality (columns, cron)
     * only applies to post types enabled in settings.
     */
    public function register_meta() {
        // Get all public post types that support the editor
        $post_types = get_post_types( array( 'public' => true, 'show_in_rest' => true ), 'names' );

        // Remove attachment
        unset( $post_types['attachment'] );

        foreach ( $post_types as $post_type ) {
            $this->register_meta_for_single_type( $post_type );
        }
    }

    /**
     * Register meta for a single post type (called when post type is registered)
     */
    public function register_meta_for_post_type( $post_type, $post_type_object ) {
        // Only register for public post types with REST support
        if ( ! $post_type_object->public || ! $post_type_object->show_in_rest ) {
            return;
        }

        // Skip attachment
        if ( 'attachment' === $post_type ) {
            return;
        }

        $this->register_meta_for_single_type( $post_type );
    }

    /**
     * Register meta fields for a single post type
     */
    private function register_meta_for_single_type( $post_type ) {
        // Skip if already registered
        if ( in_array( $post_type, $this->registered_meta_types, true ) ) {
            return;
        }

        $this->registered_meta_types[] = $post_type;

        register_post_meta( $post_type, '_bw_expiry_date', array(
            'show_in_rest'      => true,
            'single'            => true,
            'type'              => 'string',
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => function() {
                return current_user_can( 'edit_posts' );
            },
        ) );

        register_post_meta( $post_type, '_bw_expired', array(
            'show_in_rest'      => true,
            'single'            => true,
            'type'              => 'boolean',
            'default'           => false,
            'sanitize_callback' => 'rest_sanitize_boolean',
            'auth_callback'     => function() {
                return current_user_can( 'edit_posts' );
            },
        ) );
    }

    /**
     * Enqueue block editor assets
     */
    public function enqueue_editor_assets() {
        global $post;

        // Check if current post type is enabled
        if ( ! isset( $post ) ) {
            return;
        }

        $plugin = BW_Expiry_Post::get_instance();
        if ( ! $plugin->is_post_type_enabled( $post->post_type ) ) {
            return;
        }

        // Enqueue the Gutenberg panel script
        wp_enqueue_script(
            'bw-expiry-gutenberg',
            BW_EXPIRY_PLUGIN_URL . 'assets/js/gutenberg-panel.js',
            array(
                'wp-plugins',
                'wp-edit-post',
                'wp-element',
                'wp-components',
                'wp-data',
                'wp-i18n',
            ),
            BW_EXPIRY_VERSION,
            true
        );

        // Pass data to script
        wp_localize_script( 'bw-expiry-gutenberg', 'bwExpiryData', array(
            'metaKey'    => '_bw_expiry_date',
            'expiredKey' => '_bw_expired',
            'labels'     => array(
                'panelTitle'       => __( 'Post Expiry', 'bw-expiry-post' ),
                'dateLabel'        => __( 'Expires on', 'bw-expiry-post' ),
                'neverExpires'     => __( 'Never expires', 'bw-expiry-post' ),
                'neverExpiresHelp' => __( 'This post will remain published indefinitely.', 'bw-expiry-post' ),
                'helpText'         => __( 'Post will be set to Draft when this date is reached.', 'bw-expiry-post' ),
                'expiredMsg'       => __( 'This post was automatically unpublished due to expiry.', 'bw-expiry-post' ),
                'selectDate'       => __( 'Select a date', 'bw-expiry-post' ),
            ),
        ) );
    }
}
