<?php

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

/**
 * Coerce a value that may be ID / post / array into an integer post ID.
 */
if ( ! function_exists( 'reeid_coerce_post_id' ) ) {
    function reeid_coerce_post_id( $maybe_post ) {

        if ( is_object( $maybe_post ) ) {
            if ( isset( $maybe_post->ID ) ) {
                return (int) $maybe_post->ID;
            }
            return (int) $maybe_post;
        }

        if ( is_array( $maybe_post ) && isset( $maybe_post['ID'] ) ) {
            return (int) $maybe_post['ID'];
        }

        return (int) $maybe_post;
    }
}

/**
 * Resolve authoritative source editor for translation.
 *
 * Policy:
 * - authoritative by default via _reeid_source_editor
 * - if missing, detect live editor and store it
 * - if mismatch, keep stored origin and log it
 *
 * Allowed values are intentionally narrow for future extensibility.
 *
 * @param mixed $post_or_id Post object, array, or ID.
 * @return string One of: gutenberg, classic.
 **/

if ( ! function_exists( 'reeid_resolve_source_editor' ) ) {
    function reeid_resolve_source_editor( $post_or_id ) {

        $post_id = reeid_coerce_post_id( $post_or_id );
        if ( $post_id <= 0 ) {
            return 'classic';
        }

        $allowed = array( 'gutenberg', 'classic' );
        $stored = get_post_meta( $post_id, '_reeid_source_editor', true );
        $stored = is_string( $stored ) ? sanitize_key( $stored ) : '';

        $live = function_exists( 'reeid_detect_editor_type' )
            ? reeid_detect_editor_type( $post_id )
            : 'classic';

        $live = in_array( $live, $allowed, true ) ? $live : 'classic';

        if ( in_array( $stored, $allowed, true ) ) {
            if ( $stored !== $live && function_exists( 'reeid_debug_log' ) ) {
                reeid_debug_log(
                    'EDITOR_ORIGIN_MISMATCH',
                    array(
                        'post_id' => $post_id,
                        'stored'  => $stored,
                        'live'    => $live,
                    )
                );
            }
            return $stored;
        }

        update_post_meta( $post_id, '_reeid_source_editor', $live );

        return $live;
    }
}

/**
 * Detect editor type: gutenberg / classic. 
 **/

 if ( ! function_exists( 'reeid_detect_editor_type' ) ) {
    function reeid_detect_editor_type( $post_or_id ) {

        $post_id = reeid_coerce_post_id( $post_or_id );
        if ( $post_id <= 0 ) {
            return 'classic';
        }

               $edit_mode = '';
        $has_data  = null;

        $panels_data = get_post_meta( $post_id, 'panels_data', true );
        if ( is_array( $panels_data ) && ! empty( $panels_data ) ) {
            return 'classic';
        }

        $post = get_post( $post_id );
        if ( $post && function_exists( 'has_blocks' ) && has_blocks( $post->post_content ) ) {
            return 'gutenberg';
        }

        return 'classic';
    }
}
