<?php
/**
 * Opening Screen API Endpoint
 *
 * Handles API requests for opening screen widget.
 *
 * @package BoostBot
 * @since 1.0.0
 */

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

/**
 * Class BoostBot_Opening_Screen_Endpoint
 *
 * REST API endpoint for opening screen operations.
 */
class BoostBot_Opening_Screen_Endpoint extends BoostBot_Base_Endpoint {

    /**
     * Register routes.
     *
     * @since 1.0.0
     */
    public function register() {
        // Get opening screen data for a bot/widget
        register_rest_route(
            $this->namespace,
            '/opening-screen/(?P<bot_id>\d+)',
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_opening_data' ),
                'permission_callback' => array( $this, 'public_with_api_rate_limit' ), // Passive opening-screen bootstrap read
                'args'                => array(
                    'bot_id' => array(
                        'required'          => true,
                        'type'              => 'integer',
                        'sanitize_callback' => 'absint',
                    ),
                ),
            )
        );

        // Handle question click (Mode 1)
        register_rest_route(
            $this->namespace,
            '/opening-screen/question-click',
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'handle_question_click' ),
                'permission_callback' => array( $this, 'public_with_rate_limit' ),
                'args'                => array(
                    'widget_id'    => array(
                        'required' => true,
                        'type'     => 'integer',
                    ),
                    'question_idx' => array(
                        'required' => true,
                        'type'     => 'integer',
                    ),
                ),
            )
        );

        // Handle Q&A click (Mode 2)
        register_rest_route(
            $this->namespace,
            '/opening-screen/qa-click',
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'handle_qa_click' ),
                'permission_callback' => array( $this, 'public_with_rate_limit' ),
                'args'                => array(
                    'widget_id' => array(
                        'required' => true,
                        'type'     => 'integer',
                    ),
                    'qa_idx'    => array(
                        'required' => true,
                        'type'     => 'integer',
                    ),
                ),
            )
        );

        // Admin: Save opening screen settings
        register_rest_route(
            $this->namespace,
            '/opening-screen/settings',
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'save_settings' ),
                'permission_callback' => array( $this, 'admin_access' ),
                'args'                => array(
                    'bot_id'   => array(
                        'required' => true,
                        'type'     => 'integer',
                    ),
                    'settings' => array(
                        'required' => true,
                        'type'     => 'object',
                    ),
                ),
            )
        );

        // Admin: Get available modes
        register_rest_route(
            $this->namespace,
            '/opening-screen/modes',
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_modes' ),
                'permission_callback' => array( $this, 'admin_access' ),
            )
        );
    }

    /**
     * Get opening screen data for chat display.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response
     */
    public function get_opening_data( WP_REST_Request $request ) {
        $bot_id = $request->get_param( 'bot_id' );

        // First, check if bot has an opening screen preset
        $bot_model = new BoostBot_Bot_Model();
        $bot = $bot_model->get( $bot_id );
        
        if ( $bot && ! empty( $bot->opening_screen_preset_id ) ) {
            // Bot-level overrides take precedence over preset values (admin "disconnect to independent editing").
            $opening_overrides = isset( $bot->opening_screen_overrides ) ? $bot->opening_screen_overrides : null;
            if ( is_string( $opening_overrides ) ) {
                $opening_overrides = json_decode( $opening_overrides, true );
            }
            if ( ! is_array( $opening_overrides ) ) {
                $opening_overrides = array();
            }

            // Get preset data
            $preset_model = new BoostBot_Opening_Screen_Preset_Model();
            $preset = $preset_model->get( $bot->opening_screen_preset_id );
            
            if ( $preset ) {
                $data = $this->format_preset_data( $preset );
                // Merge in overrides (if any)
                if ( ! empty( $opening_overrides ) ) {
                    if ( isset( $opening_overrides['attached_files'] ) && ! isset( $opening_overrides['files'] ) ) {
                        $opening_overrides['files'] = $opening_overrides['attached_files'];
                    }
                    $data = array_merge( $data, $opening_overrides );
                }
                return $this->success( array(
                    'has_opening_screen' => true,
                    'preset_id'          => $preset->id,
                    'data'               => $data,
                ) );
            }
        }

        // Fallback: Get bot's opening screen widget (legacy support)
        $widget_model = new BoostBot_Widget_Model();
        $widgets      = $widget_model->get_by_bot( $bot_id );

        // Find opening screen widget
        $opening_widget = null;
        foreach ( $widgets as $widget ) {
            if ( 'opening_screen' === $widget->widget_type ) {
                $opening_widget = $widget;
                break;
            }
        }

        if ( ! $opening_widget ) {
            return $this->success( array(
                'has_opening_screen' => false,
            ) );
        }

        // Get opening data using widget class
        $widget_class = new BoostBot_Opening_Screen_Widget();
        $data         = $widget_class->get_opening_data( $opening_widget->id );

        return $this->success( array(
            'has_opening_screen' => true,
            'widget_id'          => $opening_widget->id,
            'data'               => $data,
        ) );
    }

    /**
     * Format preset data for frontend consumption.
     *
     * @param object $preset Preset object.
     * @return array Formatted data.
     */
    private function format_preset_data( $preset ) {
        $data = array(
            'mode'         => $preset->mode,
            'show_welcome' => (bool) $preset->show_welcome,
            'welcome_text' => $preset->welcome_text,
        );

        switch ( $preset->mode ) {
            case 'questions_ai':
                $questions = $preset->questions;
                if ( is_string( $questions ) ) {
                    $questions = json_decode( $questions, true );
                }
                $data['questions'] = $questions ?: array();
                $data['ai_instructions'] = $preset->ai_instructions;
                break;

            case 'questions_answers':
                $qa_pairs = $preset->qa_pairs;
                if ( is_string( $qa_pairs ) ) {
                    $qa_pairs = json_decode( $qa_pairs, true );
                }
                $data['qa_pairs'] = $qa_pairs ?: array();
                break;

            case 'departments':
                $data['contact_list_id'] = $preset->contact_list_id;
                $data['show_departments'] = (bool) $preset->show_departments;
                $data['show_contact_cards'] = (bool) $preset->show_contact_cards;
                break;

        }

        // Add opening buttons (available for all modes)
        $opening_buttons = $preset->opening_buttons ?? null;
        if ( is_string( $opening_buttons ) ) {
            $opening_buttons = json_decode( $opening_buttons, true );
        }
        $data['opening_buttons'] = $opening_buttons ?: array();

        return $data;
    }

    /**
     * Handle question click for Mode 1.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response
     */
    public function handle_question_click( WP_REST_Request $request ) {
        $widget_id    = absint( $request->get_param( 'widget_id' ) );
        $question_idx = absint( $request->get_param( 'question_idx' ) );
        $context      = $request->get_param( 'context' ) ?? array();

        $widget_class = new BoostBot_Opening_Screen_Widget();
        $result       = $widget_class->handle_question_click( $widget_id, $question_idx, $context );

        if ( ! $result['success'] ) {
            return $this->error( $result['error'] ?? __( 'שגיאה לא ידועה', 'boostbot' ) );
        }

        return $this->success( $result );
    }

    /**
     * Handle Q&A click for Mode 2.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response
     */
    public function handle_qa_click( WP_REST_Request $request ) {
        $widget_id = absint( $request->get_param( 'widget_id' ) );
        $qa_idx    = absint( $request->get_param( 'qa_idx' ) );

        $widget_class = new BoostBot_Opening_Screen_Widget();
        $result       = $widget_class->handle_qa_click( $widget_id, $qa_idx );

        if ( ! $result['success'] ) {
            return $this->error( $result['error'] ?? __( 'שגיאה לא ידועה', 'boostbot' ) );
        }

        return $this->success( $result );
    }

    /**
     * Save opening screen settings (Admin).
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response
     */
    public function save_settings( WP_REST_Request $request ) {
        $bot_id   = absint( $request->get_param( 'bot_id' ) );
        $settings = $request->get_param( 'settings' );

        // Validate settings
        $widget_class = new BoostBot_Opening_Screen_Widget();
        $validation   = $widget_class->validate( $settings );

        if ( ! $validation['valid'] ) {
            return $this->validation_error( $validation['errors'] );
        }

        // Check if opening screen widget already exists for this bot
        $widget_model = new BoostBot_Widget_Model();
        $widgets      = $widget_model->get_by_bot( $bot_id );

        $existing_widget = null;
        foreach ( $widgets as $widget ) {
            if ( 'opening_screen' === $widget->widget_type ) {
                $existing_widget = $widget;
                break;
            }
        }

        if ( $existing_widget ) {
            // Update existing widget
            $widget_model->update( $existing_widget->id, array(
                'settings' => wp_json_encode( $settings ),
            ) );
            $widget_id = $existing_widget->id;
        } else {
            // Create new widget
            $widget_id = $widget_model->create( array(
                'bot_id'      => $bot_id,
                'widget_type' => 'opening_screen',
                'name'        => __( 'מסך פתיחה', 'boostbot' ),
                'settings'    => wp_json_encode( $settings ),
                'is_active'   => 1,
            ) );
        }

        if ( ! $widget_id ) {
            return $this->error( __( 'שגיאה בשמירת ההגדרות', 'boostbot' ) );
        }

        return $this->success( array(
            'widget_id' => $widget_id,
            'message'   => __( 'הגדרות מסך פתיחה נשמרו בהצלחה', 'boostbot' ),
        ) );
    }

    /**
     * Get available modes (Admin).
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response
     */
    public function get_modes( WP_REST_Request $request ) {
        return $this->success( array(
            'modes' => BoostBot_Opening_Screen_Widget::get_modes(),
        ) );
    }
}

