<?php
/**
 * Opening Screen Presets API Endpoint
 *
 * Handles API requests for opening screen presets.
 *
 * @package BoostBot
 * @since 1.1.0
 */

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

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

    /**
     * REST route base.
     *
     * @var string
     */
    protected $rest_base = 'opening-screen-presets';

    /**
     * Register routes.
     *
     * @since 1.1.0
     */
    public function register() {
        // Get all presets
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base,
            array(
                array(
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => array( $this, 'get_presets' ),
                    'permission_callback' => array( $this, 'admin_access' ),
                ),
                array(
                    'methods'             => WP_REST_Server::CREATABLE,
                    'callback'            => array( $this, 'create_preset' ),
                    'permission_callback' => array( $this, 'admin_access' ),
                ),
            )
        );

        // Single preset operations
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/(?P<id>\d+)',
            array(
                array(
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => array( $this, 'get_preset' ),
                    'permission_callback' => array( $this, 'admin_access' ),
                ),
                array(
                    'methods'             => WP_REST_Server::EDITABLE,
                    'callback'            => array( $this, 'update_preset' ),
                    'permission_callback' => array( $this, 'admin_access' ),
                ),
                array(
                    'methods'             => WP_REST_Server::DELETABLE,
                    'callback'            => array( $this, 'delete_preset' ),
                    'permission_callback' => array( $this, 'admin_access' ),
                ),
            )
        );

        // Set as default
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/(?P<id>\d+)/set-default',
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'set_default' ),
                'permission_callback' => array( $this, 'admin_access' ),
            )
        );

        // Duplicate preset
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/(?P<id>\d+)/duplicate',
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'duplicate_preset' ),
                'permission_callback' => array( $this, 'admin_access' ),
            )
        );

        // Bulk delete presets
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/bulk-delete',
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'bulk_delete' ),
                'permission_callback' => array( $this, 'admin_access' ),
            )
        );

        // GET /opening-screen-presets/{id}/linked-bots - Get bots using this preset
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/(?P<id>\d+)/linked-bots',
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_linked_bots' ),
                'permission_callback' => array( $this, 'admin_access' ),
            )
        );

        // POST /opening-screen-presets/{id}/link-bot/{bot_id} - Link bot to this preset
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/(?P<id>\d+)/link-bot/(?P<bot_id>\d+)',
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'link_bot' ),
                'permission_callback' => array( $this, 'admin_access' ),
            )
        );

        // POST /opening-screen-presets/{id}/unlink-bot/{bot_id} - Unlink bot from this preset
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/(?P<id>\d+)/unlink-bot/(?P<bot_id>\d+)',
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'unlink_bot' ),
                'permission_callback' => array( $this, 'admin_access' ),
            )
        );
    }

    /**
     * Get all presets.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response
     */
    public function get_presets( WP_REST_Request $request ) {
        $model = new BoostBot_Opening_Screen_Preset_Model();

        $args = array( 'limit' => 200 );

        if ( $request->has_param( 'language' ) ) {
            $args['where'] = array( 'language' => $request->get_param( 'language' ) );
        }

        $presets = $model->get_all( $args );

        // Parse JSON fields for each preset
        $presets = array_map( function( $preset ) use ( $model ) {
            return $model->parse_json_fields( $preset );
        }, $presets );

        return $this->success( array(
            'presets' => $presets,
            'modes'   => BoostBot_Opening_Screen_Preset_Model::get_modes(),
        ) );
    }

    /**
     * Get a single preset.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function get_preset( WP_REST_Request $request ) {
        $id = absint( $request->get_param( 'id' ) );

        $model = new BoostBot_Opening_Screen_Preset_Model();
        $preset = $model->get( $id );

        if ( ! $preset ) {
            return $this->not_found( __( 'הגדרת פתיחה', 'boostbot' ) );
        }

        $preset = $model->parse_json_fields( $preset );

        return $this->success( array(
            'preset' => $preset,
            'modes'  => BoostBot_Opening_Screen_Preset_Model::get_modes(),
        ) );
    }

    /**
     * Create a new preset.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function create_preset( WP_REST_Request $request ) {
        $data = $request->get_json_params();

        if ( empty( $data['name'] ) ) {
            return $this->error( __( 'שם הגדרת הפתיחה הוא שדה חובה', 'boostbot' ) );
        }

        $model = new BoostBot_Opening_Screen_Preset_Model();

        // Generate slug if not provided
        if ( empty( $data['slug'] ) ) {
            $data['slug'] = $model->generate_slug( $data['name'] );
        }

        // Set defaults
        $data['is_default'] = $data['is_default'] ?? 0;
        $data['is_system'] = 0; // User-created presets are never system presets
        $data['mode'] = $data['mode'] ?? 'questions_ai';
        $data['show_welcome'] = $data['show_welcome'] ?? 1;

        $id = $model->create( $data );

        if ( ! $id ) {
            return $this->error( __( 'שגיאה ביצירת הגדרת פתיחה', 'boostbot' ) );
        }

        $preset = $model->get( $id );
        $preset = $model->parse_json_fields( $preset );

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

    /**
     * Update a preset.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function update_preset( WP_REST_Request $request ) {
        $id = absint( $request->get_param( 'id' ) );
        $data = $request->get_json_params();

        $model = new BoostBot_Opening_Screen_Preset_Model();
        $existing = $model->get( $id );

        if ( ! $existing ) {
            return $this->not_found( __( 'הגדרת פתיחה', 'boostbot' ) );
        }

        // Don't allow changing system status
        unset( $data['is_system'] );

        // Update slug if name changed
        if ( ! empty( $data['name'] ) && $data['name'] !== $existing->name && empty( $data['slug'] ) ) {
            $data['slug'] = $model->generate_slug( $data['name'], $id );
        }

        $updated = $model->update( $id, $data );

        if ( ! $updated ) {
            return $this->error( __( 'שגיאה בעדכון הגדרת פתיחה', 'boostbot' ) );
        }

        $preset = $model->get( $id );
        $preset = $model->parse_json_fields( $preset );

        return $this->success( array(
            'preset'  => $preset,
            'message' => __( 'הגדרת פתיחה עודכנה בהצלחה', 'boostbot' ),
        ) );
    }

    /**
     * Delete a preset.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function delete_preset( WP_REST_Request $request ) {
        $id = absint( $request->get_param( 'id' ) );

        $model = new BoostBot_Opening_Screen_Preset_Model();
        $existing = $model->get( $id );

        if ( ! $existing ) {
            return $this->not_found( __( 'הגדרת פתיחה', 'boostbot' ) );
        }

        // Don't allow deleting system presets
        if ( $existing->is_system ) {
            return $this->error( __( 'לא ניתן למחוק הגדרת פתיחה מערכתית', 'boostbot' ), 403 );
        }

        $deleted = $model->delete( $id );

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

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

    /**
     * Set a preset as default.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function set_default( WP_REST_Request $request ) {
        $id = absint( $request->get_param( 'id' ) );

        $model = new BoostBot_Opening_Screen_Preset_Model();
        $existing = $model->get( $id );

        if ( ! $existing ) {
            return $this->not_found( __( 'הגדרת פתיחה', 'boostbot' ) );
        }

        $result = $model->set_as_default( $id );

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

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

    /**
     * Duplicate a preset.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function duplicate_preset( WP_REST_Request $request ) {
        $id = absint( $request->get_param( 'id' ) );

        $model = new BoostBot_Opening_Screen_Preset_Model();
        $existing = $model->get( $id );

        if ( ! $existing ) {
            return $this->not_found( __( 'הגדרת פתיחה', 'boostbot' ) );
        }

        // Create copy data
        $copy_data = (array) $existing;
        unset( $copy_data['id'], $copy_data['created_at'], $copy_data['updated_at'] );

        // Update name and slug
        /* translators: %s: preset name */
        $copy_data['name'] = sprintf( __( '%s (העתק)', 'boostbot' ), $existing->name );
        $copy_data['slug'] = $model->generate_slug( $copy_data['name'] );
        $copy_data['is_default'] = 0;
        $copy_data['is_system'] = 0;

        $new_id = $model->create( $copy_data );

        if ( ! $new_id ) {
            return $this->error( __( 'שגיאה בשכפול הגדרת פתיחה', 'boostbot' ) );
        }

        $preset = $model->get( $new_id );
        $preset = $model->parse_json_fields( $preset );

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

    /**
     * Bulk delete presets.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function bulk_delete( WP_REST_Request $request ) {
        $data = $request->get_json_params();
        $ids = $data['ids'] ?? array();

        if ( empty( $ids ) || ! is_array( $ids ) ) {
            return $this->error( __( 'לא נבחרו פריטים למחיקה', 'boostbot' ) );
        }

        $model = new BoostBot_Opening_Screen_Preset_Model();
        $deleted_count = 0;
        $skipped_system = 0;
        $errors = array();

        foreach ( $ids as $id ) {
            $id = absint( $id );
            $preset = $model->get( $id );

            if ( ! $preset ) {
                continue;
            }

            // Skip system presets
            if ( $preset->is_system ) {
                $skipped_system++;
                continue;
            }

            $result = $model->delete( $id );
            if ( $result ) {
                $deleted_count++;
            } else {
                $errors[] = $id;
            }
        }

        /* translators: %d: number of deleted presets */
        $message = sprintf( __( '%d הגדרות פתיחה נמחקו בהצלחה', 'boostbot' ), $deleted_count );
        
        if ( $skipped_system > 0 ) {
            /* translators: %d: number of skipped system presets */
            $message .= sprintf( __( ' (%d הגדרות מערכת לא נמחקו)', 'boostbot' ), $skipped_system );
        }

        return $this->success( array(
            'deleted_count'  => $deleted_count,
            'skipped_system' => $skipped_system,
            'errors'         => $errors,
            'message'        => $message,
        ) );
    }

    /**
     * Get bots using this preset.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function get_linked_bots( WP_REST_Request $request ) {
        $id = absint( $request->get_param( 'id' ) );

        $model = new BoostBot_Opening_Screen_Preset_Model();
        $preset = $model->get( $id );

        if ( ! $preset ) {
            return $this->not_found( __( 'הגדרת פתיחה', 'boostbot' ) );
        }

        $bots = $model->get_linked_bots( $id );

        return $this->success( array( 'bots' => $bots ) );
    }

    /**
     * Link a bot to this preset.
     *
     * Sets opening_screen_preset_id on the bot and clears opening_screen_overrides.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function link_bot( WP_REST_Request $request ) {
        $preset_id = absint( $request->get_param( 'id' ) );
        $bot_id    = absint( $request->get_param( 'bot_id' ) );

        // Verify preset exists
        $model  = new BoostBot_Opening_Screen_Preset_Model();
        $preset = $model->get( $preset_id );

        if ( ! $preset ) {
            return $this->not_found( __( 'הגדרת פתיחה', 'boostbot' ) );
        }

        // Verify bot exists
        $bot_model = new BoostBot_Bot_Model();
        $bot       = $bot_model->get( $bot_id );

        if ( ! $bot ) {
            return $this->not_found( __( 'בוט', 'boostbot' ) );
        }

        // Link the bot to this preset and clear overrides
        $result = $bot_model->update( $bot_id, array(
            'opening_screen_preset_id' => $preset_id,
            'opening_screen_overrides' => null,
        ) );

        if ( ! $result ) {
            return $this->error( __( 'שגיאה בשיוך הבוט להודעת הפתיחה', 'boostbot' ) );
        }

        if ( class_exists( 'BoostBot_Logger' ) ) {
            BoostBot_Logger::info( 'Bot linked to opening screen preset', array(
                'bot_id'    => $bot_id,
                'preset_id' => $preset_id,
            ) );
        }

        return $this->success( array(
            'message' => __( 'הבוט שויך להודעת הפתיחה בהצלחה', 'boostbot' ),
        ) );
    }

    /**
     * Unlink a bot from this preset.
     *
     * Before unlinking, copies the preset's current configuration into
     * opening_screen_overrides on the bot so it doesn't lose its greeting config.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function unlink_bot( WP_REST_Request $request ) {
        $preset_id = absint( $request->get_param( 'id' ) );
        $bot_id    = absint( $request->get_param( 'bot_id' ) );

        // Get the preset to copy values before unlinking
        $model  = new BoostBot_Opening_Screen_Preset_Model();
        $preset = $model->get( $preset_id );

        if ( ! $preset ) {
            return $this->not_found( __( 'הגדרת פתיחה', 'boostbot' ) );
        }

        // Get the bot
        $bot_model = new BoostBot_Bot_Model();
        $bot       = $bot_model->get( $bot_id );

        if ( ! $bot || absint( $bot->opening_screen_preset_id ) !== $preset_id ) {
            return $this->not_found( __( 'בוט', 'boostbot' ) );
        }

        // Copy preset configuration into opening_screen_overrides before unlinking
        $overrides = array(
            'mode'               => $preset->mode,
            'welcome_text'       => $preset->welcome_text,
            'show_welcome'       => $preset->show_welcome,
            'questions'          => $preset->questions,
            'ai_instructions'    => $preset->ai_instructions,
            'qa_pairs'           => $preset->qa_pairs,
            'contact_list_id'    => $preset->contact_list_id,
            'show_departments'   => $preset->show_departments,
            'show_contact_cards' => $preset->show_contact_cards,
            'attached_files'     => $preset->attached_files,
            'opening_buttons'    => $preset->opening_buttons ?? null,
        );

        // Encode overrides as JSON string for storage
        $overrides_json = wp_json_encode( $overrides );

        $result = $bot_model->update( $bot_id, array(
            'opening_screen_preset_id' => null,
            'opening_screen_overrides' => $overrides_json,
        ) );

        if ( ! $result ) {
            return $this->error( __( 'שגיאה בניתוק הבוט מהודעת הפתיחה', 'boostbot' ) );
        }

        if ( class_exists( 'BoostBot_Logger' ) ) {
            BoostBot_Logger::info( 'Bot unlinked from opening screen preset', array(
                'bot_id'    => $bot_id,
                'preset_id' => $preset_id,
            ) );
        }

        return $this->success( array(
            'message' => __( 'הבוט נותק מהודעת הפתיחה בהצלחה', 'boostbot' ),
        ) );
    }
}






