<?php
/**
 * Dakidarts Numerology Core - Gutenberg Blocks
 *
 * Registers Gutenberg blocks for Numerology forms with live preview.
 *
 * @package Dakidarts_Numerology_Core
 */

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

class Dakidarts_Blocks {

    public function __construct() {
        // Register Gutenberg blocks
        add_action( 'init', [ $this, 'register_blocks' ] );

        // Enqueue block editor assets
        add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_block_assets' ] );

        // Enqueue front-end assets
        add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_block_assets' ] );

        // AJAX calculation for live preview & front-end
        add_action( 'wp_ajax_dakidarts_block_calculate', [ $this, 'ajax_calculate' ] );
        add_action( 'wp_ajax_nopriv_dakidarts_block_calculate', [ $this, 'ajax_calculate' ] );

        // Register custom block category
        add_filter( 'block_categories_all', [ $this, 'register_block_category' ], 10, 2 );
    }

    /**
     * Register custom Gutenberg block category
     */
    public function register_block_category( $categories, $post ) {
        return array_merge(
            $categories,
            [
                [
                    'slug'  => 'dakidarts',
                    'title' => __( 'Dakidarts', 'dakidarts-numerology-core' ),
                    'icon'  => null,
                ],
            ]
        );
    }

    /**
     * Register the Numerology block
     */
    public function register_blocks() {
        if ( ! function_exists( 'register_block_type' ) ) return;

        register_block_type(
            'dakidarts/numerology',
            [
                'editor_script'   => 'dakidarts-blocks-js',
                'editor_style'    => 'dakidarts-blocks-css',
                'render_callback' => [ $this, 'render_block' ],
                'attributes'      => [
                    'endpoint' => [
                        'type'    => 'string',
                        'default' => 'life-path',
                    ],
                    'template' => [
                        'type'    => 'string',
                        'default' => 'default',
                    ],
                ],
            ]
        );
    }



    /**
     * Enqueue block editor & front-end JS/CSS
     */
    public function enqueue_block_assets() {
        $handle_js  = 'dakidarts-blocks-js';
        $handle_css = 'dakidarts-blocks-css';

        $js_file  = DAKIDARTS_PLUGIN_PATH . 'assets/js/blocks.js';
        $css_file = DAKIDARTS_PLUGIN_PATH . 'assets/css/admin.css';

        wp_enqueue_script(
            $handle_js,
            DAKIDARTS_PLUGIN_URL . 'assets/js/blocks.js',
            [ 'wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'jquery' ],
            file_exists( $js_file ) ? filemtime( $js_file ) : false,
            true
        );

        wp_enqueue_style(
            $handle_css,
            DAKIDARTS_PLUGIN_URL . 'assets/css/admin.css',
            [],
            file_exists( $css_file ) ? filemtime( $css_file ) : false
        );
        

        // Localize script for front-end & editor
        $styles = wp_parse_args( get_option( 'dakidarts_numerology_style_settings', [] ), [
            'form_bg' => '#fff',
            'form_padding' => '10px',
            'form_margin' => '0',
            'form_radius' => '8px',
            'button_bg' => '#0073aa',
            'button_color' => '#fff',
            'button_padding' => '10px 20px',
            'button_border_width' => '1',
            'button_border_style' => 'solid',
            'button_border_color' => '#0073aa',
            'button_radius' => '4px',
            'calculate_text' => __( 'Calculate', 'dakidarts-numerology-core' ),
            'try_again_text' => __( 'Try Again', 'dakidarts-numerology-core' ),
            'button_position' => 'inherit'
        ] );

        $endpoints_with_desc = array_map(function($ep) {
            return [
                'params'     => $ep['params'],
                'param_desc' => $ep['param_desc'] ?? [],
                'label'      => $ep['label']
            ];
        }, Dakidarts_API::get_endpoints() );

        wp_localize_script( $handle_js, 'dakidarts_block_settings', [
            'styles'     => $styles,
            'endpoints'  => $endpoints_with_desc,
            'ajax_url'   => admin_url( 'admin-ajax.php' ),
            'nonce'      => wp_create_nonce( 'dakidarts_block_nonce' ),
            'fixed_content'      => trailingslashit( DAKIDARTS_PLUGIN_PATH ) . 'assets/images/block-preview.jpg',
            'i18n'       => [
                'select_true_false' => __( 'Please choose True or False.', 'dakidarts-numerology-core' ),
                'expanded_help'     => __( 'Tip: expanded=true returns full cycles and detailed meanings. expanded=false keeps output brief.', 'dakidarts-numerology-core' ),
                'allow_masters_help' => __( 'Tip: allow_masters is reserved for future master-number support. Keep false for now.', 'dakidarts-numerology-core' ),
            ],
            'plugin_url' => DAKIDARTS_PLUGIN_URL
        ] );
    }

    /**
     * Get saved styles
     */
    private function get_styles() {
        return get_option( 'dakidarts_numerology_style_settings', [] );
    }

    /**
     * Render block on frontend
     */
    public function render_block( $attributes ) {
        $endpoint = isset( $attributes['endpoint'] ) ? sanitize_key( $attributes['endpoint'] ) : 'life-path';
        $template = isset( $attributes['template'] ) ? sanitize_key( $attributes['template'] ) : 'default';

        $endpoints = Dakidarts_API::get_endpoints();
        if ( ! isset( $endpoints[ $endpoint ] ) ) {
            return '<p>' . esc_html__( 'Invalid Numerology endpoint.', 'dakidarts-numerology-core' ) . '</p>';
        }

        $params     = $endpoints[ $endpoint ]['params'] ?? [];
        $param_desc = $endpoints[ $endpoint ]['param_desc'] ?? [];
        $required_params = isset( $endpoints[ $endpoint ]['required'] ) && is_array( $endpoints[ $endpoint ]['required'] )
            ? $endpoints[ $endpoint ]['required']
            : $params;

        $styles = wp_parse_args( $this->get_styles(), [
            'form_bg'        => '#fff',
            'form_padding'   => '10px',
            'form_margin'    => '0',
            'form_radius'    => '8px',
            'button_bg'      => '#0073aa',
            'button_color'   => '#fff',
            'button_padding' => '10px 20px',
            'button_border'  => '1px solid #0073aa',
            'calculate_text' => __( 'Calculate', 'dakidarts-numerology-core' ),
        ] );

        $form_style = sprintf(
            'background:%s;padding:%s;margin:%s;border-radius:%s;',
            esc_attr( $styles['form_bg'] ),
            esc_attr( $styles['form_padding'] ),
            esc_attr( $styles['form_margin'] ),
            esc_attr( $styles['form_radius'] )
        );

        ob_start();
        $is_compatibility = $endpoint === 'compatibility-score';
        ?>
        <div class="dakidarts-block dakidarts-block-<?php echo esc_attr( $template ); ?>"
             style="<?php echo esc_attr( $form_style ); ?>"
             data-endpoint="<?php echo esc_attr( $endpoint ); ?>"
             data-params='<?php echo wp_json_encode( $params ); ?>'>
            <form class="dakidarts-block-form">
                <?php
                $render_field = function( $param ) use ( $param_desc, $required_params ) {
                    $required = in_array( $param, $required_params, true );
                    ?>
                    <p>
                        <label><?php echo esc_html( ucfirst( str_replace( '_', ' ', $param ) ) ); ?><?php echo $required ? ':' : ' (' . esc_html__( 'optional', 'dakidarts-numerology-core' ) . '):'; ?></label>
                        <?php if ( in_array( $param, [ 'reduce', 'include_gaps', 'expanded', 'allow_masters' ], true ) ) : ?>
                            <select name="<?php echo esc_attr( $param ); ?>" <?php echo $required ? 'required' : ''; ?>>
                                <option value=""><?php esc_html_e( 'Select', 'dakidarts-numerology-core' ); ?></option>
                                <option value="true"><?php esc_html_e( 'True', 'dakidarts-numerology-core' ); ?></option>
                                <option value="false"><?php esc_html_e( 'False', 'dakidarts-numerology-core' ); ?></option>
                            </select>
                            <?php if ( $param === 'expanded' ) : ?>
                                <small class="dakidarts-param-tip" style="display:block;font-style:italic;color:#555;">
                                    <span class="dakidarts-info-dot">i</span>
                                    <?php esc_html_e( 'Tip: expanded=true returns full cycles and detailed meanings. expanded=false keeps output brief.', 'dakidarts-numerology-core' ); ?>
                                </small>
                            <?php endif; ?>
                            <?php if ( $param === 'allow_masters' ) : ?>
                                <small class="dakidarts-param-tip" style="display:block;font-style:italic;color:#555;">
                                    <span class="dakidarts-info-dot">i</span>
                                    <?php esc_html_e( 'Tip: allow_masters is reserved for future master-number support. Keep false for now.', 'dakidarts-numerology-core' ); ?>
                                </small>
                            <?php endif; ?>
                        <?php else : ?>
                            <input type="text" name="<?php echo esc_attr( $param ); ?>" value="" <?php echo $required ? 'required' : ''; ?> />
                        <?php endif; ?>
                        <?php if ( ! empty( $param_desc[ $param ] ) ) : ?>
                            <small style="display:block;font-style:italic;color:#555;">
                                <?php echo esc_html( $param_desc[ $param ] ); ?>
                            </small>
                        <?php endif; ?>
                    </p>
                    <?php
                };

                if ( $is_compatibility ) {
                    $person1 = array_filter( $params, fn( $p ) => str_ends_with( $p, '_1' ) );
                    $person2 = array_filter( $params, fn( $p ) => str_ends_with( $p, '_2' ) );
                    ?>
                    <div class="dakidarts-compatibility-grid">
                        <div class="dakidarts-compatibility-card">
                            <h3><?php esc_html_e( 'Person 1', 'dakidarts-numerology-core' ); ?></h3>
                            <?php foreach ( $person1 as $param ) { $render_field( $param ); } ?>
                        </div>
                        <div class="dakidarts-compatibility-card">
                            <h3><?php esc_html_e( 'Person 2', 'dakidarts-numerology-core' ); ?></h3>
                            <?php foreach ( $person2 as $param ) { $render_field( $param ); } ?>
                        </div>
                    </div>
                    <?php
                } else {
                    foreach ( $params as $param ) { $render_field( $param ); }
                }
                ?>
                <button type="submit" class="dakidarts-block-submit"
                        style="background:<?php echo esc_attr( $styles['button_bg'] ); ?>;
                               color:<?php echo esc_attr( $styles['button_color'] ); ?>;
                               padding:<?php echo esc_attr( $styles['button_padding'] ); ?>;
                               border:<?php echo esc_attr( $styles['button_border'] ); ?>;">
                    <?php echo esc_html( $styles['calculate_text'] ); ?>
                </button>
            </form>
            <div class="dakidarts-block-result"></div>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Handle AJAX calculation for live preview & front-end
     */
    public function ajax_calculate() {
        check_ajax_referer( 'dakidarts_block_nonce', 'nonce' );

        $endpoint = isset( $_POST['endpoint'] ) ? sanitize_key( wp_unslash( $_POST['endpoint'] ) ) : '';
        $params_raw = filter_input( INPUT_POST, 'params', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
        $params = [];

        if ( is_array( $params_raw ) ) {
            foreach ( $params_raw as $key => $value ) {
                $params[ sanitize_key( $key ) ] = sanitize_text_field( $value );
            }
        }

        foreach ( [ 'reduce', 'include_gaps', 'expanded', 'allow_masters' ] as $bool_param ) {
            if ( isset( $params[ $bool_param ] ) ) {
                $params[ $bool_param ] = in_array( strtolower( (string) $params[ $bool_param ] ), [ 'true', 'false' ], true )
                    ? strtolower( (string) $params[ $bool_param ] )
                    : 'false';
            }
        }

        $required_params = Dakidarts_API::get_endpoints()[ $endpoint ]['params'] ?? [];
        foreach ( $required_params as $param ) {
            if ( empty( $params[ $param ] ) ) {
                wp_send_json_error( "Missing required parameter: $param" );
            }
        }

        $response = Dakidarts_API::request( $endpoint, $params );

        if ( is_wp_error( $response ) ) {
            wp_send_json_error( $response->get_error_message() );
        }

        // Render result using your template
        $html_output = Dakidarts_Render::render_result( $response, 'default', $endpoint );

        wp_send_json_success( ['output' => $html_output] );
    }

}
