<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/automarketer-ai.php
// Description: AutoMarketer AI — main plugin bootstrap - NUCLEAR+++
// Last Edited: 2026-04-02
// Plugin Name: AutoMarketer AI
// Plugin URI: https://automarketer-ai.com
// Description: AI-powered marketing automation for Facebook and beyond — Nuclear Fancy Pants Edition™ (NUCLEAR+++)
// Version: 1.4.41
// Requires at least: 6.0
// Requires PHP: 8.2
// Author: Ron Seigel
// Author URI: https://automarketer-ai.com
// License: GPL-2.0-or-later
// License URI: https://www.gnu.org/licenses/gpl-2.0.html
// Text Domain: automarketer-ai
// Domain Path: /languages
// ==================================================

// No direct access
defined('ABSPATH') || exit;

// --------------------------------------------------
// Constants — defined before any includes
// --------------------------------------------------
define('AMAI_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('AMAI_PLUGIN_URL', plugin_dir_url(__FILE__));
define('AMAI_VERSION', '1.4.41');

// Core API URL — override in wp-config.php if needed
if (!defined('AMAI_CORE_URL')) {
    define('AMAI_CORE_URL', 'https://core.automarketer-ai.com');
}

// HMAC secret for Core → WP webhook callbacks — must be set in wp-config.php
if (!defined('AMAI_WP_CALLBACK_SECRET')) {
    define('AMAI_WP_CALLBACK_SECRET', '');
}

// --------------------------------------------------
// Composer autoloader
// --------------------------------------------------
$amai_autoload = AMAI_PLUGIN_DIR . 'vendor/autoload.php';
if (is_file($amai_autoload)) {
    require_once $amai_autoload;
}
unset($amai_autoload);

// --------------------------------------------------
// Required includes — order matters
// --------------------------------------------------
require_once AMAI_PLUGIN_DIR . 'includes/module-interface.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-abstract-ai-provider.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-abstract-email-provider.php';
require_once AMAI_PLUGIN_DIR . 'includes/image-provider-interface.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-image-provider.php';
require_once AMAI_PLUGIN_DIR . 'modules/img-flux.php';
require_once AMAI_PLUGIN_DIR . 'modules/img-sd.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-stats-engine.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-model-watcher.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-media-cleanup.php';
require_once AMAI_PLUGIN_DIR . 'includes/channel-interface.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-migration-runner.php';
require_once AMAI_PLUGIN_DIR . '/includes/class-install-handler.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-outbound-links.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-link-preserver.php';
require_once AMAI_PLUGIN_DIR . 'migrations/001_business_profile_and_facebook_connection.php';
require_once AMAI_PLUGIN_DIR . 'migrations/002_scheduled_posts.php';
require_once AMAI_PLUGIN_DIR . 'migrations/003_scheduled_posts_utc.php';
require_once AMAI_PLUGIN_DIR . 'migrations/004_business_profile_timezone.php';
require_once AMAI_PLUGIN_DIR . 'migrations/005_waitlist.php';
require_once AMAI_PLUGIN_DIR . 'migrations/006_media_location_feeling.php';
require_once AMAI_PLUGIN_DIR . 'migrations/007_unsplash_image.php';
require_once AMAI_PLUGIN_DIR . 'migrations/008_batch_unique_key.php';
require_once AMAI_PLUGIN_DIR . 'migrations/009_instagram_account_id.php';
require_once AMAI_PLUGIN_DIR . 'migrations/010_channel_column.php';
require_once AMAI_PLUGIN_DIR . 'migrations/011_post_stats.php';
require_once AMAI_PLUGIN_DIR . 'migrations/012_business_profile_facebook_bio.php';
require_once AMAI_PLUGIN_DIR . 'migrations/013_post_type_enum_expand.php';
require_once AMAI_PLUGIN_DIR . 'migrations/014_linkedin_connection.php';
require_once AMAI_PLUGIN_DIR . 'migrations/015_tiktok_connection.php';
require_once AMAI_PLUGIN_DIR . 'migrations/016_x_connection.php';
require_once AMAI_PLUGIN_DIR . 'migrations/017_generation_batch_width.php';
require_once AMAI_PLUGIN_DIR . 'migrations/018_bounces_table.php';
require_once AMAI_PLUGIN_DIR . 'migrations/019_google_connection.php';
require_once AMAI_PLUGIN_DIR . 'migrations/020_abandoned_carts.php';
require_once AMAI_PLUGIN_DIR . 'migrations/021_abandoned_carts_raw_total.php';
require_once AMAI_PLUGIN_DIR . 'migrations/022_abandoned_carts_sequence.php';
require_once AMAI_PLUGIN_DIR . 'migrations/023_competitor_radar.php';
require_once AMAI_PLUGIN_DIR . 'migrations/024_blog_schedule.php';
require_once AMAI_PLUGIN_DIR . 'migrations/025_email_contacts.php';
require_once AMAI_PLUGIN_DIR . 'migrations/026_nudge_log.php';
require_once AMAI_PLUGIN_DIR . 'migrations/027_outbound_links.php';
require_once AMAI_PLUGIN_DIR . 'migrations/028_abandoned_carts_unsub_token.php';
require_once AMAI_PLUGIN_DIR . 'migrations/029_abandoned_carts_phone.php';
require_once AMAI_PLUGIN_DIR . 'migrations/030_usermeta_isolation.php';
require_once AMAI_PLUGIN_DIR . 'migrations/031_encrypt_api_keys.php';
require_once AMAI_PLUGIN_DIR . 'migrations/032_nudge_log_dismissed.php';
require_once AMAI_PLUGIN_DIR . 'migrations/033_scheduled_posts_platform_ids.php';
require_once AMAI_PLUGIN_DIR . 'migrations/034_social_comments.php';
require_once AMAI_PLUGIN_DIR . 'migrations/035_wp_comment_id.php';
require_once AMAI_PLUGIN_DIR . 'migrations/036_comment_form.php';
require_once AMAI_PLUGIN_DIR . 'migrations/037_product_catalog.php';
require_once AMAI_PLUGIN_DIR . 'migrations/038_product_views.php';
require_once AMAI_PLUGIN_DIR . 'migrations/039_drop_waitlist.php';
require_once AMAI_PLUGIN_DIR . 'migrations/040_google_reviews.php';
require_once AMAI_PLUGIN_DIR . 'migrations/041_competitor_urls.php';
require_once AMAI_PLUGIN_DIR . 'migrations/042_gap_topic_queue.php';
require_once AMAI_PLUGIN_DIR . 'migrations/043_ga4_connection.php';
require_once AMAI_PLUGIN_DIR . 'migrations/044_ga4_metrics.php';
require_once AMAI_PLUGIN_DIR . 'migrations/045_clusters.php';
require_once AMAI_PLUGIN_DIR . 'migrations/046_comment_sentiment.php';
require_once AMAI_PLUGIN_DIR . 'migrations/047_pinterest_connection.php';
require_once AMAI_PLUGIN_DIR . 'migrations/048_yelp_connection.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-product-view-tracker.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-business-profile.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-key-vault.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-seo-data.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-seo-analyzer.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-seo-head.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-seo-sitemap.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-seo-meta-box.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-category-assigner.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-plan-enforcer.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-blog-generator.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-blog-scheduler.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-blog-announcer.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-store-channel.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-product-catalog.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-product-engine.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-comment-fetcher.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-hot-thread-alerter.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-sentiment-scorer.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-review-velocity.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-comment-responder.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-comment-digest.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-review-fetcher.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-review-responder.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-comment-form.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-bg-optimizer.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-content-freshness.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-link-checker.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-facebook-auth.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-linkedin-auth.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-tiktok-auth.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-facebook-channel.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-instagram-channel.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-linkedin-channel.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-tiktok-channel.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-x-auth.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-google-auth.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-pinterest-auth.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-x-channel.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-google-channel.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-pinterest-channel.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-yelp-auth.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-yelp-channel.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-facebook-disconnect.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-instagram-disconnect.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-post-actions.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-posting-engine.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-ai-provider-sync.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-license-handler.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-nudge-engine.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-post-generator.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-content-engine.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-performance-analyzer.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-best-time-learner.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-competitor-analyzer.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-competitor-gap.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-ga4-auth.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-ga4-sync.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-cluster-builder.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-gap-topic-queue.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-unsplash.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-social-page.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-marketing-site.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-abandoned-cart.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-sms-provider.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-settings-page.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-email-templates.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-mailer.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-admin-page.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-webhook-receiver.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-bounce-handler.php';
require_once AMAI_PLUGIN_DIR . 'includes/class-update-checker.php';
require_once AMAI_PLUGIN_DIR . 'includes/provider-help-steps.php';
require_once AMAI_PLUGIN_DIR . 'includes/billing.php';

// --------------------------------------------------
// Namespace imports
// --------------------------------------------------
use AutoMarketerAI\NudgeEngine;
use AutoMarketerAI\AdminPage;
use AutoMarketerAI\BusinessProfile;
use AutoMarketerAI\ContentEngine;
use AutoMarketerAI\StoreChannel;
use AutoMarketerAI\ProductCatalog;
use AutoMarketerAI\ProductEngine;
use AutoMarketerAI\ProductViewTracker;
use AutoMarketerAI\FacebookAuth;
use AutoMarketerAI\LinkedInAuth;
use AutoMarketerAI\TikTokAuth;
use AutoMarketerAI\XAuth;
use AutoMarketerAI\XChannel;
use AutoMarketerAI\GoogleAuth;
use AutoMarketerAI\GoogleChannel;
use AutoMarketerAI\TikTokChannel;
use AutoMarketerAI\LinkedInChannel;
use AutoMarketerAI\FacebookDisconnect;
use AutoMarketerAI\InstagramDisconnect;
use AutoMarketerAI\MigrationRunner;
use AutoMarketerAI\PostActions;
use AutoMarketerAI\PostingEngine;
use AutoMarketerAI\SocialPage;
use AutoMarketerAI\WebhookReceiver;
use AutoMarketerAI\StatsEngine;
use AutoMarketerAI\ModelWatcher;
use AutoMarketerAI\MediaCleanup;
use AutoMarketerAI\MarketingSite;
use AutoMarketerAI\SettingsPage;
use AutoMarketerAI\Mailer;
use AutoMarketerAI\AbandonedCart;
use AutoMarketerAI\BounceHandler;
use AutoMarketerAI\UpdateChecker;
use AutoMarketerAI\PinterestAuth;
use AutoMarketerAI\PinterestChannel;
use AutoMarketerAI\YelpAuth;
use AutoMarketerAI\YelpChannel;

// --------------------------------------------------
// Boot
// --------------------------------------------------
AdminPage::init();
NudgeEngine::init();
SocialPage::init();
if (defined('AMAI_IS_PLATFORM_OWNER') && AMAI_IS_PLATFORM_OWNER) { MarketingSite::init(); }
SettingsPage::init();
Mailer::init();
AbandonedCart::init();
FacebookDisconnect::init();
InstagramDisconnect::init();
PostActions::init();
PostingEngine::init();
StatsEngine::init();
ModelWatcher::init();
MediaCleanup::init();
ContentEngine::init();
ProductCatalog::init();
ProductEngine::init();
ProductViewTracker::registerInterval();
ProductViewTracker::init();
\AutoMarketerAI\SeoAnalyzer::register();
\AutoMarketerAI\SeoHead::register();
\AutoMarketerAI\SeoSitemap::register();
\AutoMarketerAI\SeoMetaBox::register();
AutoMarketerAI\CategoryAssigner::register();
if (in_array('blog-generator', (array) get_option('amai_active_modules', []), true)) {
    AutoMarketerAI\BlogGenerator::register();
    AutoMarketerAI\BlogScheduler::register();
    \AutoMarketerAI\ClusterBuilder::register();
    AutoMarketerAI\BlogAnnouncer::register();
    AutoMarketerAI\BgOptimizer::register();
}
// Classic Editor enforcement — active when Content Optimizer module is on
if (in_array('content-optimizer', (array) get_option('amai_active_modules', []), true)) {
    add_filter('use_block_editor_for_post', '__return_false', 100);
    add_filter('use_block_editor_for_post_type', '__return_false', 100);
}
AutoMarketerAI\ContentFreshness::register();
AutoMarketerAI\LinkChecker::register();
\AutoMarketerAI\CompetitorGap::register();
WebhookReceiver::init();
BounceHandler::register();
UpdateChecker::register();
if (in_array('comment-manager', (array) get_option('amai_active_modules', []), true)) {
    AutoMarketerAI\CommentFetcher::register();
    AutoMarketerAI\CommentForm::register();
    AutoMarketerAI\CommentDigest::register();
}

AutoMarketerAI\HotThreadAlerter::register();
AutoMarketerAI\SentimentScorer::register();
AutoMarketerAI\ReviewVelocity::register();
if (in_array('review-responder', (array) get_option('amai_active_modules', []), true)) {
    AutoMarketerAI\ReviewFetcher::init();
    AutoMarketerAI\ReviewResponder::init();
}

// --------------------------------------------------
// Blog morning nudge cron handler
add_action(AutoMarketerAI\BlogScheduler::HOOK_MORNING, function (): void {
    AutoMarketerAI\BlogScheduler::morningCheck();
});
// Blog afternoon auto-draft cron handler
add_action(AutoMarketerAI\BlogScheduler::HOOK_AFTERNOON, function (): void {
    AutoMarketerAI\BlogScheduler::afternoonCheck();
});

// Facebook token refresh — daily cron handler
// --------------------------------------------------
add_action(FacebookAuth::CRON_HOOK, 'amai_run_fb_token_refresh');
function amai_run_fb_token_refresh(): void
{
    FacebookAuth::maybeRefreshToken();
}

// --------------------------------------------------
// LinkedIn token refresh — daily cron handler
// --------------------------------------------------
add_action(LinkedInAuth::CRON_HOOK, 'amai_run_li_token_refresh');
function amai_run_li_token_refresh(): void
{
    LinkedInAuth::maybeRefreshToken();
}
// --------------------------------------------------
// TikTok token refresh - twice-daily cron handler
// TikTok access tokens expire every 24 hours.
// --------------------------------------------------
add_action(TikTokAuth::CRON_HOOK, 'amai_run_tk_token_refresh');
function amai_run_tk_token_refresh(): void
{
    TikTokAuth::maybeRefreshToken();
}
// --------------------------------------------------
// X token refresh - hourly cron handler
// X access tokens expire every 2 hours.
// --------------------------------------------------
add_action(XAuth::CRON_HOOK, 'amai_run_x_token_refresh');
function amai_run_x_token_refresh(): void
{
    XAuth::refreshAccessToken();
}
// --------------------------------------------------
// Google token refresh - twice-daily cron handler
// --------------------------------------------------
add_action(GoogleAuth::CRON_HOOK, 'amai_run_google_token_refresh');
function amai_run_google_token_refresh(): void
{
    GoogleAuth::refreshAccessToken();
}

add_action(PinterestAuth::CRON_HOOK, 'amai_run_pin_token_refresh');
function amai_run_pin_token_refresh(): void
{
    PinterestAuth::maybeRefreshToken();
}

add_action(YelpAuth::CRON_HOOK, 'amai_run_yelp_token_refresh');
function amai_run_yelp_token_refresh(): void
{
    YelpAuth::maybeRefreshToken();
}
// --------------------------------------------------
// Posting Engine — hourly cron handler
// --------------------------------------------------
add_action(PostingEngine::CRON_HOOK, 'amai_run_posting_engine');
function amai_run_posting_engine(): void
{
    PostingEngine::run();
}

// --------------------------------------------------
// Capability grant — runs on every load to cover
// installs where activation hook has already fired
// --------------------------------------------------
add_action('init', 'amai_grant_admin_capability');
AutoMarketerAI\InstallHandler::register();
function amai_grant_admin_capability(): void
{
    $role = get_role('administrator');
    if ($role instanceof WP_Role && !$role->has_cap('manage_automarketer_ai')) {
        $role->add_cap('manage_automarketer_ai');
    }
}

// --------------------------------------------------
// TikTok OAuth callback rewrite rule
// Redirect URI: https://automarketer-ai.com/tiktok/callback
// --------------------------------------------------
add_action('init', 'amai_tk_register_rewrite');
function amai_tk_register_rewrite(): void
{
    add_rewrite_rule(
        '^tiktok/callback/?$',
        'index.php?amai_tk_callback=1',
        'top'
    );
}
add_filter('query_vars', 'amai_tk_query_vars');
function amai_tk_query_vars(array $vars): array
{
    $vars[] = 'amai_tk_callback';
    return $vars;
}
add_action('template_redirect', 'amai_tk_handle_callback');
function amai_tk_handle_callback(): void
{
    if ((int) get_query_var('amai_tk_callback', 0) !== 1) {
        return;
    }
    if (!is_user_logged_in() || !current_user_can('manage_automarketer_ai')) {
        wp_safe_redirect(home_url('/'));
        exit;
    }
    TikTokAuth::handleCallback();
}
// --------------------------------------------------
// X OAuth callback rewrite rule
// Redirect URI: https://automarketer-ai.com/x/callback
// --------------------------------------------------
add_action('init', 'amai_x_register_rewrite');
function amai_x_register_rewrite(): void
{
    add_rewrite_rule(
        '^x/callback/?$',
        'index.php?amai_x_callback=1',
        'top'
    );
}
add_filter('query_vars', 'amai_x_query_vars');
function amai_x_query_vars(array $vars): array
{
    $vars[] = 'amai_x_callback';
    return $vars;
}
add_action('template_redirect', 'amai_x_handle_callback');
function amai_x_handle_callback(): void
{
    if ((int) get_query_var('amai_x_callback', 0) !== 1) {
        return;
    }
    if (!is_user_logged_in() || !current_user_can('manage_automarketer_ai')) {
        wp_safe_redirect(home_url('/'));
        exit;
    }
    XAuth::handleCallback();
}
// --------------------------------------------------
// Google OAuth callback rewrite rule
// Redirect URI: https://automarketer-ai.com/google/callback
// --------------------------------------------------
add_action('init', 'amai_google_register_rewrite');
function amai_google_register_rewrite(): void
{
    add_rewrite_rule(
        '^google/callback/?$',
        'index.php?amai_google_callback=1',
        'top'
    );
}
add_filter('query_vars', 'amai_google_query_vars');
function amai_google_query_vars(array $vars): array
{
    $vars[] = 'amai_google_callback';
    return $vars;
}
add_action('template_redirect', 'amai_google_handle_callback');
function amai_google_handle_callback(): void
{
    if ((int) get_query_var('amai_google_callback', 0) !== 1) {
        return;
    }
    if (!is_user_logged_in() || !current_user_can('manage_automarketer_ai')) {
        wp_safe_redirect(home_url('/'));
        exit;
    }
    GoogleAuth::handleCallback();
}
add_action('init','amai_pin_register_rewrite');
function amai_pin_register_rewrite(): void
{
    add_rewrite_rule('^pinterest/callback/?$','index.php?amai_pin_callback=1','top');
}
add_filter('query_vars','amai_pin_query_vars');
function amai_pin_query_vars(array $vars): array
{
    $vars[]='amai_pin_callback';
    return $vars;
}
add_action('template_redirect','amai_pin_handle_callback');
function amai_pin_handle_callback(): void
{
    if ((int)get_query_var('amai_pin_callback',0)!==1){return;}
    if(!is_user_logged_in()||!current_user_can('manage_automarketer_ai')){wp_safe_redirect(home_url('/'));exit;}
    PinterestAuth::handleCallback();
}
add_action('init','amai_yelp_register_rewrite');
function amai_yelp_register_rewrite(): void
{
    add_rewrite_rule('^yelp/callback/?$','index.php?amai_yelp_callback=1','top');
}
add_filter('query_vars','amai_yelp_query_vars');
function amai_yelp_query_vars(array $vars): array
{
    $vars[]='amai_yelp_callback';
    return $vars;
}
add_action('template_redirect','amai_yelp_handle_callback');
function amai_yelp_handle_callback(): void
{
    if ((int)get_query_var('amai_yelp_callback',0)!==1){return;}
    if(!is_user_logged_in()||!current_user_can('manage_automarketer_ai')){wp_safe_redirect(home_url('/'));exit;}
    YelpAuth::handleCallback();
}
add_action('wp_ajax_amai_yelp_search','amai_yelp_ajax_search');
function amai_yelp_ajax_search(): void
{
    check_ajax_referer('amai_yelp_search','_wpnonce');
    if(!current_user_can('manage_automarketer_ai')){wp_send_json_error('unauthorized');}
    $term=sanitize_text_field((string)($_POST['term']??''));
    $location=sanitize_text_field((string)($_POST['location']??''));
    if($term===''||$location===''){wp_send_json_error('missing_params');}
    $result=YelpAuth::searchBusinesses($term,$location);
    if(isset($result['error'])){wp_send_json_error($result['error']);}
    $out=[];
    foreach(($result['businesses']??[]) as $biz){
        $out[]=['id'=>(string)($biz['id']??''),'name'=>(string)($biz['name']??''),'address'=>implode(', ',(array)($biz['location']['display_address']??[])),'image'=>(string)($biz['image_url']??''),'rating'=>$biz['rating']??null,'review_count'=>(int)($biz['review_count']??0)];
    }
    wp_send_json_success($out);
}
add_action('wp_ajax_amai_yelp_select_business','amai_yelp_ajax_select_business');
function amai_yelp_ajax_select_business(): void
{
    check_ajax_referer('amai_yelp_select_business','_wpnonce');
    if(!current_user_can('manage_automarketer_ai')){wp_send_json_error('unauthorized');}
    $business_id=sanitize_text_field((string)($_POST['business_id']??''));
    if($business_id===''){wp_send_json_error('missing_business_id');}
    $token=YelpAuth::getAccessToken();
    if($token===null){wp_send_json_error('no_token');}
    $ok=YelpAuth::saveBusiness($business_id,$token);
    if(!$ok){wp_send_json_error('save_failed');}
    wp_send_json_success();
}
// --------------------------------------------------
// GA4 OAuth callback rewrite rule
// Redirect URI: https://automarketer-ai.com/ga4/callback
// --------------------------------------------------
add_action('init', 'amai_ga4_register_rewrite');
function amai_ga4_register_rewrite(): void
{
    add_rewrite_rule(
        '^ga4/callback/?$',
        'index.php?amai_ga4_callback=1',
        'top'
    );
}
add_filter('query_vars', 'amai_ga4_query_vars');
function amai_ga4_query_vars(array $vars): array
{
    $vars[] = 'amai_ga4_callback';
    return $vars;
}
add_action('template_redirect', 'amai_ga4_handle_callback');
function amai_ga4_handle_callback(): void
{
    if ((int) get_query_var('amai_ga4_callback', 0) !== 1) {
        return;
    }
    if (!is_user_logged_in() || !current_user_can('manage_automarketer_ai')) {
        wp_safe_redirect(home_url('/'));
        exit;
    }
    AutoMarketerAI\Ga4Auth::handleCallback();
}
// --------------------------------------------------
// GA4 cron + AJAX handlers -- registered unconditionally
// --------------------------------------------------
add_action('amai_ga4_sync', ['AutoMarketerAI\\Ga4Sync', 'run']);
add_action('amai_ga4_token_refresh', ['AutoMarketerAI\\Ga4Auth', 'refreshAccessToken']);
add_action('wp_ajax_amai_ga4_disconnect', 'amai_ga4_ajax_disconnect');
function amai_ga4_ajax_disconnect(): void
{
    check_ajax_referer('amai_ga4_disconnect', 'nonce');
    if (!current_user_can('manage_automarketer_ai')) {
        wp_send_json_error(['message' => 'Unauthorized.'], 403);
    }
    AutoMarketerAI\Ga4Auth::disconnect();
    AutoMarketerAI\Ga4Sync::unscheduleCron();
    wp_send_json_success(['disconnected' => true]);
}
add_action('wp_ajax_amai_ga4_sync_now', 'amai_ga4_ajax_sync_now');

// Cluster Builder AJAX
add_action('wp_ajax_amai_generate_cluster', ['\AutoMarketerAI\ClusterBuilder', 'handleGenerateCluster']);
add_action('wp_ajax_amai_cluster_status',   ['\AutoMarketerAI\ClusterBuilder', 'handleClusterStatus']);
function amai_ga4_ajax_sync_now(): void
{
    check_ajax_referer('amai_ga4_sync', 'nonce');
    if (!current_user_can('manage_automarketer_ai')) {
        wp_send_json_error(['message' => 'Unauthorized.'], 403);
    }
    AutoMarketerAI\Ga4Sync::run();
    wp_send_json_success(['synced' => true]);
}
// Migration check — runs on every admin load
// --------------------------------------------------
add_action('admin_init', 'amai_run_pending_migrations');
function amai_run_pending_migrations(): void
{
    $runner = new MigrationRunner();
    if (!$runner->isUpToDate()) {
        $runner->run();
    }
}



// --------------------------------------------------
// Handoff save -- called by Claude at session end
// --------------------------------------------------
add_action('wp_ajax_nopriv_amai_save_handoff', 'amai_save_handoff');
add_action('wp_ajax_amai_save_handoff',         'amai_save_handoff');

// --------------------------------------------------
// Setup profile save handler
// --------------------------------------------------
add_action('wp_ajax_amai_save_setup_profile', 'amai_ajax_save_setup_profile');
function amai_ajax_save_setup_profile(): void
{
    check_ajax_referer('amai_setup_profile', '_ajax_nonce');

    if (!current_user_can('manage_automarketer_ai')) {
        wp_send_json_error(['message' => 'Unauthorized']);
        return;
    }

    $category       = sanitize_text_field(trim((string) ($_POST['business_category'] ?? '')));
    $differentiator = sanitize_textarea_field(trim((string) ($_POST['differentiator'] ?? '')));

    if ($category === '' || $differentiator === '') {
        wp_send_json_error(['message' => 'Please fill in both fields before continuing.']);
        return;
    }

    $bp = new BusinessProfile();

    // Create the row if it does not exist yet
    $existing = $bp->get();
    if (!is_array($existing)) {
        global $wpdb;
        $wpdb->insert(
            $wpdb->prefix . 'amai_business_profile',
            [
                'tenant_id'      => 'default',
                'onboarding_step' => 0,
            ],
            ['%s', '%d']
        );
    }

    $ok = $bp->update([
        'business_category' => $category,
        'differentiator'    => $differentiator,
    ]);

    if (!$ok) {
        wp_send_json_error(['message' => 'Save failed. Please try again.']);
        return;
    }

    wp_send_json_success(['saved' => true]);
}

function amai_save_handoff(): void
{
    if (!defined('AMAI_HANDOFF_SECRET') || AMAI_HANDOFF_SECRET === '') {
        wp_send_json_error(['message' => 'Not configured.'], 500);
        return;
    }
    $token = trim((string) ($_POST['token'] ?? ''));
    if (!hash_equals(AMAI_HANDOFF_SECRET, $token)) {
        wp_send_json_error(['message' => 'Unauthorized.'], 401);
        return;
    }
    $session = (int) ($_POST['session'] ?? 0);
    $content = trim((string) ($_POST['content'] ?? ''));
    if ($session <= 0) {
        wp_send_json_error(['message' => 'Invalid session number.'], 400);
        return;
    }
    if ($content === '') {
        wp_send_json_error(['message' => 'Empty content.'], 400);
        return;
    }
    $key = 'amai_handoff_' . gmdate('Y-m-d') . '-s' . $session;
    update_option($key, $content, false);
    wp_send_json_success(['saved' => $key]);
}

// --------------------------------------------------
// Activation hook
// --------------------------------------------------
// --------------------------------------------------
// Default category setup - runs once on init
// --------------------------------------------------
add_action('init', 'amai_maybe_setup_categories');
function amai_maybe_setup_categories(): void
{
    if (get_option('amai_categories_created')) {
        return;
    }
    amai_setup_default_categories();
}

function amai_setup_default_categories(): void
{
    $categories = [
        'News & Updates'      => 'Company announcements, launches, and updates.',
        'Tips & How-To'       => 'Educational and instructional content for your audience.',
        'Behind the Scenes'   => 'Team, culture, and process stories.',
        'Products & Services' => 'Showcase what your business offers.',
        'Customer Stories'    => 'Testimonials, case studies, and success stories.',
        'Industry Insights'   => 'Trends, commentary, and thought leadership.',
        'Promotions & Offers' => 'Deals, events, and seasonal campaigns.',
        'Community'           => 'Local involvement, partnerships, and causes.',
    ];

    // Rename WP default "Uncategorized" to first category, reuse the term
    foreach ($categories as $name => $description) {
        $slug     = sanitize_title($name);
        $existing = get_term_by('slug', $slug, 'category');
        if ($existing instanceof \WP_Term) {
            // Already exists - update description in case it changed
            wp_update_term($existing->term_id, 'category', ['description' => $description]);
            continue;
        }
        wp_insert_term($name, 'category', [
            'slug'        => $slug,
            'description' => $description,
        ]);
    }

    update_option('amai_categories_created', true);
}

register_activation_hook(__FILE__, 'amai_plugin_activate');
function amai_plugin_activate(): void
{
    $runner = new MigrationRunner();
    $runner->run();

    $profile = new BusinessProfile();
    $profile->getOrCreate();

    if (!get_option('automarketer_ai_license_status')) {
        update_option('automarketer_ai_license_status', 'inactive');
    }
    if (!get_option('amai_active_modules')) {
        update_option('amai_active_modules', []);
    }

    $role = get_role('administrator');
    if ($role instanceof WP_Role) {
        $role->add_cap('manage_automarketer_ai');
    }

    FacebookAuth::scheduleDailyRefresh();
    PostingEngine::scheduleHourlyRun();
    AutoMarketerAI\BlogScheduler::scheduleCrons();
    ContentEngine::maybeSchedule();
    ProductCatalog::maybeSchedule();
    ProductEngine::maybeSchedule();
    ModelWatcher::scheduleDaily();
    MediaCleanup::scheduleDaily();
    BounceHandler::register();

    \AutoMarketerAI\SeoSitemap::flushRewrites();
    amai_setup_default_categories();
    amai_provision_tenant();
    flush_rewrite_rules();
}

// --------------------------------------------------
// Provision tenant in Core on activation
// --------------------------------------------------
// --------------------------------------------------
// AJAX: generate one-click install token
// --------------------------------------------------
add_action('wp_ajax_amai_generate_install_token', function (): void {
    check_ajax_referer('amai_install_onboarding', 'nonce');
    if (!current_user_can('install_plugins')) {
        wp_send_json_error(['message' => 'Permission denied.'], 403);
    }
    $siteUrl    = isset($_POST['site_url']) ? esc_url_raw(wp_unslash((string) $_POST['site_url'])) : '';
    $licenseKey = (string) get_option('automarketer_ai_license_key', '');
    if ($siteUrl === '' || $licenseKey === '') {
        wp_send_json_error(['message' => 'Missing site URL or license key.']);
    }
    if (!defined('AMAI_CORE_URL') || AMAI_CORE_URL === '') {
        wp_send_json_error(['message' => 'Server configuration error.']);
    }
    $method    = 'POST';
    $path      = '/api/install/generate-token';
    $url       = rtrim(AMAI_CORE_URL, '/') . $path;
    $body      = (string) json_encode(['license_key' => $licenseKey]);
    $timestamp = (string) time();
    $nonce     = bin2hex(random_bytes(16));
    $tenant    = amai_tenant_id();
    $key_id    = 'WP_PROXY';
    $tenantSecret = (string) get_option('amai_tenant_hmac_secret', '');
    if ($tenantSecret === '') {
        wp_send_json_error(['message' => 'Install not configured. Please contact support.']);
    }
    $secret    = hex2bin($tenantSecret);
    $body_b64  = base64_encode(hash('sha256', $body, true));
    $canonical = implode('|', [$method, $path, $timestamp, $nonce, $tenant, $key_id, $body_b64]);
    $signature = rtrim(base64_encode(hash_hmac('sha256', $canonical, $secret, true)), "\n");
    $response  = wp_remote_request($url, [
        'method'  => $method,
        'timeout' => 15,
        'headers' => [
            'Content-Type'       => 'application/json',
            'X-Amai-Tenant'      => $tenant,
            'X-Amai-Key-Id'      => $key_id,
            'X-Amai-Timestamp'   => $timestamp,
            'X-Amai-Nonce'       => $nonce,
            'X-Amai-Body-SHA256' => $body_b64,
            'X-Amai-Signature'   => $signature,
        ],
        'body' => $body,
    ]);
    if (is_wp_error($response)) {
        wp_send_json_error(['message' => 'Could not reach AutoMarketer AI servers. Please try again.']);
    }
    $code = (int) wp_remote_retrieve_response_code($response);
    $data = json_decode(wp_remote_retrieve_body($response), true);
    if ($code !== 200 || empty($data['connect_url'])) {
        wp_send_json_error(['message' => 'Could not generate install link. Please try again.']);
    }
    wp_send_json_success(['connect_url' => $data['connect_url']]);
});

// Returns the tenant ID for this install.
// Client installs define AMAI_TENANT_ID in wp-config.php.
// Main install omits it and defaults to FOO.
function amai_tenant_id(): string
{
    return defined('AMAI_TENANT_ID') && (string) AMAI_TENANT_ID !== '' ? (string) AMAI_TENANT_ID : 'FOO';
}

function amai_provision_tenant(): void
{
    if (!defined('AMAI_CORE_URL') || AMAI_CORE_URL === '') {
        return;
    }
    if (!defined('AMAI_BOOTSTRAP_KEY') || AMAI_BOOTSTRAP_KEY === '') {
        return;
    }
    $secret = bin2hex(random_bytes(32));
    $url    = rtrim(AMAI_CORE_URL, '/') . '/api/tenant/provision';
    $body   = (string) json_encode(['tenant_id' => amai_tenant_id(), 'hmac_secret' => $secret]);
    $response = wp_remote_post($url, [
        'timeout' => 15,
        'headers' => [
            'Content-Type'        => 'application/json',
            'X-Amai-Bootstrap-Key' => AMAI_BOOTSTRAP_KEY,
        ],
        'body' => $body,
    ]);
    if (is_wp_error($response)) {
        return;
    }
    $code = (int) wp_remote_retrieve_response_code($response);
    if ($code === 200) {
        update_option('amai_tenant_hmac_secret', $secret);
    }
}
// --------------------------------------------------
// Deactivation hook
// --------------------------------------------------
register_deactivation_hook(__FILE__, 'amai_plugin_deactivate');
function amai_plugin_deactivate(): void
{
    FacebookAuth::clearScheduledRefresh();
    PostingEngine::clearScheduledRun();
    AutoMarketerAI\BlogScheduler::clearCrons();
    ContentEngine::clearSchedule();
    ProductCatalog::clearSchedule();
    ProductEngine::clearSchedule();
    ModelWatcher::clearSchedule();
    MediaCleanup::clearSchedule();
    UpdateChecker::deregister();
    BounceHandler::deregister();
    AutoMarketerAI\CommentFetcher::deregister();
    AutoMarketerAI\CommentDigest::deregister();
}

// --------------------------------------------------
// Free license activation handler
// --------------------------------------------------
add_action('admin_post_amai_activate_free_license', 'amai_handle_free_license_activation');
function amai_handle_free_license_activation(): void
{
    if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(
        sanitize_text_field(wp_unslash($_POST['_wpnonce'])),
        'amai_activate_free_license'
    )) {
        wp_die('Nonce verification failed. Please try again.');
    }

    $first_name = sanitize_text_field(trim((string) ($_POST['first_name'] ?? '')));
    $email      = sanitize_email(trim((string) ($_POST['email'] ?? '')));
    $consent    = isset($_POST['consent']);
    $referer    = wp_get_referer() ?: admin_url('admin.php?page=automarketer-ai');

    if (empty($first_name) || empty($email) || !$consent) {
        wp_safe_redirect(add_query_arg('error', 'missing_fields', $referer));
        exit;
    }

    if (!is_email($email)) {
        wp_safe_redirect(add_query_arg('error', 'invalid_email', $referer));
        exit;
    }

    $free_key = 'free-' . wp_generate_uuid4();
    update_option('automarketer_ai_license_key', $free_key);
    update_option('automarketer_ai_license_status', 'free');
    MarketingSite::sendWelcomeEmail($email, $first_name, $free_key);

    wp_safe_redirect(add_query_arg('activated', 'free', admin_url('admin.php?page=automarketer-ai')));
    exit;
}

// --------------------------------------------------
// Deactivate license handler
// --------------------------------------------------
add_action('admin_post_amai_deactivate_license', 'amai_handle_deactivate_license');
function amai_handle_deactivate_license(): void
{
    if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(
        sanitize_text_field(wp_unslash($_POST['_wpnonce'])),
        'amai_deactivate_license'
    )) {
        wp_die('Nonce verification failed. Please try again.');
    }

    delete_option('automarketer_ai_license_key');
    update_option('automarketer_ai_license_status', 'inactive');

    $active_modules = (array) get_option('amai_active_modules', []);
    $active_modules = array_filter(
        $active_modules,
        static fn(mixed $id): bool => is_string($id) && !str_starts_with($id, 'ai-')
    );
    update_option('amai_active_modules', array_values($active_modules));

    set_transient('amai_deactivated_notice_shown', true, 30);
    wp_safe_redirect(admin_url('admin.php?page=automarketer-ai'));
    exit;
}

// --------------------------------------------------
// AI provider model update handler
// --------------------------------------------------
// --------------------------------------------------
// Email sender save handler
// --------------------------------------------------
add_action('admin_post_amai_save_email_sender', 'amai_handle_save_email_sender');
function amai_handle_save_email_sender(): void
{
    if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(
        sanitize_text_field(wp_unslash($_POST['_wpnonce'])),
        'amai_save_email_sender'
    )) {
        wp_die('Nonce verification failed. Please try again.');
    }
    if (!current_user_can('manage_automarketer_ai')) {
        wp_die('Unauthorized');
    }
    $sender_name  = sanitize_text_field(trim((string) ($_POST['sender_name'] ?? '')));
    $sender_email = sanitize_email(trim((string) ($_POST['sender_email'] ?? '')));
    $referer      = wp_get_referer() ?: admin_url('admin.php?page=automarketer-ai-settings');
    if (empty($sender_name) || empty($sender_email) || !is_email($sender_email)) {
        wp_safe_redirect(add_query_arg('sender_error', '1', $referer));
        exit;
    }
    update_option('amai_email_sender_name', $sender_name);
    update_option('amai_email_sender_email', $sender_email);
    update_option('amai_email_tagline', sanitize_text_field(trim((string) ($_POST['email_tagline'] ?? ''))));
    wp_safe_redirect(add_query_arg('sender_saved', '1', admin_url('admin.php?page=automarketer-ai-settings')));
    exit;
}
// --------------------------------------------------
add_action('admin_post_amai_update_model', 'amai_handle_update_model');
add_action('admin_post_amai_abandoned_cart_toggle', 'amai_handle_abandoned_cart_toggle');
add_action('admin_post_amai_abandoned_cart_sms_toggle', 'amai_handle_abandoned_cart_sms_toggle');
function amai_handle_abandoned_cart_toggle(): void {
    if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'amai_abandoned_cart_toggle')) {
        wp_die('Nonce failed.');
    }
    if (!current_user_can('manage_automarketer_ai')) { wp_die('Unauthorized'); }
    $active         = get_option('amai_abandoned_cart_active', '0') === '1';
    $current_plan   = (string) get_option('automarketer_ai_plan_id', 'free');
    $active_modules = (array) get_option('amai_active_modules', []);
    if ($active) {
        AbandonedCart::deactivate();
        $active_modules = array_values(array_filter($active_modules, function(mixed $id): bool {
            return $id !== 'abandoned-cart';
        }));
        update_option('amai_active_modules', $active_modules);
        if (in_array($current_plan, ['starter', 'starter_pro'], true)) {
            $over = PlanEnforcer::countSlotModules($active_modules) - 5;
            if ($over > 0) {
                update_option('amai_module_over_limit', $over);
            } else {
                delete_option('amai_module_over_limit');
            }
        }
    } else {
        if (in_array($current_plan, ['starter', 'starter_pro'], true) && PlanEnforcer::starterSlotsFull($active_modules)) {
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-modules&amai_error=slots_full'));
            exit;
        }
        AbandonedCart::activate();
        if (!in_array('abandoned-cart', $active_modules, true)) {
            $active_modules[] = 'abandoned-cart';
            update_option('amai_active_modules', array_values($active_modules));
        }
        delete_option('amai_module_over_limit');
    }
    wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-modules'));
    exit;
}

function amai_handle_abandoned_cart_sms_toggle(): void {
    if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'amai_abandoned_cart_sms_toggle')) {
        wp_die('Nonce failed.');
    }
    if (!current_user_can('manage_automarketer_ai')) { wp_die('Unauthorized'); }
    $active         = in_array('abandoned-cart-sms', (array) get_option('amai_active_modules', []), true);
    $current_plan   = (string) get_option('automarketer_ai_plan_id', 'free');
    $active_modules = (array) get_option('amai_active_modules', []);
    if ($active) {
        $active_modules = array_values(array_filter($active_modules, function(mixed $id): bool {
            return $id !== 'abandoned-cart-sms';
        }));
        update_option('amai_active_modules', $active_modules);
    } else {
        if (in_array($current_plan, ['starter', 'starter_pro'], true) && AutoMarketerAI\PlanEnforcer::starterSlotsFull($active_modules)) {
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-modules&amai_error=slots_full'));
            exit;
        }
        if (!in_array('abandoned-cart-sms', $active_modules, true)) {
            $active_modules[] = 'abandoned-cart-sms';
            update_option('amai_active_modules', array_values($active_modules));
        }
        delete_option('amai_module_over_limit');
    }
    wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-modules'));
    exit;
}
add_action('admin_post_amai_re_engagement_toggle', 'amai_handle_re_engagement_toggle');
function amai_handle_re_engagement_toggle(): void {
    if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'amai_re_engagement_toggle')) {
        wp_die('Nonce failed.');
    }
    if (!current_user_can('manage_automarketer_ai')) { wp_die('Unauthorized'); }
    $active         = in_array('re-engagement', (array) get_option('amai_active_modules', []), true);
    $current_plan   = (string) get_option('automarketer_ai_plan_id', 'free');
    $active_modules = (array) get_option('amai_active_modules', []);
    $eligible_plans = ['starter', 'starter_pro', 'unlimited_ai', 'agency'];
    if ($active) {
        $active_modules = array_values(array_filter($active_modules, function(mixed $id): bool {
            return $id !== 're-engagement';
        }));
        update_option('amai_active_modules', $active_modules);
        AutoMarketerAI\ProductViewTracker::clearSchedule();
    } else {
        if (!in_array($current_plan, $eligible_plans, true)) {
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-modules&amai_error=upgrade_required'));
            exit;
        }
        if (in_array($current_plan, ['starter', 'starter_pro'], true) && AutoMarketerAI\PlanEnforcer::starterSlotsFull($active_modules)) {
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-modules&amai_error=slots_full'));
            exit;
        }
        if (!in_array('re-engagement', $active_modules, true)) {
            $active_modules[] = 're-engagement';
            update_option('amai_active_modules', array_values($active_modules));
        }
        delete_option('amai_module_over_limit');
        AutoMarketerAI\ProductViewTracker::maybeSchedule();
    }
    wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-modules'));
    exit;
}

add_action('admin_post_amai_review_responder_toggle', 'amai_handle_review_responder_toggle');
function amai_handle_review_responder_toggle(): void {
    if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'amai_review_responder_toggle')) {
        wp_die('Nonce failed.');
    }
    if (!current_user_can('manage_automarketer_ai')) { wp_die('Unauthorized'); }
    $active         = in_array('review-responder', (array) get_option('amai_active_modules', []), true);
    $current_plan   = (string) get_option('automarketer_ai_plan_id', 'free');
    $active_modules = (array) get_option('amai_active_modules', []);
    $eligible_plans = ['unlimited_ai', 'agency'];
    if ($active) {
        $active_modules = array_values(array_filter($active_modules, function(mixed $id): bool {
            return $id !== 'review-responder';
        }));
        update_option('amai_active_modules', $active_modules);
        AutoMarketerAI\ReviewFetcher::unschedule();
    } else {
        if (!in_array($current_plan, $eligible_plans, true)) {
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-modules&amai_error=upgrade_required'));
            exit;
        }
        if (!in_array('review-responder', $active_modules, true)) {
            $active_modules[] = 'review-responder';
            update_option('amai_active_modules', array_values($active_modules));
        }
        delete_option('amai_module_over_limit');
        AutoMarketerAI\ReviewFetcher::maybeSchedule();
    }
    wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-modules'));
    exit;
}
function amai_handle_update_model(): void
{
    if (!current_user_can('manage_automarketer_ai')) {
        wp_die('Unauthorized');
    }

    check_admin_referer('amai_update_model', '_wpnonce');

    $provider_id = sanitize_key((string) ($_POST['provider_id'] ?? ''));
    $model       = sanitize_text_field((string) ($_POST['model'] ?? ''));

    if (empty($provider_id) || empty($model)) {
        wp_die('Missing provider or model.');
    }

    update_option('amai_model_' . $provider_id, $model);
    wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-modules'));
    exit;
}

// --------------------------------------------------
// Auto-fade success notices
// --------------------------------------------------
add_action('admin_footer', 'amai_auto_fade_notices_js');
function amai_auto_fade_notices_js(): void
{
    $screen = get_current_screen();
    if (!$screen instanceof WP_Screen || strpos($screen->id, 'automarketer-ai') === false) {
        return;
    }
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('.notice-success.amai-temp-notice').forEach(function (notice) {
            setTimeout(function () {
                notice.style.transition = 'opacity 1s ease';
                notice.style.opacity = '0';
                setTimeout(function () { notice.remove(); }, 1000);
            }, 6000);
        });
    });
    </script>
    <?php
}

// --------------------------------------------------
// Plans submenu
// --------------------------------------------------
add_action('wp_enqueue_scripts', 'amai_enqueue_related_link_styles');
function amai_enqueue_related_link_styles(): void
{
    wp_enqueue_style(
        'amai-related-links',
        plugin_dir_url(__FILE__) . 'assets/css/related-links.css',
        [],
        (string) filemtime(plugin_dir_path(__FILE__) . 'assets/css/related-links.css')
    );
}
add_action('wp_enqueue_scripts', 'amai_enqueue_credit_styles');
function amai_enqueue_credit_styles(): void
{
    if (!is_single()) {
        return;
    }
    wp_enqueue_style(
        'amai-unsplash-credit',
        plugin_dir_url(__FILE__) . 'assets/css/unsplash-credit.css',
        [],
        (string) filemtime(plugin_dir_path(__FILE__) . 'assets/css/unsplash-credit.css')
    );
}

// --------------------------------------------------
// Unsplash photo credit -- appended after post content on single posts
// --------------------------------------------------
add_filter('the_content', 'amai_append_unsplash_credit');
function amai_append_unsplash_credit(string $content): string
{
    if (!is_single() || !in_the_loop() || !is_main_query()) {
        return $content;
    }
    $post_id  = get_the_ID();
    if ($post_id === false || $post_id === 0) {
        return $content;
    }
    $thumb_id = (int) get_post_thumbnail_id($post_id);
    if ($thumb_id === 0) {
        return $content;
    }
    $title = get_the_title($thumb_id);
    if (!str_starts_with($title, 'Photo by ') || !str_ends_with($title, ' on Unsplash')) {
        return $content;
    }
    $profile_url = (string) get_post_meta($thumb_id, '_amai_unsplash_profile_url', true);
    $credit_name = substr($title, strlen('Photo by '), -strlen(' on Unsplash'));
    if ($profile_url !== '') {
        $credit_html = '<p class="amai-unsplash-credit">Photo by <a href="' . esc_url($profile_url) . '?utm_source=automarketer_ai&utm_medium=referral" target="_blank" rel="noopener noreferrer">' . esc_html($credit_name) . '</a> on <a href="https://unsplash.com/?utm_source=automarketer_ai&utm_medium=referral" target="_blank" rel="noopener noreferrer">Unsplash</a></p>';
    } else {
        $credit_html = '<p class="amai-unsplash-credit">Photo by ' . esc_html($credit_name) . ' on Unsplash</p>';
    }
    return $content . $credit_html;
}

add_action('admin_menu', 'amai_add_billing_submenu');
function amai_add_billing_submenu(): void
{
    add_submenu_page(
        null,
        'Plans',
        'Plans',
        'read',
        'automarketer-ai-billing',
        static function (): void {
            $plans        = \amai_get_plans();
            $current_plan = get_option('automarketer_ai_plan_id', 'free');
            include AMAI_PLUGIN_DIR . 'templates/billing.php';
        }
    );

}
// --------------------------------------------------
