<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class SBPAI_Ajax_Handler {
    public function handle_queue_generation() {
        check_ajax_referer( 'sbpai_ajax_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

        $type = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : 'posts';
        $amount = isset( $_POST['amount'] ) ? intval( $_POST['amount'] ) : 1;
        
        $raw_args  = isset( $_POST['args'] ) ? (array) wp_unslash( $_POST['args'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        // Sanitize args payload
        $safe_args = array();
        foreach ( $raw_args as $k => $v ) {
            $safe_args[ sanitize_key( $k ) ] = sanitize_text_field( (string) $v );
        }

        $niche = get_option( 'sbpai_active_niche', 'General' );
        $ai = get_option( 'sbpai_active_ai', 1 );

        $scheduler = new SBPAI_Action_Scheduler();
        $queued = $scheduler->schedule_job( $type, $amount, $niche, $ai, $safe_args );

        if ( $queued ) {
            wp_send_json_success( "Successfully queued {$amount} {$type} in the background." );
        } else {
            wp_send_json_error( "Action Scheduler is not active." );
        }
    }

    public function handle_polling_status() {
        check_ajax_referer( 'sbpai_ajax_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

        if ( ! function_exists('as_get_scheduled_actions') ) wp_send_json_error();

        $pending = as_get_scheduled_actions( array(
            'hook' => 'sbpai_generate_dummy_data_job',
            'status' => \ActionScheduler_Store::STATUS_PENDING
        ), 'ids' );

        wp_send_json_success( array( 'pending' => count($pending) ) );
    }

    public function handle_save_settings() {
        check_ajax_referer( 'sbpai_ajax_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();

        update_option( 'sbpai_active_niche',       sanitize_text_field( wp_unslash( $_POST['niche'] ?? '' ) ) );
        update_option( 'sbpai_active_ai',           intval( $_POST['ai'] ?? 0 ) );
        update_option( 'sbpai_use_ai_provider',     intval( $_POST['ai'] ?? 0 ) );

        wp_send_json_success();
    }

    public function handle_save_ai_key() {
        check_ajax_referer( 'sbpai_ajax_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

        $provider = sanitize_key( wp_unslash( $_POST['provider'] ?? '' ) );
        $api_key  = sanitize_text_field( wp_unslash( $_POST['api_key'] ?? '' ) );

        if ( ! $provider ) wp_send_json_error( 'Invalid provider.' );

        update_option( 'sbpai_ai_api_key_' . $provider, $api_key );
        wp_send_json_success( 'Key saved.' );
    }

    public function handle_test_ai_connection() {
        check_ajax_referer( 'sbpai_ajax_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

        $provider = sanitize_key( wp_unslash( $_POST['provider'] ?? '' ) );
        $api_key  = sanitize_text_field( wp_unslash( $_POST['api_key'] ?? '' ) );

        if ( ! $provider || ! $api_key ) {
            wp_send_json_error( 'Provider and API key are required.' );
        }

        $result = SBPAI_Service_AI::test_connection( $provider, $api_key );

        if ( $result['success'] ) {
            wp_send_json_success( $result['message'] );
        } else {
            wp_send_json_error( $result['message'] );
        }
    }

    public function handle_set_active_provider() {
        check_ajax_referer( 'sbpai_ajax_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

        $provider  = sanitize_key( $_POST['provider'] ?? '' );
        $providers = SBPAI_Service_AI::get_providers();

        if ( ! isset( $providers[$provider] ) ) {
            wp_send_json_error( 'Unknown provider.' );
        }

        $api_key = get_option( 'sbpai_ai_api_key_' . $provider, '' );
        if ( empty( $api_key ) ) {
            wp_send_json_error( 'Please save an API key for this provider before activating it.' );
        }

        update_option( 'sbpai_ai_provider', $provider );
        wp_send_json_success( 'Provider activated.' );
    }

    public function handle_save_primary_provider() {
        check_ajax_referer( 'sbpai_ajax_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

        $provider = sanitize_key( wp_unslash( $_POST['provider'] ?? '' ) );
        $api_key  = sanitize_text_field( wp_unslash( $_POST['api_key'] ?? '' ) );
        $providers = SBPAI_Service_AI::get_providers();

        if ( ! isset( $providers[$provider] ) ) wp_send_json_error( 'Unknown provider.' );

        update_option( 'sbpai_ai_provider',              $provider );
        update_option( 'sbpai_ai_api_key_' . $provider,  $api_key );
        wp_send_json_success( 'Primary provider saved and activated.' );
    }

    public function handle_save_fallback_provider() {
        check_ajax_referer( 'sbpai_ajax_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

        $provider = sanitize_key( wp_unslash( $_POST['provider'] ?? '' ) );
        $api_key  = sanitize_text_field( wp_unslash( $_POST['api_key'] ?? '' ) );
        $providers = SBPAI_Service_AI::get_providers();

        if ( $provider && ! isset( $providers[$provider] ) ) wp_send_json_error( 'Unknown provider.' );

        update_option( 'sbpai_ai_fallback_provider',                  $provider );
        update_option( 'sbpai_ai_api_key_fallback_' . $provider,      $api_key );
        wp_send_json_success( 'Fallback provider saved.' );
    }

    public function handle_quick_config_wc() {
        check_ajax_referer( 'sbpai_ajax_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();

        if ( ! class_exists( 'WooCommerce' ) ) {
            wp_send_json_error( 'WooCommerce is not installed.' );
        }

        $args = isset( $_POST['args'] ) ? (array) wp_unslash( $_POST['args'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Each key/value sanitized below.
        
        $address  = isset( $args['address'] )  ? sanitize_text_field( $args['address'] )  : '';
        $city     = isset( $args['city'] )     ? sanitize_text_field( $args['city'] )     : '';
        $country  = isset( $args['country'] )  ? sanitize_text_field( $args['country'] )  : '';
        $postcode = isset( $args['postcode'] ) ? sanitize_text_field( $args['postcode'] ) : '';
        $currency = isset( $args['currency'] ) ? sanitize_text_field( $args['currency'] ) : 'USD';
        
        $tax      = (isset($args['tax']) && $args['tax'] == 1) ? 'yes' : 'no';
        $shipping = (isset($args['shipping']) && $args['shipping'] == 1) ? 'yes' : 'no';

        // Establish Default Store Locations to USA
        update_option( 'woocommerce_store_address', $address );
        update_option( 'woocommerce_store_city', $city );
        update_option( 'woocommerce_default_country', $country );
        update_option( 'woocommerce_store_postcode', $postcode );
        update_option( 'woocommerce_currency', $currency );
        
        // Tax and Shipping
        update_option( 'woocommerce_calc_taxes', $tax );
        if ($shipping === 'yes') {
            update_option( 'woocommerce_ship_to_countries', 'all' );
            update_option( 'woocommerce_ship_to_destination', 'billing_only' );
        }

        // Hide Setup Wizard Tasks & Banners Globally
        $onboarding_profile = get_option( 'woocommerce_onboarding_profile', array() );
        $onboarding_profile['completed'] = true;
        $onboarding_profile['skipped'] = true;
        update_option( 'woocommerce_onboarding_profile', $onboarding_profile );
        
        update_option( 'woocommerce_task_list_hidden', 'yes' );
        update_option( 'woocommerce_task_list_complete', 'yes' );
        update_option( 'woocommerce_task_list_welcome_modal_dismissed', 'yes' );
        update_option( 'woocommerce_setup_background', 'yes' );
        update_option( 'woocommerce_show_marketplace_suggestions', 'no' );
        
        // Gateways processing
        $gateways = isset($args['gateways']) ? (array) $args['gateways'] : array();
        
        // COD
        $cod_settings = get_option('woocommerce_cod_settings', array());
        $cod_settings['enabled'] = (isset($gateways['cod']) && $gateways['cod'] == 1) ? 'yes' : 'no';
        if ($cod_settings['enabled'] === 'yes') {
            $cod_settings['title'] = 'Cash on delivery';
            $cod_settings['description'] = 'Pay with cash upon delivery.';
            $cod_settings['instructions'] = 'Pay with cash upon delivery.';
        }
        update_option( 'woocommerce_cod_settings', $cod_settings );

        // BACS (Direct Bank Transfer)
        $bacs_settings = get_option('woocommerce_bacs_settings', array());
        $bacs_settings['enabled'] = (isset($gateways['bacs']) && $gateways['bacs'] == 1) ? 'yes' : 'no';
        if ($bacs_settings['enabled'] === 'yes') {
            $bacs_settings['title'] = 'Direct bank transfer';
            $bacs_settings['description'] = 'Make your payment directly into our bank account.';
        }
        update_option( 'woocommerce_bacs_settings', $bacs_settings );

        // Cheque (Check Payments)
        $cheque_settings = get_option('woocommerce_cheque_settings', array());
        $cheque_settings['enabled'] = (isset($gateways['cheque']) && $gateways['cheque'] == 1) ? 'yes' : 'no';
        if ($cheque_settings['enabled'] === 'yes') {
            $cheque_settings['title'] = 'Check payments';
            $cheque_settings['description'] = 'Please send a check to Store Name.';
        }
        update_option( 'woocommerce_cheque_settings', $cheque_settings );

        update_option( 'woocommerce_enable_guest_checkout', 'yes' );

        wp_send_json_success( 'WooCommerce Quick Settings Applied' );
    }

    public function handle_reset_config_wc() {
        check_ajax_referer( 'sbpai_ajax_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();

        update_option( 'woocommerce_store_address', '' );
        update_option( 'woocommerce_store_city', '' );
        update_option( 'woocommerce_default_country', 'US' );
        update_option( 'woocommerce_store_postcode', '' );
        update_option( 'woocommerce_currency', 'USD' );
        update_option( 'woocommerce_calc_taxes', 'no' );
        update_option( 'woocommerce_ship_to_countries', '' );

        $gateways = ['woocommerce_cod_settings', 'woocommerce_bacs_settings', 'woocommerce_cheque_settings'];
        foreach ($gateways as $g) {
            $settings = get_option($g, array());
            $settings['enabled'] = 'no';
            update_option($g, $settings);
        }

        // Wipe Wizard settings so it acts completely fresh and asks again
        delete_option( 'woocommerce_onboarding_profile' );
        delete_option( 'woocommerce_task_list_hidden' );
        delete_option( 'woocommerce_task_list_complete' );
        delete_option( 'woocommerce_task_list_welcome_modal_dismissed' );
        update_option( 'woocommerce_setup_background', 'no' );
        update_option( 'woocommerce_show_marketplace_suggestions', 'yes' );

        wp_send_json_success( 'WooCommerce settings have been reset' );
    }
}

