<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Exit if accessed directly
function wpsummarize_post_action(
    $post_id,
    $post,
    $update,
    $wpsummarize_post_settings,
    $update_on_edit
) {
    if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) || wpsummarize_is_translated_post( $post_id ) ) {
        return;
    }
    $wpsummarize_options = get_option( 'wpsummarize_options', [] );
    // Defaults to an empty array if not set
    if ( !is_array( $wpsummarize_post_settings ) ) {
        $wpsummarize_post_settings = [];
    }
    // Merge global settings with per-post settings
    $final_settings = array_merge( $wpsummarize_options, $wpsummarize_post_settings );
    // Determine whether to generate summary on publish or update
    $create_on_publish = ( isset( $_POST['_wpsummarize_post_settings']['create_on_publish'] ) ? $_POST['_wpsummarize_post_settings']['create_on_publish'] : '0' );
    // '1' for checked, '0' for unchecked
    $summarySet = get_post_meta( $post_id, '_wpsummarize_summary_set', true );
    if ( ('publish' === $post->post_status || 'future' === $post->post_status) && '1' === $create_on_publish && empty( $summarySet ) || $update && '1' === $update_on_edit ) {
        wpsummarize_add_summary_to_action_scheduler_queue( $post_id );
    } elseif ( isset( $_POST['wpsummarize_summary_content'] ) && !empty( $_POST['wpsummarize_summary_content'] ) ) {
        update_post_meta( $post_id, '_wpsummarize_summary_set', wp_kses_post( wp_unslash( $_POST['wpsummarize_summary_content'] ) ) );
        update_post_meta( $post_id, '_wpsummarize_summary_set_manual', intval( time() ) );
    }
}

// Auto-generate summary for posts created via REST API.
function wpsummarize_autogen_on_rest_insert(  $post, $request, $creating  ) {
    // Only on create (not updates via REST)
    if ( !$creating ) {
        return;
    }
    // Skip if summary already exists
    $existing_summary = get_post_meta( $post_id, '_wpsummarize_summary_set', true );
    if ( !empty( $existing_summary ) ) {
        return;
    }
    // get global options
    $wpsummarize_options = get_option( 'wpsummarize_options', [] );
    // Defaults to an empty array if not set
    // Check for creation on publish enabled
    $create_on_publish = ( isset( $wpsummarize_options['create_on_publish'] ) ? $wpsummarize_options['create_on_publish'] : '0' );
    // If nothing is set, default to standard posts
    if ( $create_on_publish != '1' ) {
        return;
    }
    // Only when published or scheduled
    if ( $post->post_status !== 'publish' && $post->post_status !== 'future' ) {
        return;
    }
    // Check for allowed post types or return
    $enabled_post_types = ( isset( $wpsummarize_options['wpsummarize_post_types_enabled'] ) ? $wpsummarize_options['wpsummarize_post_types_enabled'] : [] );
    // If nothing is set, default to standard posts
    if ( empty( $enabled_post_types ) ) {
        $enabled_post_types = ['post'];
    }
    if ( !in_array( $post->post_type, $enabled_post_types, true ) ) {
        return;
    }
    wpsummarize_add_summary_to_action_scheduler_queue( $post->ID );
}

add_action(
    'rest_after_insert_post',
    'wpsummarize_autogen_on_rest_insert',
    10,
    3
);
// Auto-generate summary for posts created programmatically (e.g., CyberSEO, WP All Import, etc.)
function wpsummarize_autogen_on_programmatic_insert(  $post_id, $post, $update  ) {
    // Skip if this is a revision or autosave
    if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
        return;
    }
    // Skip if this is coming from WordPress editor (has nonce)
    // This prevents conflict with wpsummarize_save_post_meta
    if ( isset( $_POST['wpsummarize_nonce'] ) ) {
        return;
    }
    // Skip if summary already exists
    $existing_summary = get_post_meta( $post_id, '_wpsummarize_summary_set', true );
    if ( !empty( $existing_summary ) ) {
        return;
    }
    // Only when published or scheduled
    if ( $post->post_status !== 'publish' && $post->post_status !== 'future' ) {
        return;
    }
    // Get global options
    $wpsummarize_options = get_option( 'wpsummarize_options', [] );
    // Check for creation on publish enabled
    $create_on_publish = ( isset( $wpsummarize_options['create_on_publish'] ) ? $wpsummarize_options['create_on_publish'] : '0' );
    if ( $create_on_publish != '1' ) {
        return;
    }
    // Check for allowed post types
    $enabled_post_types = ( isset( $wpsummarize_options['wpsummarize_post_types_enabled'] ) ? $wpsummarize_options['wpsummarize_post_types_enabled'] : [] );
    if ( empty( $enabled_post_types ) ) {
        $enabled_post_types = ['post'];
    }
    if ( !in_array( $post->post_type, $enabled_post_types, true ) ) {
        return;
    }
    wpsummarize_add_summary_to_action_scheduler_queue( $post_id );
}

add_action(
    'save_post',
    'wpsummarize_autogen_on_programmatic_insert',
    20,
    3
);
function wpsummarize_add_summary_to_action_scheduler_queue(  $post_id  ) {
    global $wpdb;
    update_post_meta( $post_id, 'wpsummarize_running_api', intval( time() ) );
    delete_post_meta( $post_id, '_wpsummarize_summary_set_manual' );
    // Check if there's already a scheduled action for this post
    $existing_actions = as_get_scheduled_actions( array(
        'hook'   => 'wpsummarize_generate_summary_hook',
        'args'   => array($post_id),
        'status' => ActionScheduler_Store::STATUS_PENDING,
    ), 'ids' );
    if ( empty( $existing_actions ) ) {
        // Schedule the new action
        $scheduled = as_schedule_single_action(
            time(),
            'wpsummarize_generate_summary_hook',
            array($post_id),
            'wpsummarize'
        );
        if ( $scheduled ) {
            update_post_meta( $post_id, 'wpsummarize_action_scheduled', intval( time() ) );
            // Run only this specific action
            $action_id = as_get_scheduled_actions( array(
                'hook'   => 'wpsummarize_generate_summary_hook',
                'args'   => array($post_id),
                'status' => ActionScheduler_Store::STATUS_PENDING,
            ), 'ids' );
            if ( !empty( $action_id ) ) {
                $action_id = reset( $action_id );
                // Get the first (and should be only) action ID
                $runner = new ActionScheduler_QueueRunner(ActionScheduler::store());
                $runner->process_action( $action_id );
            }
        } else {
        }
    } else {
        // Action already scheduled, no need to schedule again
    }
}

function wpsummarize_generate_summary(  $post_id  ) {
    $post = get_post( $post_id );
    wpsummarize_send_data_to_api( $post );
    delete_post_meta( $post->ID, 'wpsummarize_running_api' );
}

add_action(
    'wpsummarize_generate_summary_hook',
    'wpsummarize_generate_summary',
    10,
    1
);
function wpsummarize_queue_summary_async(  $post_id  ) {
    $post_id = absint( $post_id );
    if ( !$post_id ) {
        return false;
    }
    // Don't double-queue if a generation is genuinely already in flight.
    // (This also clears the flag if it is stale.)
    if ( wpsummarize_check_if_summary_is_generating( $post_id ) ) {
        return true;
    }
    // If an action is already pending for this post, leave it; just mark running.
    $existing_actions = as_get_scheduled_actions( array(
        'hook'   => 'wpsummarize_generate_summary_hook',
        'args'   => array($post_id),
        'status' => ActionScheduler_Store::STATUS_PENDING,
    ), 'ids' );
    update_post_meta( $post_id, 'wpsummarize_running_api', intval( time() ) );
    delete_post_meta( $post_id, '_wpsummarize_summary_set_manual' );
    if ( !empty( $existing_actions ) ) {
        // Already queued; AS will run it. Nothing more to do.
        return true;
    }
    $scheduled = as_schedule_single_action(
        time(),
        'wpsummarize_generate_summary_hook',
        array($post_id),
        'wpsummarize'
    );
    if ( $scheduled ) {
        update_post_meta( $post_id, 'wpsummarize_action_scheduled', intval( time() ) );
        return true;
    }
    // Scheduling failed — don't leave a running flag implying work is happening.
    delete_post_meta( $post_id, 'wpsummarize_running_api' );
    return false;
}

function wpsummarize_rename_post_meta_key(  $post_id, $old_key, $new_key  ) {
    global $wpdb;
    // Check if the old meta key exists
    $meta_exists = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = %s", $post_id, $old_key ) );
    if ( $meta_exists > 0 ) {
        // Update the meta key
        $wpdb->query( $wpdb->prepare(
            "UPDATE {$wpdb->postmeta} SET meta_key = %s WHERE meta_key = %s AND post_id = %d",
            $new_key,
            $old_key,
            $post_id
        ) );
    }
}

function wpsummarize_send_data_to_api(  $post  ) {
    if ( !$post || !is_a( $post, 'WP_Post' ) ) {
        return;
    }
    $wpsummarize_options = get_option( 'wpsummarize_options', [] );
    $wpsummarize_post_settings = get_post_meta( $post->ID, '_wpsummarize_post_settings', true );
    // Ensure settings are arrays
    $wpsummarize_options = ( is_array( $wpsummarize_options ) ? $wpsummarize_options : [] );
    $wpsummarize_post_settings = maybe_unserialize( $wpsummarize_post_settings );
    $wpsummarize_post_settings = ( is_array( $wpsummarize_post_settings ) ? $wpsummarize_post_settings : [] );
    $final_settings = array_merge( $wpsummarize_options, $wpsummarize_post_settings );
    // Get the API key
    $api_key = wpsummarize_get_api_key();
    // Get the API provider
    $ai_api_provider = get_option( 'wpsummarize_ai_api_provider', 'openai mini' );
    // Get the custom prompt
    $custom_prompt = get_option( 'wpsummarize_custom_prompt', '' );
    // Get full post content including ACF fields if enabled
    $full_content = ( function_exists( 'wpsummarize_get_full_post_content__premium_only' ) ? wpsummarize_get_full_post_content__premium_only( $post ) : $post->post_content );
    // Polylang
    if ( function_exists( 'pll_get_post_language' ) ) {
        $post_lang = pll_get_post_language( $post->ID, 'locale' );
        $default_lang = $final_settings['language'];
        if ( $post_lang && $default_lang && $post_lang != $default_lang ) {
            $final_settings['language'] = $post_lang;
        }
    }
    // Prepare the data, ensuring all values are set
    $data = [
        'post_title'        => $post->post_title,
        'post_content'      => $full_content,
        'post_url'          => get_permalink( $post->ID ),
        'final_settings'    => $final_settings,
        'locale'            => get_locale(),
        'license_id'        => '',
        'install_id'        => '',
        'site_private_key'  => '',
        'url'               => '',
        'wp_url'            => get_site_url(),
        'trialtf'           => false,
        'ai_provider'       => $ai_api_provider,
        'custom_prompt'     => $custom_prompt,
        'azure_endpoint'    => get_option( 'wpsummarize_azure_endpoint', '' ),
        'azure_deployment'  => get_option( 'wpsummarize_azure_deployment', '' ),
        'encrypted_api_key' => ( $api_key ? wpsummarize_encrypt_for_transit( $api_key ) : '' ),
    ];
    // Safely get Freemius data
    if ( function_exists( 'wpsummarize_fs' ) ) {
        $fs = wpsummarize_fs();
        if ( $fs ) {
            $license = $fs->_get_license();
            $site = $fs->get_site();
            if ( $license ) {
                $data['license_id'] = $license->id;
            }
            if ( $site ) {
                $data['install_id'] = $site->id;
                $data['site_private_key'] = $site->secret_key;
                $data['url'] = $site->url;
            }
        }
    }
    // Encode data to JSON, handling potential encoding issues
    $body = wp_json_encode( $data );
    if ( $body === false ) {
        return;
    }
    $api_url = 'https://wpsummarize.com/api_connect_wpsum.php';
    $args = [
        'body'        => $body,
        'headers'     => [
            'Content-Type'           => 'application/json',
            'X-WPSummarize-Site-Key' => wpsummarize_get_or_generate_site_key(),
        ],
        'data_format' => 'body',
        'timeout'     => 60,
    ];
    $response = wp_remote_post( $api_url, $args );
    $response_code = wp_remote_retrieve_response_code( $response );
    if ( $response_code != 200 ) {
        return;
    }
    // Check if response body is empty
    $response_body = wp_remote_retrieve_body( $response );
    if ( empty( $response_body ) ) {
        return;
    }
    // Decode the API response
    $api_response = json_decode( wp_remote_retrieve_body( $response ), true );
    // Check for success
    if ( isset( $api_response['success'] ) && $api_response['success'] === true ) {
        // Clear any previous API error notice on success
        delete_transient( 'wpsummarize_api_error' );
        // rename the set summary to make it a revision, available to get it back as set
        wpsummarize_rename_post_meta_key( $post->ID, '_wpsummarize_summary_set', '_wpsummarize_summary_revision' );
        // add the post meta with the summary
        update_post_meta( $post->ID, '_wpsummarize_summary_set', wp_kses_post( $api_response['summary'] ) );
        // Stamp the generation timestamp (Unix time) so the dashboard can display
        // and sort by when each summary was produced. Fires for every generation
        // path (single, batch, REST, programmatic) since they all funnel here.
        update_post_meta( $post->ID, '_wpsummarize_summary_generated', time() );
        wpsummarize_check_and_notify_token_limit();
    } else {
        // Check if it's a quota error
        if ( isset( $api_response['error_code'] ) && $api_response['error_code'] === 'insufficient_quota' ) {
            // Set the quota error notice (respecting 24-hour limit)
            wpsummarize_set_quota_error_notice( $ai_api_provider );
        } elseif ( isset( $api_response['error_message'] ) && !empty( $api_response['error_message'] ) ) {
            $error_message = "";
            $error_message = $api_response['error_message'];
            if ( !empty( $error_message ) ) {
                wpsummarize_set_api_error_notice( $error_message, $ai_api_provider, $post->ID );
            }
        }
    }
}

function wpsummarize_update_post_modified_date(  $post_id  ) {
    $post_data = array(
        'ID'                => $post_id,
        'post_modified'     => current_time( 'mysql' ),
        'post_modified_gmt' => current_time( 'mysql', 1 ),
    );
    wp_update_post( $post_data );
}

function wpsummarize_api_check_tokens(  $type  ) {
    // Prepare the data to be sent to the API
    $api_url = 'https://wpsummarize.com/api_connect_wpsum.php';
    // Set this to your API endpoint URL
    $body = [];
    if ( function_exists( 'wpsummarize_fs' ) ) {
        $fs = wpsummarize_fs();
        if ( $fs && method_exists( $fs, '_get_license' ) ) {
            $license = $fs->_get_license();
            if ( $license && isset( $license->id ) ) {
                $body['license_id'] = $license->id;
            }
        }
        if ( $fs && method_exists( $fs, 'get_site' ) ) {
            $site = $fs->get_site();
            if ( $site ) {
                if ( isset( $site->id ) ) {
                    $body['install_id'] = $site->id;
                }
                if ( isset( $site->secret_key ) ) {
                    $body['site_private_key'] = $site->secret_key;
                }
                if ( isset( $site->url ) ) {
                    $body['url'] = $site->url;
                }
            }
        }
        // additional url info check
        $body['wp_url'] = get_site_url();
    }
    $body['trialtf'] = false;
    if ( isset( $type ) ) {
        $body['type'] = $type;
    }
    $json_body = wp_json_encode( $body );
    // Set up the request headers
    $args = [
        'body'        => $json_body,
        'headers'     => [
            'Content-Type' => 'application/json',
        ],
        'data_format' => 'body',
        'timeout'     => 60,
    ];
    // Send the request
    $response = wp_remote_post( $api_url, $args );
    // Check for errors in the response
    if ( is_wp_error( $response ) ) {
        return;
    }
    $response_code = wp_remote_retrieve_response_code( $response );
    if ( $response_code != 200 ) {
        return;
    }
    // Check if response body is empty
    $response_body = wp_remote_retrieve_body( $response );
    if ( empty( $response_body ) ) {
        return;
    }
    // Decode the API response
    $api_response = json_decode( wp_remote_retrieve_body( $response ), true );
    if ( isset( $api_response['success'] ) && $api_response['success'] === true ) {
        return $api_response;
    } else {
        // Handle failed API response
    }
}

function wpsummarize_set_quota_error_notice(  $ai_provider = 'openai mini'  ) {
    $last_notice_time = get_option( 'wpsummarize_last_quota_notice', 0 );
    $current_time = time();
    // Only show notice if 24 hours have passed since the last one
    if ( $current_time - $last_notice_time > 86400 ) {
        // 86400 seconds = 24 hours
        set_transient( 'wpsummarize_quota_error', $ai_provider, 7 * DAY_IN_SECONDS );
        update_option( 'wpsummarize_last_quota_notice', $current_time );
    }
}

add_action( 'admin_notices', 'wpsummarize_display_quota_error_notice' );
function wpsummarize_display_quota_error_notice() {
    $quota_error = get_transient( 'wpsummarize_quota_error' );
    if ( $quota_error ) {
        $ai_provider_name = wpsummarize_get_provider_display_name( $quota_error );
        ?>
        <div class="notice notice-error is-dismissible wpsummarize-quota-error">
            <p>
                <strong><?php 
        echo esc_html__( 'WPSummarize: AI Credits Exhausted', 'wpsummarize' );
        ?></strong>
            </p>
            <p>
                <?php 
        printf( esc_html__( 'Your %s API credits have been exhausted. Please add credits to your %s account to continue generating summaries.', 'wpsummarize' ), '<strong>' . esc_html( $ai_provider_name ) . '</strong>', esc_html( $ai_provider_name ) );
        ?>
            </p>
            <p>
                <a href="<?php 
        echo esc_url( wpsummarize_get_provider_billing_url( $quota_error ) );
        ?>" 
                   class="button button-primary" 
                   target="_blank">
                    <?php 
        echo esc_html__( 'Manage API Credits', 'wpsummarize' );
        ?>
                </a>
                <button type="button" class="button wpsummarize-dismiss-quota-notice" data-notice="quota_error">
                    <?php 
        echo esc_html__( 'Dismiss', 'wpsummarize' );
        ?>
                </button>
            </p>
        </div>
        <?php 
    }
}

/**
 * Get display name for AI provider
 */
function wpsummarize_get_provider_display_name(  $provider  ) {
    $names = [
        'openai mini' => 'OpenAI',
        'openai full' => 'OpenAI',
        'anthropic'   => 'Anthropic',
        'gemini mini' => 'Gemini',
        'gemini full' => 'Gemini',
    ];
    return ( isset( $names[$provider] ) ? $names[$provider] : ucfirst( $provider ) );
}

function wpsummarize_get_provider_billing_url(  $provider  ) {
    $urls = [
        'openai mini' => 'https://platform.openai.com/account/billing',
        'openai full' => 'https://platform.openai.com/account/billing',
        'anthropic'   => 'https://console.anthropic.com/settings/billing',
        'gemini mini' => 'https://aistudio.google.com/usage',
        'gemini full' => 'https://aistudio.google.com/usage',
    ];
    return ( isset( $urls[$provider] ) ? $urls[$provider] : '#' );
}

add_action( 'wp_ajax_wpsummarize_dismiss_quota_notice', 'wpsummarize_dismiss_quota_notice_ajax' );
function wpsummarize_dismiss_quota_notice_ajax() {
    check_ajax_referer( 'wpsummarize_nonce_ajax', 'nonce' );
    if ( isset( $_POST['notice_type'] ) && $_POST['notice_type'] === 'quota_error' ) {
        delete_transient( 'wpsummarize_quota_error' );
        wp_send_json_success( [
            'message' => 'Notice dismissed',
        ] );
    }
    wp_send_json_error( [
        'message' => 'Invalid request',
    ] );
}

/**
 * Store a generic API error for display as an admin notice.
 * Respects a 6-hour throttle so the same error doesn't spam the user.
 */
function wpsummarize_set_api_error_notice(  $error_message, $ai_provider = 'openai mini', $post_id = 0  ) {
    $last_error_time = get_option( 'wpsummarize_last_api_error_notice', 0 );
    $current_time = time();
    // Throttle: only store a new error if 6 hours have passed since the last one
    if ( $current_time - $last_error_time > 3600 * 6 ) {
        $error_data = array(
            'message'    => sanitize_text_field( $error_message ),
            'provider'   => sanitize_text_field( $ai_provider ),
            'post_id'    => intval( $post_id ),
            'post_title' => ( $post_id ? get_the_title( $post_id ) : '' ),
            'timestamp'  => $current_time,
        );
        set_transient( 'wpsummarize_api_error', $error_data, 7 * DAY_IN_SECONDS );
        update_option( 'wpsummarize_last_api_error_notice', $current_time );
    }
}

/**
 * Display the generic API error notice in the admin.
 */
function wpsummarize_display_api_error_notice() {
    // Don't show if quota error is active (it has its own specific notice)
    if ( get_transient( 'wpsummarize_quota_error' ) ) {
        return;
    }
    $error_data = get_transient( 'wpsummarize_api_error' );
    if ( !$error_data || !is_array( $error_data ) ) {
        return;
    }
    $provider_name = wpsummarize_get_provider_display_name( ( isset( $error_data['provider'] ) ? $error_data['provider'] : '' ) );
    $error_message = ( isset( $error_data['message'] ) ? $error_data['message'] : esc_html__( 'An unknown error occurred.', 'wpsummarize' ) );
    $post_title = ( isset( $error_data['post_title'] ) ? $error_data['post_title'] : '' );
    $timestamp = ( isset( $error_data['timestamp'] ) ? $error_data['timestamp'] : 0 );
    // Format time ago
    $time_ago = '';
    if ( $timestamp ) {
        $diff = time() - $timestamp;
        if ( $diff < 60 ) {
            $time_ago = esc_html__( 'just now', 'wpsummarize' );
        } elseif ( $diff < 3600 ) {
            $minutes = intval( $diff / 60 );
            $time_ago = sprintf( 
                /* translators: %d: number of minutes */
                _n(
                    '%d minute ago',
                    '%d minutes ago',
                    $minutes,
                    'wpsummarize'
                ),
                $minutes
             );
        } elseif ( $diff < 86400 ) {
            $hours = intval( $diff / 3600 );
            $time_ago = sprintf( 
                /* translators: %d: number of hours */
                _n(
                    '%d hour ago',
                    '%d hours ago',
                    $hours,
                    'wpsummarize'
                ),
                $hours
             );
        } else {
            $days = intval( $diff / 86400 );
            $time_ago = sprintf( 
                /* translators: %d: number of days */
                _n(
                    '%d day ago',
                    '%d days ago',
                    $days,
                    'wpsummarize'
                ),
                $days
             );
        }
    }
    // Detect if the error message contains a URL the user should visit
    $action_url = '';
    if ( preg_match( '/(https?:\\/\\/[^\\s]+)/', $error_message, $matches ) ) {
        $action_url = $matches[1];
        // Clean trailing punctuation from URL
        $action_url = rtrim( $action_url, '.,;:)' );
    }
    ?>
    <div class="notice notice-error is-dismissible wpsummarize-api-error-notice">
        <p>
            <strong><?php 
    printf( 
        /* translators: %s: AI provider name */
        esc_html__( 'WPSummarize: %s API Error', 'wpsummarize' ),
        esc_html( $provider_name )
     );
    ?></strong>
        </p>
        <p>
            <?php 
    echo esc_html( $error_message );
    ?>
        </p>
        <?php 
    if ( !empty( $post_title ) ) {
        ?>
            <p style="color: #646970; font-size: 13px;">
                <?php 
        printf( 
            /* translators: %1$s: post title, %2$s: time ago */
            esc_html__( 'Failed while generating summary for "%1$s" (%2$s).', 'wpsummarize' ),
            esc_html( $post_title ),
            esc_html( $time_ago )
         );
        ?>
            </p>
        <?php 
    }
    ?>
        <p>
            <?php 
    if ( !empty( $action_url ) ) {
        ?>
                <a href="<?php 
        echo esc_url( $action_url );
        ?>" 
                   class="button button-primary" 
                   target="_blank">
                    <?php 
        echo esc_html__( 'Fix This Issue', 'wpsummarize' );
        ?>
                </a>
            <?php 
    }
    ?>
            <a href="<?php 
    echo esc_url( admin_url( 'admin.php?page=wpsummarize_settings' ) );
    ?>" 
               class="button <?php 
    echo ( empty( $action_url ) ? 'button-primary' : 'button-secondary' );
    ?>">
                <?php 
    echo esc_html__( 'Check Settings', 'wpsummarize' );
    ?>
            </a>
            <button type="button" class="button wpsummarize-dismiss-api-error-notice" data-notice="wpsummarize_api_error" style="margin-left: 5px;">
                <?php 
    echo esc_html__( 'Dismiss', 'wpsummarize' );
    ?>
            </button>
        </p>
    </div>
    <?php 
}

add_action( 'admin_notices', 'wpsummarize_display_api_error_notice' );
/**
 * AJAX handler to dismiss the generic API error notice.
 */
function wpsummarize_dismiss_api_error_notice_ajax() {
    check_ajax_referer( 'wpsummarize_nonce_ajax', 'nonce' );
    if ( !current_user_can( 'manage_options' ) ) {
        wp_send_json_error( [
            'message' => 'Insufficient permissions',
        ] );
        return;
    }
    if ( isset( $_POST['notice_type'] ) && $_POST['notice_type'] === 'wpsummarize_api_error' ) {
        delete_transient( 'wpsummarize_api_error' );
        wp_send_json_success( [
            'message' => 'Notice dismissed',
        ] );
    }
    wp_send_json_error( [
        'message' => 'Invalid request',
    ] );
}

add_action( 'wp_ajax_wpsummarize_dismiss_api_error_notice', 'wpsummarize_dismiss_api_error_notice_ajax' );
function wpsummarize_check_and_notify_token_limit() {
    // Only check for users who can manage options (admins)
    if ( !current_user_can( 'manage_options' ) ) {
        return false;
    }
    if ( function_exists( 'wpsummarize_fs' ) ) {
        if ( wpsummarize_fs()->can_use_premium_code() && !wpsummarize_fs()->is_trial() ) {
            return false;
        }
    }
    // Get tokens left
    $tokens_left = wpsummarize_api_check_tokens( 'tokens_left' );
    // If tokens are at 0, set the notice
    if ( $tokens_left === 0 || $tokens_left === '0' ) {
        return wpsummarize_set_token_limit_notice();
    }
    return false;
}

function wpsummarize_set_token_limit_notice() {
    $last_notice_time = get_option( 'wpsummarize_last_token_limit_notice', 0 );
    $current_time = time();
    // Only show notice if 24 hours have passed since the last one
    if ( $current_time - $last_notice_time > 86400 ) {
        // 86400 seconds = 24 hours
        set_transient( 'wpsummarize_token_limit_reached', true, 7 * DAY_IN_SECONDS );
        update_option( 'wpsummarize_last_token_limit_notice', $current_time );
        return true;
    }
    return false;
}

function wpsummarize_display_token_limit_notice() {
    // Don't show if quota error notice is active (quota errors have priority)
    $quota_error = get_transient( 'wpsummarize_quota_error' );
    if ( $quota_error ) {
        return;
        // Quota error notice will show instead
    }
    // Check if token limit notice should be shown
    $token_limit_reached = get_transient( 'wpsummarize_token_limit_reached' );
    if ( $token_limit_reached ) {
        // Get plan information
        $plan_name = 'Free';
        if ( function_exists( 'wpsummarize_fs' ) ) {
            $fs = wpsummarize_fs();
            if ( $fs->is_trial() ) {
                $plan_name = 'Trial';
            } elseif ( $fs->is_free_plan() ) {
                $plan_name = 'Free';
            }
        }
        ?>
        <div class="notice notice-warning is-dismissible wpsummarize-token-limit-notice">
            <p>
                <strong><?php 
        echo esc_html__( 'WPSummarize: Monthly Token Limit Reached', 'wpsummarize' );
        ?></strong>
            </p>
            <p>
                <?php 
        printf( esc_html__( 'You have reached your monthly token limit on the %s plan. Upgrade to continue generating summaries.', 'wpsummarize' ), '<strong>' . esc_html( $plan_name ) . '</strong>' );
        ?>
            </p>
            <p>
                <?php 
        if ( function_exists( 'wpsummarize_fs' ) ) {
            ?>
                    <a href="<?php 
            echo esc_url( wpsummarize_fs()->get_upgrade_url() );
            ?>" 
                       class="button button-primary">
                        <?php 
            echo esc_html__( 'Upgrade Plan', 'wpsummarize' );
            ?>
                    </a>
                <?php 
        }
        ?>
                <button type="button" 
                        class="button wpsummarize-dismiss-token-limit-notice" 
                        data-notice="token_limit"
                        style="margin-left: 10px;">
                    <?php 
        echo esc_html__( 'Dismiss', 'wpsummarize' );
        ?>
                </button>
            </p>
        </div>
        <?php 
    }
}

add_action( 'admin_notices', 'wpsummarize_display_token_limit_notice' );
function wpsummarize_dismiss_token_limit_notice_ajax() {
    if ( !isset( $_POST['nonce'] ) || !wp_verify_nonce( $_POST['nonce'], 'wpsummarize_nonce_ajax' ) ) {
        wp_send_json_error( [
            'message' => 'Invalid security token',
        ] );
        return;
    }
    if ( !current_user_can( 'manage_options' ) ) {
        wp_send_json_error( [
            'message' => 'Insufficient permissions',
        ] );
        return;
    }
    // Process the dismissal
    if ( isset( $_POST['notice_type'] ) && $_POST['notice_type'] === 'token_limit' ) {
        delete_transient( 'wpsummarize_token_limit_reached' );
        wp_send_json_success( [
            'message' => 'Notice dismissed successfully',
        ] );
    } else {
        wp_send_json_error( [
            'message' => 'Invalid notice type',
        ] );
    }
}

add_action( 'wp_ajax_wpsummarize_dismiss_token_limit_notice', 'wpsummarize_dismiss_token_limit_notice_ajax' );
function wpsummarize_clear_token_limit_notice() {
    delete_transient( 'wpsummarize_token_limit_reached' );
    delete_option( 'wpsummarize_last_token_limit_notice' );
}
