<?php
/**
 * My AI Agent page AJAX handlers.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/traits
 * @since      1.17.0
 */

if ( ! defined( 'WPINC' ) ) {
    die;
}

trait SiteStaffr_Admin_Agent_Ajax_Trait {

    /**
     * Save an individual AI instruction toggle.
     *
     * @since 1.17.0
     */
    public function ajax_save_agent_instruction() {
        if ( ! check_ajax_referer( 'sitestaffr_agent_nonce', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed.', 'sitestaffr' ) ) );
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'sitestaffr' ) ) );
            return;
        }

        $allowed_keys = array( 'ai_collect_contact', 'ai_disregard_personal_info' );
        $setting_key = isset( $_POST['setting_key'] ) ? sanitize_key( wp_unslash( $_POST['setting_key'] ) ) : '';
        if ( ! in_array( $setting_key, $allowed_keys, true ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid setting.', 'sitestaffr' ) ) );
            return;
        }

        $value = isset( $_POST['value'] ) ? sanitize_key( wp_unslash( $_POST['value'] ) ) : '0';
        $bool_value = ( '1' === $value );

        $settings = get_option( 'sitestaffr_settings', array() );
        $settings[ $setting_key ] = $bool_value;
        update_option( 'sitestaffr_settings', $settings );

        wp_send_json_success();
    }

    /**
     * Save voice, greeting, and tone from the My AI Agent page.
     *
     * @since 1.17.0
     */
    public function ajax_save_agent_voice() {
        if ( ! check_ajax_referer( 'sitestaffr_agent_nonce', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed.', 'sitestaffr' ) ) );
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'sitestaffr' ) ) );
            return;
        }

        $settings = get_option( 'sitestaffr_settings', array() );

        // AI Voice — validate against allowed voices for plan.
        if ( isset( $_POST['ai_voice'] ) ) {
            $ai_voice = sanitize_key( wp_unslash( $_POST['ai_voice'] ) );
            $plan_key = $this->get_current_plan_key();
            $allowed = self::get_voices_for_plan( $plan_key );
            if ( in_array( $ai_voice, $allowed, true ) ) {
                $settings['ai_voice'] = $ai_voice;
                // Sync to widget settings.
                $widget_settings = get_option( 'sitestaffr_widget_settings', array() );
                $widget_settings['ai_voice'] = $ai_voice;
                update_option( 'sitestaffr_widget_settings', $widget_settings );
            }
        }

        // Custom Greeting — only for Pro plan.
        if ( isset( $_POST['custom_greeting'] ) && $this->is_custom_greeting_allowed_for_plan( $this->get_current_plan_key() ) ) {
            $custom_greeting_result = $this->sanitize_custom_greeting( wp_unslash( $_POST['custom_greeting'] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized by sanitize_custom_greeting()
            $settings['custom_greeting'] = $custom_greeting_result['value'];
        }

        // Custom Greeting Tone.
        if ( isset( $_POST['custom_greeting_tone'] ) ) {
            $settings['custom_greeting_tone'] = $this->sanitize_custom_greeting_tone( sanitize_key( wp_unslash( $_POST['custom_greeting_tone'] ) ) );
        }

        update_option( 'sitestaffr_settings', $settings );
        wp_send_json_success( array( 'message' => __( 'Voice settings saved.', 'sitestaffr' ) ) );
    }

    /**
     * Save (create or update) a custom instruction.
     *
     * @since 1.20.0
     */
    public function ajax_save_custom_instruction() {
        if ( ! check_ajax_referer( 'sitestaffr_agent_nonce', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed.', 'sitestaffr' ) ) );
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'sitestaffr' ) ) );
            return;
        }

        $text = isset( $_POST['text'] ) ? sanitize_text_field( wp_unslash( $_POST['text'] ) ) : '';
        if ( '' === $text || mb_strlen( $text ) > 200 ) {
            wp_send_json_error( array( 'message' => __( 'Instruction must be 1-200 characters.', 'sitestaffr' ) ) );
            return;
        }

        $settings = get_option( 'sitestaffr_settings', array() );
        $list = isset( $settings['custom_instructions_list'] ) ? $settings['custom_instructions_list'] : array();

        $id = isset( $_POST['id'] ) ? sanitize_key( wp_unslash( $_POST['id'] ) ) : '';

        if ( '' === $id ) {
            $limit = self::get_custom_instructions_limit( $this->get_current_plan_key() );
            if ( count( $list ) >= $limit ) {
                wp_send_json_error( array( 'message' => __( 'Custom instruction limit reached.', 'sitestaffr' ) ) );
                return;
            }
            $id = 'ci_' . strtolower( wp_generate_password( 8, false ) );
            $list[] = array(
                'id'      => $id,
                'text'    => $text,
                'enabled' => true,
            );
        } else {
            $found = false;
            foreach ( $list as &$item ) {
                if ( strtolower( $item['id'] ) === $id ) {
                    $item['text'] = $text;
                    $found = true;
                    break;
                }
            }
            unset( $item );
            if ( ! $found ) {
                wp_send_json_error( array( 'message' => __( 'Instruction not found.', 'sitestaffr' ) ) );
                return;
            }
        }

        $settings['custom_instructions_list'] = $list;
        update_option( 'sitestaffr_settings', $settings );

        wp_send_json_success( array(
            'id'      => $id,
            'text'    => $text,
            'enabled' => true,
        ) );
    }

    /**
     * Toggle a custom instruction on/off.
     *
     * @since 1.20.0
     */
    public function ajax_toggle_custom_instruction() {
        if ( ! check_ajax_referer( 'sitestaffr_agent_nonce', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed.', 'sitestaffr' ) ) );
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'sitestaffr' ) ) );
            return;
        }

        $id = isset( $_POST['id'] ) ? sanitize_key( wp_unslash( $_POST['id'] ) ) : '';
        $value = isset( $_POST['value'] ) ? sanitize_key( wp_unslash( $_POST['value'] ) ) : '0';

        $settings = get_option( 'sitestaffr_settings', array() );
        $list = isset( $settings['custom_instructions_list'] ) ? $settings['custom_instructions_list'] : array();

        $found = false;
        foreach ( $list as &$item ) {
            if ( strtolower( $item['id'] ) === $id ) {
                $item['enabled'] = ( '1' === $value );
                $found = true;
                break;
            }
        }
        unset( $item );

        if ( ! $found ) {
            wp_send_json_error( array( 'message' => __( 'Instruction not found.', 'sitestaffr' ) ) );
            return;
        }

        $settings['custom_instructions_list'] = $list;
        update_option( 'sitestaffr_settings', $settings );

        wp_send_json_success();
    }

    /**
     * Delete a custom instruction.
     *
     * @since 1.20.0
     */
    public function ajax_delete_custom_instruction() {
        if ( ! check_ajax_referer( 'sitestaffr_agent_nonce', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed.', 'sitestaffr' ) ) );
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'sitestaffr' ) ) );
            return;
        }

        $id = isset( $_POST['id'] ) ? sanitize_key( wp_unslash( $_POST['id'] ) ) : '';

        $settings = get_option( 'sitestaffr_settings', array() );
        $list = isset( $settings['custom_instructions_list'] ) ? $settings['custom_instructions_list'] : array();

        $new_list = array();
        $found = false;
        foreach ( $list as $item ) {
            if ( strtolower( $item['id'] ) === $id ) {
                $found = true;
                continue;
            }
            $new_list[] = $item;
        }

        if ( ! $found ) {
            wp_send_json_error( array( 'message' => __( 'Instruction not found.', 'sitestaffr' ) ) );
            return;
        }

        $settings['custom_instructions_list'] = $new_list;
        update_option( 'sitestaffr_settings', $settings );

        wp_send_json_success();
    }
}
