<?php
/**
 * AI Recommend cross-sell: install, cron, and cart/checkout links.
 */

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

if (!defined('ASKAGENTO_RECOMMEND_CROSS_SELL_META_KEY')) {
    define('ASKAGENTO_RECOMMEND_CROSS_SELL_META_KEY', '_askagento_ai_cross_sell_ids');
}

if (!defined('ASKAGENTO_OPTION_CROSS_SELL_PAYLOAD')) {
    define('ASKAGENTO_OPTION_CROSS_SELL_PAYLOAD', 'askagento_last_cross_sell_recommendations_payload');
}

if (!defined('ASKAGENTO_OPTION_CROSS_SELL_SITE_ID')) {
    define('ASKAGENTO_OPTION_CROSS_SELL_SITE_ID', 'askagento_last_cross_sell_recommendations_site_id');
}

if (!defined('ASKAGENTO_RECOMMEND_CROSS_SELL_DEMO_SHOP_HOST')) {
    define('ASKAGENTO_RECOMMEND_CROSS_SELL_DEMO_SHOP_HOST', 'demowp.askagento.com');
}

/**
 * Whether this shop is the public demo catalogue (cross-sell bundles are published there).
 */
function askagento_recommend_cross_sell_is_demo_shop(): bool {
    $host = strtolower(trim((string) wp_parse_url(site_url(), PHP_URL_HOST)));
    $demo_host = strtolower(ASKAGENTO_RECOMMEND_CROSS_SELL_DEMO_SHOP_HOST);
    if ($host === $demo_host || $host === 'www.' . $demo_host) {
        return true;
    }

    return (bool) apply_filters('askagento_recommend_cross_sell_is_demo_shop', false);
}

/**
 * Product-id map from a cross-sell API payload ({@see GET /recommend/cross-sell}).
 *
 * @param array $payload Decoded JSON body.
 * @return array<string, array>
 */
function askagento_recommend_cross_sell_payload_map(array $payload): array {
    if (isset($payload['cross_sells']) && is_array($payload['cross_sells'])) {
        return $payload['cross_sells'];
    }
    if (isset($payload['recommendations']) && is_array($payload['recommendations'])) {
        return $payload['recommendations'];
    }

    return [];
}

/**
 * @return string Raw JSON stored for cross-sell, or empty.
 */
function askagento_recommend_cross_sell_get_stored_payload_raw(): string {
    return (string) get_option(ASKAGENTO_OPTION_CROSS_SELL_PAYLOAD, '');
}

/**
 * @param array $payload Cross-sell recommendations payload.
 */
function askagento_recommend_cross_sell_store_payload(array $payload, string $site_id): void {
    update_option(ASKAGENTO_OPTION_CROSS_SELL_PAYLOAD, wp_json_encode($payload), false);
    update_option(ASKAGENTO_OPTION_CROSS_SELL_SITE_ID, sanitize_text_field($site_id), false);
}

/**
 * Fetch cross-sell recommendations via API (GET /recommend/cross-sell).
 *
 * @param string $site_id Installation site identifier.
 * @return array|WP_Error
 */
function askagento_recommend_cross_sell_fetch($site_id) {
    $settings = askagento_get_install_settings();

    if (!askagento_install_api_is_enabled()) {
        return new WP_Error('not_enabled', __('Installation API not enabled', 'askagento'));
    }

    if (empty($site_id)) {
        return new WP_Error('missing_installation_id', __('No installation ID found', 'askagento'));
    }

    if (function_exists('askagento_feature_is_enabled') && !askagento_feature_is_enabled('ai_recommend_cross_sell')) {
        return new WP_Error('feature_not_available', __('AI Cross-sell Recommendations is not available on your current plan.', 'askagento'));
    }

    $api_key = isset($settings['api_key']) ? trim((string) $settings['api_key']) : '';

    if ($api_key === '') {
        return new WP_Error('missing_api_key', __('Discovery API key is missing; cannot load cross-sell recommendations.', 'askagento'));
    }

    $args = [
        'method'  => 'GET',
        'timeout' => 90,
        'headers' => [
            'Content-Type'          => 'application/json',
            'X-Askagento-Site-Id'   => (string) $site_id,
            'X-Askagento-Api-Key'   => $api_key,
        ],
    ];

    $base = rtrim((string) $settings['api_url'], '/');
    $url = $base . '/recommend/cross-sell';
    $response = wp_remote_get($url, $args);
    if (is_wp_error($response)) {
        return $response;
    }

    $code = wp_remote_retrieve_response_code($response);
    $body = json_decode(wp_remote_retrieve_body($response), true);

    if ($code >= 200 && $code < 300 && is_array($body)) {
        if (askagento_recommend_cross_sell_payload_map($body) === []) {
            return new WP_Error('invalid_payload', __('Cross-sell recommendations payload is empty.', 'askagento'));
        }

        return $body;
    }

    if ($code === 404 && is_array($body)) {
        $api_code = isset($body['code']) ? sanitize_key((string) $body['code']) : '';
        $api_error = !empty($body['error']) && is_string($body['error']) ? trim($body['error']) : '';
        $is_unpublished = ($api_code === 'not_published')
            || ($api_error !== '' && stripos($api_error, 'not published') !== false)
            || ($api_error !== '' && stripos($api_error, 'cross-sell') !== false && stripos($api_error, 'not found') !== false);

        if ($is_unpublished) {
            $message = !empty($body['message']) && is_string($body['message'])
                ? trim($body['message'])
                : __('Cross-sell recommendations are not available yet. Wait for catalogue sync to finish on AskAgento, or run Finish installation again from Settings.', 'askagento');

            return new WP_Error('not_published', $message);
        }
    }

    return askagento_install_api_response_error(
        $response,
        __('Failed to load cross-sell recommendations', 'askagento'),
        __('Cross-sell recommendations are not available yet. Wait for catalogue sync to finish on AskAgento, or run Finish installation again from Settings.', 'askagento')
    );
}

/**
 * Whether a successful cross-sell API fetch already ran today.
 */
function askagento_recommend_cross_sell_api_fetched_today() {
    $last = (string) get_option('askagento_last_cross_sell_recommendations_api_fetch_day', '');
    if ($last === '') {
        return false;
    }

    return $last === current_time('Y-m-d');
}

/**
 * Record a successful cross-sell API fetch for the daily cap.
 */
function askagento_recommend_cross_sell_mark_api_fetched_today() {
    update_option('askagento_last_cross_sell_recommendations_api_fetch_day', current_time('Y-m-d'), false);
}

/**
 * Fetch cross-sell recommendations only if the daily download quota allows.
 *
 * @param string $site_id Installation site identifier.
 * @return array|WP_Error
 */
function askagento_recommend_cross_sell_fetch_if_daily_quota($site_id) {
    if (apply_filters('askagento_recommend_cross_sell_bypass_daily_fetch_cap', false)) {
        $result = askagento_recommend_cross_sell_fetch($site_id);
        if (!is_wp_error($result)) {
            askagento_recommend_cross_sell_mark_api_fetched_today();
        }

        return $result;
    }

    if (askagento_recommend_cross_sell_api_fetched_today()) {
        return new WP_Error(
            'daily_cap',
            __('Cross-sell recommendations were already downloaded today (limit: once per calendar day). Try again tomorrow.', 'askagento')
        );
    }

    $result = askagento_recommend_cross_sell_fetch($site_id);
    if (!is_wp_error($result)) {
        askagento_recommend_cross_sell_mark_api_fetched_today();
    }

    return $result;
}

/**
 * Clear cross-sell autonomous run history (catalogue re-registration).
 */
function askagento_recommend_cross_sell_reset_activity_options() {
    delete_option('askagento_ai_cross_sell_auto');
    delete_option('askagento_ai_cross_sell_auto_mode');
    delete_option('askagento_ai_cross_sell_auto_last_run');
    delete_option('askagento_ai_cross_sell_auto_last_error');
    delete_option('askagento_ai_cross_sell_installed_at');
    delete_option(ASKAGENTO_OPTION_CROSS_SELL_PAYLOAD);
    delete_option(ASKAGENTO_OPTION_CROSS_SELL_SITE_ID);
    delete_option('askagento_last_cross_sell_recommendations_api_fetch_day');
}

/**
 * Whether this product already has AI cross-sell links installed.
 *
 * @param int $product_id WooCommerce product ID.
 */
function askagento_recommend_cross_sell_product_has_installed_links($product_id) {
    $product_id = (int) $product_id;
    if ($product_id <= 0 || !metadata_exists('post', $product_id, ASKAGENTO_RECOMMEND_CROSS_SELL_META_KEY)) {
        return false;
    }

    $existing_meta = get_post_meta($product_id, ASKAGENTO_RECOMMEND_CROSS_SELL_META_KEY, true);
    $existing_ids = is_array($existing_meta) ? array_values(array_filter(array_map('intval', $existing_meta))) : [];

    return !empty($existing_ids);
}

/**
 * Write WooCommerce cross-sell IDs without a full product save (faster for bulk install).
 *
 * @param int   $product_id Source product ID.
 * @param int[] $linked_ids Linked cross-sell product IDs.
 */
function askagento_recommend_cross_sell_write_product_links(int $product_id, array $linked_ids): void {
    update_post_meta($product_id, '_crosssell_ids', $linked_ids);
    update_post_meta($product_id, ASKAGENTO_RECOMMEND_CROSS_SELL_META_KEY, $linked_ids);

    if (function_exists('wc_delete_product_transients')) {
        wc_delete_product_transients($product_id);
    }
    clean_post_cache($product_id);
}

/**
 * Apply AI recommendations to WooCommerce cross-sell IDs only.
 *
 * @param array  $payload Recommendations payload.
 * @param string $mode    'replace_all' or 'fill_missing'.
 * @return array|WP_Error
 */
function askagento_recommend_cross_sell_apply_to_shop($payload, $mode = 'replace_all', array $batch = []) {
    if (!function_exists('wc_get_product')) {
        return new WP_Error('woocommerce_missing', __('WooCommerce is required to install recommendation links.', 'askagento'));
    }

    $recommendations = is_array($payload) ? askagento_recommend_cross_sell_payload_map($payload) : [];
    if ($recommendations === []) {
        return new WP_Error('invalid_payload', __('Invalid cross-sell recommendations payload', 'askagento'));
    }

    $product_ids = array_values(array_map('intval', array_keys($recommendations)));
    $product_ids = array_values(array_filter($product_ids, static function ($id) {
        return $id > 0;
    }));
    $batch_total = count($product_ids);

    $batch_offset = max(0, (int) ($batch['offset'] ?? 0));
    $batch_limit = isset($batch['limit']) ? max(0, (int) $batch['limit']) : 0;
    $use_batching = $batch_limit > 0;

    if ($use_batching) {
        if ($batch_offset >= $batch_total) {
            return [
                'updated_products' => 0,
                'linked_rows' => 0,
                'skipped_products' => 0,
                'mode' => ($mode === 'fill_missing') ? 'fill_missing' : 'replace_all',
                'batch_offset' => $batch_offset,
                'batch_total' => $batch_total,
                'batch_processed' => 0,
                'batch_done' => true,
                'next_offset' => null,
            ];
        }
        $product_ids = array_slice($product_ids, $batch_offset, $batch_limit);
    }

    $fill_missing_only = ($mode === 'fill_missing');
    $updated_products = 0;
    $linked_rows = 0;
    $skipped_products = 0;

    $linked_candidates = [];
    foreach ($product_ids as $source_id) {
        $rows = $recommendations[(string) $source_id] ?? $recommendations[$source_id] ?? [];
        if (!is_array($rows)) {
            continue;
        }
        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }
            $linked_id = isset($row['product_id']) ? (int) $row['product_id'] : 0;
            if ($linked_id > 0) {
                $linked_candidates[] = $linked_id;
            }
        }
    }
    $valid_ids = function_exists('askagento_recommend_valid_product_id_set')
        ? askagento_recommend_valid_product_id_set(array_merge($product_ids, $linked_candidates))
        : [];

    if (function_exists('askagento_recommend_begin_bulk_install')) {
        askagento_recommend_begin_bulk_install();
    } elseif (function_exists('wp_suspend_cache_addition')) {
        wp_suspend_cache_addition(true);
    }

    foreach ($product_ids as $product_id) {
        if ($valid_ids !== [] && !isset($valid_ids[$product_id])) {
            continue;
        }

        if ($fill_missing_only && askagento_recommend_cross_sell_product_has_installed_links($product_id)) {
            $skipped_products++;
            continue;
        }

        $rows = $recommendations[(string) $product_id] ?? $recommendations[$product_id] ?? [];
        $linked_ids = [];
        if (is_array($rows)) {
            foreach ($rows as $row) {
                if (!is_array($row)) {
                    continue;
                }
                $linked_id = isset($row['product_id']) ? (int) $row['product_id'] : 0;
                if ($linked_id <= 0 || $linked_id === $product_id) {
                    continue;
                }
                if ($valid_ids !== [] && !isset($valid_ids[$linked_id])) {
                    continue;
                }
                if ($valid_ids === [] && !wc_get_product($linked_id)) {
                    continue;
                }
                $linked_ids[] = $linked_id;
            }
        }

        $linked_ids = array_values(array_unique($linked_ids));
        if ($linked_ids === []) {
            continue;
        }

        if ($valid_ids === [] && !wc_get_product($product_id)) {
            continue;
        }

        askagento_recommend_cross_sell_write_product_links($product_id, $linked_ids);

        $updated_products++;
        $linked_rows += count($linked_ids);
    }

    if (function_exists('askagento_recommend_end_bulk_install')) {
        askagento_recommend_end_bulk_install();
    } elseif (function_exists('wp_suspend_cache_addition')) {
        wp_suspend_cache_addition(false);
    }

    $batch_processed = count($product_ids);
    $batch_done = !$use_batching || ($batch_offset + $batch_processed >= $batch_total);

    if ($batch_done) {
        update_option('askagento_ai_cross_sell_installed_at', current_time('mysql'), false);
    }

    $result = [
        'updated_products' => $updated_products,
        'linked_rows' => $linked_rows,
        'skipped_products' => $skipped_products,
        'mode' => $fill_missing_only ? 'fill_missing' : 'replace_all',
    ];

    if ($use_batching) {
        $result['batch_offset'] = $batch_offset;
        $result['batch_total'] = $batch_total;
        $result['batch_processed'] = $batch_processed;
        $result['batch_done'] = $batch_done;
        $result['next_offset'] = $batch_done ? null : ($batch_offset + $batch_processed);
    }

    return $result;
}

/**
 * Product IDs that AskAgento may have written cross-sell links for (meta tag and/or stored bundle keys).
 *
 * @return int[]
 */
function askagento_recommend_cross_sell_collect_tracked_product_ids(): array {
    $ids = [];

    $tagged = get_posts([
        'post_type' => 'product',
        'post_status' => 'any',
        'posts_per_page' => -1,
        'fields' => 'ids',
        'meta_key' => ASKAGENTO_RECOMMEND_CROSS_SELL_META_KEY,
        'no_found_rows' => true,
        'update_post_meta_cache' => false,
        'update_post_term_cache' => false,
    ]);
    foreach ($tagged as $product_id) {
        $product_id = (int) $product_id;
        if ($product_id > 0) {
            $ids[$product_id] = true;
        }
    }

    $raw = askagento_recommend_cross_sell_get_stored_payload_raw();
    if ($raw !== '') {
        $decoded = json_decode($raw, true);
        if (is_array($decoded)) {
            foreach (array_keys(askagento_recommend_cross_sell_payload_map($decoded)) as $product_id) {
                $product_id = (int) $product_id;
                if ($product_id > 0) {
                    $ids[$product_id] = true;
                }
            }
        }
    }

    return array_map('intval', array_keys($ids));
}

/**
 * Clear AI cross-sell links from products previously installed by AskAgento.
 *
 * @return array{updated_products: int, hint: string}
 */
function askagento_recommend_cross_sell_clear_links() {
    $updated_products = 0;

    foreach (askagento_recommend_cross_sell_collect_tracked_product_ids() as $product_id) {
        $product = wc_get_product($product_id);
        if (!$product) {
            delete_post_meta($product_id, ASKAGENTO_RECOMMEND_CROSS_SELL_META_KEY);
            continue;
        }

        $had_cross_sells = !empty($product->get_cross_sell_ids('edit'));
        $had_meta = metadata_exists('post', $product_id, ASKAGENTO_RECOMMEND_CROSS_SELL_META_KEY);

        if (!$had_cross_sells && !$had_meta) {
            continue;
        }

        $product->set_cross_sell_ids([]);
        $product->save();
        wc_delete_product_transients($product_id);

        delete_post_meta($product_id, ASKAGENTO_RECOMMEND_CROSS_SELL_META_KEY);

        $updated_products++;
    }

    update_option('askagento_ai_cross_sell_installed_at', '', false);

    $hint = '';
    if ($updated_products === 0) {
        $upsell_meta_keys = array_filter([
            defined('ASKAGENTO_RECOMMEND_UPSELL_META_KEY') ? ASKAGENTO_RECOMMEND_UPSELL_META_KEY : '_askagento_ai_upsell_ids',
        ]);
        $upsell_meta_query = ['relation' => 'OR'];
        foreach ($upsell_meta_keys as $meta_key) {
            $upsell_meta_query[] = [
                'key' => $meta_key,
                'compare' => 'EXISTS',
            ];
        }
        $upsell_tagged = get_posts([
            'post_type' => 'product',
            'post_status' => 'any',
            'posts_per_page' => 1,
            'fields' => 'ids',
            'meta_query' => $upsell_meta_query,
            'no_found_rows' => true,
        ]);
        if (!empty($upsell_tagged)) {
            $hint = __(
                'No AI-tagged cross-sell links were found. Linked products under “Upsells” on the product edit screen are cleared from AI Recommend → Upsell → Setup, not here.',
                'askagento'
            );
        } else {
            $hint = __(
                'No AI-tagged cross-sell links were found. Install cross-sell recommendations first, or remove links manually under Linked products → Cross-sells on each product.',
                'askagento'
            );
        }
    }

    return [
        'updated_products' => $updated_products,
        'hint' => $hint,
    ];
}

/**
 * Admin preview rows for cross-sell payload (reuses upsell preview layout).
 *
 * @param array $payload Cross-sell API payload.
 * @return array
 */
function askagento_recommend_cross_sell_build_preview_first_three(array $payload): array {
    if (!function_exists('askagento_recommend_upsell_build_preview_first_three')) {
        return [];
    }

    $normalized = $payload;
    $normalized['recommendations'] = askagento_recommend_cross_sell_payload_map($payload);

    return askagento_recommend_upsell_build_preview_first_three($normalized);
}

/**
 * AJAX: Download cross-sell recommendations payload.
 */
add_action('wp_ajax_askagento_recommend_cross_sell_download', function () {
    if (!check_ajax_referer('askagento_admin', 'nonce', false)) {
        wp_send_json_error(['message' => __('Security check failed. Please reload the page.', 'askagento')], 403);
    }

    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => __('Permission denied', 'askagento')]);
    }

    if (function_exists('wp_raise_memory_limit')) {
        wp_raise_memory_limit('admin');
    }

    $site_id = get_option('askagento_install_site_id', '');
    if (empty($site_id)) {
        wp_send_json_error(['message' => __('No installation ID found', 'askagento')]);
    }

    $result = askagento_recommend_cross_sell_fetch($site_id);
    if (is_wp_error($result)) {
        $payload = ['message' => $result->get_error_message()];
        if ($result->get_error_code() === 'not_published') {
            $payload['code'] = 'not_published';
        }
        wp_send_json_error($payload);
    }

    askagento_recommend_cross_sell_store_payload($result, $site_id);

    wp_send_json_success([
        'filename' => sanitize_file_name($site_id . '-cross-sell.json'),
        'payload' => $result,
        'preview_first_three' => askagento_recommend_cross_sell_build_preview_first_three($result),
    ]);
});

/**
 * AJAX: Export stored cross-sell recommendations JSON.
 */
add_action('wp_ajax_askagento_recommend_cross_sell_export_stored_json', function () {
    if (!check_ajax_referer('askagento_admin', 'nonce', false)) {
        wp_send_json_error(['message' => __('Security check failed. Please reload the page.', 'askagento')], 403);
    }

    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => __('Permission denied', 'askagento')]);
    }

    $raw = askagento_recommend_cross_sell_get_stored_payload_raw();
    if ($raw === '') {
        wp_send_json_error(['message' => __('No cross-sell recommendations stored on this shop yet. Download cross-sell recommendations first.', 'askagento')]);
    }

    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        wp_send_json_error(['message' => __('Stored recommendations are invalid. Download again.', 'askagento')]);
    }

    $pretty = wp_json_encode(
        $decoded,
        JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
    );
    if (!is_string($pretty) || $pretty === '') {
        wp_send_json_error(['message' => __('Could not encode recommendations JSON.', 'askagento')]);
    }

    $site_id = sanitize_file_name(get_option(ASKAGENTO_OPTION_CROSS_SELL_SITE_ID, get_option('askagento_install_site_id', 'site')));
    if ($site_id === '') {
        $site_id = 'recommendations';
    }
    $filename = sanitize_file_name($site_id . '-cross-sell-recommendations.json');
    if ($filename === '') {
        $filename = 'recommendations.json';
    }

    wp_send_json_success([
        'filename' => $filename,
        'body' => $pretty,
    ]);
});

/**
 * AJAX: Install cross-sell recommendations to WooCommerce products.
 */
add_action('wp_ajax_askagento_recommend_cross_sell_install', function () {
    if (!check_ajax_referer('askagento_admin', 'nonce', false)) {
        wp_send_json_error(['message' => __('Security check failed. Please reload the page.', 'askagento')], 403);
    }

    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => __('Permission denied', 'askagento')]);
    }

    if (function_exists('wp_raise_memory_limit')) {
        wp_raise_memory_limit('admin');
    }

    $raw_payload = askagento_recommend_cross_sell_get_stored_payload_raw();
    if (empty($raw_payload)) {
        wp_send_json_error(['message' => __('No cross-sell bundle stored on this shop. Use Install recommendations on Cross-sell - Setup first.', 'askagento')]);
    }

    if (function_exists('askagento_recommend_decode_install_payload')) {
        $payload = askagento_recommend_decode_install_payload('cross_sell', $raw_payload);
        if (is_wp_error($payload)) {
            wp_send_json_error(['message' => $payload->get_error_message()]);
        }
    } else {
        $payload = json_decode($raw_payload, true);
        if (!is_array($payload)) {
            wp_send_json_error(['message' => __('Stored recommendations are invalid. Download again.', 'askagento')]);
        }
    }

    $mode = isset($_POST['mode']) ? sanitize_key(wp_unslash($_POST['mode'])) : 'replace_all';
    if ($mode !== 'fill_missing') {
        $mode = 'replace_all';
    }

    $offset = isset($_POST['offset']) ? absint(wp_unslash($_POST['offset'])) : 0;
    $batch_limit = function_exists('askagento_recommend_install_batch_size')
        ? askagento_recommend_install_batch_size()
        : 25;

    try {
        $result = askagento_recommend_cross_sell_apply_to_shop($payload, $mode, [
            'offset' => $offset,
            'limit' => $batch_limit,
        ]);
    } catch (Throwable $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }

    if (is_wp_error($result)) {
        wp_send_json_error(['message' => $result->get_error_message()]);
    }

    wp_send_json_success($result);
});

/**
 * AJAX: Clear cross-sell recommendations from WooCommerce products.
 */
add_action('wp_ajax_askagento_recommend_cross_sell_clear', function () {
    if (!check_ajax_referer('askagento_admin', 'nonce', false)) {
        wp_send_json_error(['message' => __('Security check failed. Please reload the page.', 'askagento')], 403);
    }

    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => __('Permission denied', 'askagento')]);
    }

    $result = askagento_recommend_cross_sell_clear_links();
    wp_send_json_success($result);
});

/**
 * Fetch cross-sell bundle for autonomous/cron (daily cap) with stored fallback.
 *
 * @param string $site_id Installation site identifier.
 * @return array|WP_Error
 */
function askagento_recommend_cross_sell_resolve_payload_for_pipeline($site_id) {
    $result = askagento_recommend_cross_sell_fetch_if_daily_quota($site_id);
    if (!is_wp_error($result)) {
        return $result;
    }
    if ($result->get_error_code() !== 'daily_cap') {
        return $result;
    }

    $raw = askagento_recommend_cross_sell_get_stored_payload_raw();
    if ($raw === '') {
        return $result;
    }

    $decoded = json_decode($raw, true);
    if (!is_array($decoded) || askagento_recommend_cross_sell_payload_map($decoded) === []) {
        return $result;
    }

    return $decoded;
}

if (!defined('ASKAGENTO_RECOMMEND_CROSS_SELL_CRON_HOOK')) {
    define('ASKAGENTO_RECOMMEND_CROSS_SELL_CRON_HOOK', 'askagento_recommend_cross_sell_cron_event');
}

/**
 * AJAX: Cross-sell autonomous + installation status (Setup tab).
 */
add_action('wp_ajax_askagento_recommend_cross_sell_combined_admin_status', function () {
    if (!check_ajax_referer('askagento_admin', 'nonce', false)) {
        wp_send_json_error(['message' => __('Security check failed. Please reload the page.', 'askagento')], 403);
    }

    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => __('Permission denied', 'askagento')]);
    }

    $installation = [];
    $site_id = get_option('askagento_install_site_id', '');
    if ($site_id === '') {
        $installation['ok'] = false;
        $installation['message'] = __('No installation ID found', 'askagento');
    } elseif (function_exists('askagento_check_install_status')) {
        $remote = askagento_check_install_status($site_id);
        if (is_wp_error($remote)) {
            $installation['ok'] = false;
            $installation['message'] = $remote->get_error_message();
        } else {
            $installation['ok'] = true;
            $installation['payload'] = $remote;
        }
    } else {
        $installation['ok'] = true;
    }

    $next_cron_unix = wp_next_scheduled(ASKAGENTO_RECOMMEND_CROSS_SELL_CRON_HOOK);
    $last_run_raw = get_option('askagento_ai_cross_sell_auto_last_run', '');
    $last_err = get_option('askagento_ai_cross_sell_auto_last_error', []);
    $last_run = [];
    if (is_string($last_run_raw) && $last_run_raw !== '') {
        $decoded_run = json_decode($last_run_raw, true);
        $last_run = is_array($decoded_run) ? $decoded_run : [];
    }

    $autonomous = [
        'enabled' => (bool) get_option('askagento_ai_cross_sell_auto', false),
        'install_mode' => get_option('askagento_ai_cross_sell_auto_mode', 'replace_all') === 'fill_missing'
            ? 'fill_missing'
            : 'replace_all',
        'cron_next_unix' => $next_cron_unix ? (int) $next_cron_unix : null,
        'last_run' => $last_run,
        'last_error' => is_array($last_err) ? $last_err : [],
    ];

    wp_send_json_success(
        [
            'installation' => $installation,
            'autonomous' => $autonomous,
        ]
    );
});

function askagento_recommend_cross_sell_schedule_cron() {
    if (wp_next_scheduled(ASKAGENTO_RECOMMEND_CROSS_SELL_CRON_HOOK)) {
        return;
    }
    wp_schedule_event(time() + 240, 'daily', ASKAGENTO_RECOMMEND_CROSS_SELL_CRON_HOOK);
}

function askagento_recommend_cross_sell_unschedule_cron() {
    wp_clear_scheduled_hook(ASKAGENTO_RECOMMEND_CROSS_SELL_CRON_HOOK);
}

function askagento_recommend_cross_sell_maybe_schedule_cron() {
    if (!(bool) get_option('askagento_ai_cross_sell_auto', false)) {
        return;
    }
    askagento_recommend_cross_sell_schedule_cron();
}

/**
 * Regenerate cross-sell bundle (daily cap) and install using autonomous mode preference.
 *
 * @param string $context Optional slug for troubleshooting.
 */
function askagento_recommend_cross_sell_run_autonomous_pipeline($context = '') {
    unset($context);

    if (!(bool) get_option('askagento_ai_cross_sell_auto', false)) {
        return;
    }

    if (!askagento_install_api_is_enabled() || !function_exists('wc_get_product')) {
        return;
    }

    $site_id = get_option('askagento_install_site_id', '');
    if ($site_id === '') {
        return;
    }

    $result = askagento_recommend_cross_sell_resolve_payload_for_pipeline($site_id);
    if (is_wp_error($result)) {
        if ($result->get_error_code() === 'daily_cap') {
            return;
        }
        update_option(
            'askagento_ai_cross_sell_auto_last_error',
            [
                'time' => current_time('mysql'),
                'message' => $result->get_error_message(),
            ],
            false
        );

        return;
    }

    delete_option('askagento_ai_cross_sell_auto_last_error');
    askagento_recommend_cross_sell_store_payload($result, $site_id);

    $mode_raw = get_option('askagento_ai_cross_sell_auto_mode', 'replace_all');
    $install_mode = ($mode_raw === 'fill_missing') ? 'fill_missing' : 'replace_all';

    $apply = askagento_recommend_cross_sell_apply_to_shop($result, $install_mode);
    if (is_wp_error($apply)) {
        update_option(
            'askagento_ai_cross_sell_auto_last_error',
            [
                'time' => current_time('mysql'),
                'message' => $apply->get_error_message(),
            ],
            false
        );

        return;
    }

    update_option(
        'askagento_ai_cross_sell_auto_last_run',
        wp_json_encode(
            [
                'time' => current_time('mysql'),
                'mode' => $install_mode,
                'updated_products' => $apply['updated_products'] ?? 0,
                'linked_rows' => $apply['linked_rows'] ?? 0,
                'skipped_products' => $apply['skipped_products'] ?? 0,
            ],
            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
        ),
        false
    );
}

add_action(ASKAGENTO_RECOMMEND_CROSS_SELL_CRON_HOOK, static function () {
    askagento_recommend_cross_sell_run_autonomous_pipeline('cron');
});

add_action(
    'plugins_loaded',
    static function () {
        askagento_recommend_cross_sell_maybe_schedule_cron();
    },
    21
);

add_action(
    'updated_option_askagento_ai_cross_sell_auto',
    static function ($old_val, $value) {
        unset($old_val);
        if ((bool) $value) {
            askagento_recommend_cross_sell_schedule_cron();
        } else {
            askagento_recommend_cross_sell_unschedule_cron();
        }
    },
    10,
    2
);

add_action(
    'add_option_askagento_ai_cross_sell_auto',
    static function ($option, $value) {
        unset($option);
        if ((bool) $value) {
            askagento_recommend_cross_sell_schedule_cron();
        }
    },
    10,
    2
);

add_action(
    'upgrader_process_complete',
    static function ($_upgrader, $options) {
        unset($_upgrader);
        if (empty($options['type']) || 'plugin' !== $options['type'] || empty($options['action']) || 'update' !== $options['action']) {
            return;
        }

        $slugs = [];
        if (! empty($options['plugins']) && is_array($options['plugins'])) {
            $slugs = $options['plugins'];
        }
        if (! empty($options['plugin']) && is_string($options['plugin'])) {
            $slugs[] = $options['plugin'];
        }

        if (! defined('ASKAGENTO_PLUGIN_FILE')) {
            return;
        }

        foreach (array_unique($slugs) as $slug) {
            if ($slug === plugin_basename(ASKAGENTO_PLUGIN_FILE)) {
                askagento_recommend_cross_sell_maybe_schedule_cron();
                askagento_recommend_cross_sell_run_autonomous_pipeline('plugin_update');
                return;
            }
        }
    },
    10,
    2
);
