<?php
/**
 * Remote theme usage tracking helpers.
 * 
 * IMPORTANT: This theme tracks usage and reports to our centralized server.
 * The plugin (Notify Manager) is ONLY installed on our main site (luzukdemo.com).
 * Customers do NOT need to install any plugin - theme automatically reports 
 * to our centralized tracking server.
 *
 * @package Akhada Fitness Gym
 */

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

/**
 * Tracker endpoint for reporting theme activations.
 * 
 * CONCEPT:
 * - Default: Remote endpoint (luzukdemo.com) - for customers' sites
 * - If plugin active: Local endpoint - only for our main site (luzukdemo.com)
 * 
 * Customers' sites will always use remote endpoint since they don't have plugin.
 * Only our main site (luzukdemo.com) has the plugin, so it uses local endpoint.
 *
 * @return string Tracker API endpoint URL
 */
function cpa_accountant_free_get_tracker_endpoint() {
    // Default remote endpoint for customers' sites
    // This is where our plugin is installed (luzukdemo.com)
    $default = defined( 'cpa_accountant_free_TRACKER_ENDPOINT' )
        ? cpa_accountant_free_TRACKER_ENDPOINT
        : 'https://www.luzukdemo.com/demo/testing/wp-json/notify-manager/v1/themes/register';

    /**
     * Filter the tracker endpoint.
     *
     * @param string $endpoint The tracker endpoint URL.
     */
    return apply_filters( 'cpa_accountant_free_tracker_endpoint', $default );
}

/**
 * Auto-detect endpoint based on plugin availability.
 * 
 * - If plugin is active (our main site): Use local endpoint
 * - If plugin is NOT active (customers' sites): Use remote endpoint (default)
 */
add_filter(
    'cpa_accountant_free_tracker_endpoint',
    function ( $endpoint ) {
        // Only our main site (luzukdemo.com) has the plugin installed
        // So if plugin exists, use local endpoint
        if ( class_exists( 'Notify_Manager' ) ) {
            return home_url( '/wp-json/notify-manager/v1/themes/register' );
        }

        // Customers' sites don't have plugin, so use remote endpoint
        return $endpoint;
    }
);

/**
 * Get our theme slug constant.
 *
 * @return string
 */
function cpa_accountant_free_get_theme_slug() {
    // Return the actual theme folder name (stylesheet)
    // This will be used for tracking purposes
    $theme = wp_get_theme();
    if ( $theme && $theme->exists() ) {
        return $theme->get_stylesheet();
    }
    // Fallback to common folder names
    return 'free-cpa-accountant-free';
}

/**
 * Check if our theme is currently active.
 * Checks by Text Domain and Theme Name to be more reliable.
 *
 * @return bool
 */
function cpa_accountant_free_is_theme_active() {
    $theme = wp_get_theme();
    if ( ! $theme || ! $theme->exists() ) {
        return false;
    }
    
    // Check by Text Domain (most reliable)
    $text_domain = $theme->get( 'TextDomain' );
    if ( $text_domain === 'cpa-accountant-free' ) {
        return true;
    }
    
    // Also check by Theme Name as fallback
    $theme_name = $theme->get( 'Name' );
    if ( stripos( $theme_name, 'Akhada Fitness' ) !== false ) {
        return true;
    }
    
    // Fallback: check by stylesheet (folder name)
    // This covers cases where folder might be renamed
    $current_theme_slug = $theme->get_stylesheet();
    $possible_slugs = array( 'free-cpa-accountant-free', 'cpa-accountant-free', 'cpa-accountant-free' );
    
    return in_array( $current_theme_slug, $possible_slugs, true );
}

/**
 * Maybe send a usage ping to the tracker endpoint.
 * This function only sends ping if our theme is active.
 */
function cpa_accountant_free_maybe_send_tracker_ping() {
    // First check if our theme is active - if not, don't send anything
    if ( ! cpa_accountant_free_is_theme_active() ) {
        // Theme is not active, ensure we're not tracking
        cpa_accountant_free_clear_tracking_schedule();
        return;
    }

    $endpoint = cpa_accountant_free_get_tracker_endpoint();

    if ( empty( $endpoint ) || ! filter_var( $endpoint, FILTER_VALIDATE_URL ) ) {
        return;
    }

    $theme = wp_get_theme();
    $current_theme_slug = $theme->get_stylesheet();
    $last_sent = get_option( 'cpa_accountant_free_tracker_last_sent', array() );
    $now       = time();
    $interval  = (int) apply_filters( 'cpa_accountant_free_tracker_interval', 12 * HOUR_IN_SECONDS );

    // Allow force ping via filter or query param (for testing)
    $force_ping = apply_filters( 'cpa_accountant_free_force_tracker_ping', false );
    if ( ! $force_ping && isset( $last_sent['timestamp'], $last_sent['endpoint'] )
        && ( $now - (int) $last_sent['timestamp'] ) < $interval
        && $last_sent['endpoint'] === md5( $endpoint )
        && isset( $last_sent['theme_slug'] )
        && $last_sent['theme_slug'] === $current_theme_slug
    ) {
        return;
    }

    $site_url  = home_url();
    $site_hash = hash( 'sha256', strtolower( rtrim( $site_url, '/' ) ) );

    // Validate required fields before sending
    $theme_name = $theme->get( 'Name' );
    $theme_version = $theme->get( 'Version' );
    
    if ( empty( $current_theme_slug ) || empty( $theme_name ) || empty( $site_url ) || empty( $site_hash ) ) {
        // Log missing required fields
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
            error_log( 'Akhada Fitness Gym Tracker: Missing required fields - Slug: ' . $current_theme_slug . ', Name: ' . $theme_name . ', URL: ' . $site_url . ', Hash: ' . $site_hash );
        }
        return;
    }

    $payload = array(
        'theme_slug'    => $current_theme_slug,
        'theme_name'    => $theme_name,
        'theme_version' => $theme_version,
        'site_url'      => $site_url,
        'site_hash'     => $site_hash,
        'is_active'     => true, // Always true when our theme is active
    );

    // Log payload for debugging (only if WP_DEBUG is enabled)
    if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
        error_log( 'Akhada Fitness Gym Tracker: Sending payload to ' . $endpoint . ' - ' . wp_json_encode( $payload ) );
    }

    $response = wp_remote_post(
        $endpoint,
        array(
            'timeout' => 15,
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body'    => wp_json_encode( $payload ),
            'sslverify' => true,
        )
    );

    if ( is_wp_error( $response ) ) {
        // Always store error for debugging in admin dashboard
        update_option( 'cpa_accountant_free_tracker_last_response', array(
            'error' => true,
            'message' => $response->get_error_message(),
            'code' => $response->get_error_code(),
            'time' => current_time( 'mysql' ),
            'endpoint' => $endpoint,
        ), false );
        
        // Log error for debugging (only if WP_DEBUG is enabled)
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
            error_log( 'Akhada Fitness Gym Tracker Error: ' . $response->get_error_message() . ' | Endpoint: ' . $endpoint );
        }
        return;
    }

    $code = wp_remote_retrieve_response_code( $response );
    $body = wp_remote_retrieve_body( $response );

    // Log response for debugging (only if WP_DEBUG is enabled)
    if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
        error_log( 'Akhada Fitness Gym Tracker: Response Code ' . $code . ' - Body: ' . substr( $body, 0, 500 ) );
    }

    // Always store response for debugging (not just on success)
    update_option( 'cpa_accountant_free_tracker_last_response', array(
        'code' => $code,
        'body' => substr( $body, 0, 500 ), // Store first 500 chars
        'time' => current_time( 'mysql' ),
        'endpoint' => $endpoint,
        'success' => ( $code >= 200 && $code < 300 ),
        'payload' => $payload, // Store payload for debugging
    ), false );

    if ( $code >= 200 && $code < 300 ) {
        update_option(
            'cpa_accountant_free_tracker_last_sent',
            array(
                'timestamp'  => $now,
                'endpoint'   => md5( $endpoint ),
                'theme_slug' => $current_theme_slug,
            ),
            false
        );
    } else {
        // Log non-200 responses for debugging
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
            error_log( sprintf(
                'Akhada Fitness Gym Tracker: HTTP %d - %s | Endpoint: %s',
                $code,
                substr( $body, 0, 200 ),
                $endpoint
            ) );
        }
    }
}

/**
 * Scheduled cron event handler for tracker ping.
 * This runs periodically and only sends ping if theme is active.
 */
function cpa_accountant_free_scheduled_tracker_ping() {
    // Double check if theme is still active before sending
    if ( ! cpa_accountant_free_is_theme_active() ) {
        // Theme is no longer active, send deactivation and clear schedule
        cpa_accountant_free_send_deactivation_ping();
        cpa_accountant_free_clear_tracking_schedule();
        return;
    }
    
    // Theme is active, send ping
    cpa_accountant_free_maybe_send_tracker_ping();
}

/**
 * Schedule recurring tracker ping via WordPress cron.
 */
function cpa_accountant_free_schedule_tracking() {
    $hook = 'cpa_accountant_free_tracker_ping';
    $interval = apply_filters( 'cpa_accountant_free_tracker_interval', 12 * HOUR_IN_SECONDS );
    
    // Clear any existing schedule first
    cpa_accountant_free_clear_tracking_schedule();
    
    // Schedule recurring event
    if ( ! wp_next_scheduled( $hook ) ) {
        wp_schedule_event( time(), 'twicedaily', $hook );
    }
}

/**
 * Clear tracking schedule and cancel cron events.
 */
function cpa_accountant_free_clear_tracking_schedule() {
    $hook = 'cpa_accountant_free_tracker_ping';
    $timestamp = wp_next_scheduled( $hook );
    
    if ( $timestamp ) {
        wp_unschedule_event( $timestamp, $hook );
    }
    
    // Also clear all scheduled events for this hook (safety)
    wp_clear_scheduled_hook( $hook );
}

/**
 * Hook into theme activation to schedule tracking.
 * This runs AFTER the theme is switched.
 * Note: after_switch_theme hook only passes 2 arguments: $new_name and $new_theme
 *
 * @param string   $new_name New theme name.
 * @param WP_Theme $new_theme New theme object.
 */
function cpa_accountant_free_on_theme_activation( $new_name, $new_theme ) {
    // Check if the new theme is our theme
    if ( ! $new_theme ) {
        return;
    }
    
    // Check by Text Domain (most reliable method)
    $text_domain = $new_theme->get( 'TextDomain' );
    $theme_name = $new_theme->get( 'Name' );
    $theme_slug = $new_theme->get_stylesheet();
    
    // Check if this is our theme by Text Domain, Name, or slug
    $is_our_theme = false;
    if ( $text_domain === 'cpa-accountant-free' ) {
        $is_our_theme = true;
    } elseif ( stripos( $theme_name, 'Akhada Fitness' ) !== false ) {
        $is_our_theme = true;
    } elseif ( in_array( $theme_slug, array( 'free-cpa-accountant-free', 'cpa-accountant-free', 'cpa-accountant-free' ), true ) ) {
        $is_our_theme = true;
    }
    
    // Only schedule tracking if the new theme is our theme
    if ( $is_our_theme ) {
        // Schedule tracking when our theme is activated
        cpa_accountant_free_schedule_tracking();
        
        // Clear last sent option to force immediate ping
        delete_option( 'cpa_accountant_free_tracker_last_sent' );
        
        // Send initial ping immediately
        cpa_accountant_free_maybe_send_tracker_ping();
        
        // Clear deactivation flag if it exists
        delete_option( 'cpa_accountant_free_theme_deactivated' );
    }
}
add_action( 'after_switch_theme', 'cpa_accountant_free_on_theme_activation', 10, 2 );

/**
 * Hook into WordPress init to check theme status and schedule if needed.
 */
function cpa_accountant_free_init_tracker() {
    $is_theme_active = cpa_accountant_free_is_theme_active();
    $last_sent = get_option( 'cpa_accountant_free_tracker_last_sent', array() );
    $was_tracking = ! empty( $last_sent );
    
    // If theme is not active but we were tracking it, send deactivation ping
    if ( ! $is_theme_active && $was_tracking ) {
        // Check if we already sent deactivation recently (avoid duplicate pings)
        $last_deactivation = get_option( 'cpa_accountant_free_last_deactivation_sent', 0 );
        $now = time();
        
        // Only send deactivation if we haven't sent it in the last 5 minutes
        if ( ( $now - $last_deactivation ) > 300 ) {
            // Get theme slug from last sent data
            $theme_slug = isset( $last_sent['theme_slug'] ) ? $last_sent['theme_slug'] : cpa_accountant_free_get_theme_slug();
            
            // Send deactivation ping
            cpa_accountant_free_send_deactivation_ping( $theme_slug );
            
            // Store timestamp to avoid duplicate pings
            update_option( 'cpa_accountant_free_last_deactivation_sent', $now, false );
            
            // Clear tracking data
            delete_option( 'cpa_accountant_free_tracker_last_sent' );
        }
        
        // Clear tracking schedule
        cpa_accountant_free_clear_tracking_schedule();
        return;
    }
    
    // Only run if our theme is active
    if ( ! $is_theme_active ) {
        // Theme is not active, clear any existing schedule
        cpa_accountant_free_clear_tracking_schedule();
        return;
    }
    
    // Theme is active, ensure schedule is set up
    $hook = 'cpa_accountant_free_tracker_ping';
    if ( ! wp_next_scheduled( $hook ) ) {
        cpa_accountant_free_schedule_tracking();
    }
    
    // Clear deactivation timestamp since theme is active
    delete_option( 'cpa_accountant_free_last_deactivation_sent' );
    
    // Also check on init (with interval check) for immediate tracking
    cpa_accountant_free_maybe_send_tracker_ping();
}
add_action( 'init', 'cpa_accountant_free_init_tracker' );

/**
 * Register cron event handler.
 */
add_action( 'cpa_accountant_free_tracker_ping', 'cpa_accountant_free_scheduled_tracker_ping' );

/**
 * Note: WordPress has built-in 'twicedaily' cron schedule (runs twice daily).
 * We use that schedule, so no custom schedule registration is needed.
 */

/**
 * Send deactivation ping when theme is switched away.
 *
 * @param string $theme_slug Optional theme slug to deactivate.
 */
function cpa_accountant_free_send_deactivation_ping( $theme_slug = null ) {
    $endpoint = cpa_accountant_free_get_tracker_endpoint();

    if ( empty( $endpoint ) || ! filter_var( $endpoint, FILTER_VALIDATE_URL ) ) {
        return;
    }

    // Get deactivation endpoint
    $deactivation_endpoint = str_replace( '/themes/register', '/themes/deactivate', $endpoint );

    $last_sent = get_option( 'cpa_accountant_free_tracker_last_sent', array() );
    
    if ( empty( $theme_slug ) ) {
        $theme_slug = isset( $last_sent['theme_slug'] ) ? $last_sent['theme_slug'] : cpa_accountant_free_get_theme_slug();
    }

    $site_url  = home_url();
    $site_hash = hash( 'sha256', strtolower( rtrim( $site_url, '/' ) ) );

    $payload = array(
        'theme_slug' => $theme_slug,
        'site_url'   => $site_url,
        'site_hash'  => $site_hash,
        'is_active'  => false,
    );

    $response = wp_remote_post(
        $deactivation_endpoint,
        array(
            'timeout' => 15, // Increased timeout for reliability
            'blocking' => true, // Blocking request to ensure it completes
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body'    => wp_json_encode( $payload ),
            'sslverify' => true,
        )
    );

    // Store response for debugging
    if ( is_wp_error( $response ) ) {
        // Log error but don't fail - we'll retry on next init
        error_log( 'Akhada Fitness Gym Deactivation Error: ' . $response->get_error_message() );
        
        // Store error for debugging
        update_option( 'cpa_accountant_free_deactivation_error', array(
            'error' => true,
            'message' => $response->get_error_message(),
            'time' => current_time( 'mysql' ),
        ), false );
    } else {
        $code = wp_remote_retrieve_response_code( $response );
        $body = wp_remote_retrieve_body( $response );
        
        if ( $code >= 200 && $code < 300 ) {
            // Success - clear tracking data
            delete_option( 'cpa_accountant_free_tracker_last_sent' );
            delete_option( 'cpa_accountant_free_tracker_last_response' );
            delete_option( 'cpa_accountant_free_deactivation_error' );
            
            // Store success response
            update_option( 'cpa_accountant_free_deactivation_success', array(
                'code' => $code,
                'time' => current_time( 'mysql' ),
            ), false );
        } else {
            // HTTP error - log for debugging
            error_log( sprintf(
                'Akhada Fitness Gym Deactivation: HTTP %d - %s',
                $code,
                substr( $body, 0, 200 )
            ) );
            
            // Store error response
            update_option( 'cpa_accountant_free_deactivation_error', array(
                'error' => true,
                'code' => $code,
                'message' => substr( $body, 0, 200 ),
                'time' => current_time( 'mysql' ),
            ), false );
        }
    }
    
    // Always clear the schedule when sending deactivation
    cpa_accountant_free_clear_tracking_schedule();
}

/**
 * Hook into theme switch to send deactivation ping.
 * This runs BEFORE the theme is switched, so our theme files are still loaded.
 *
 * @param string $new_name New theme name.
 * @param WP_Theme $new_theme New theme object.
 * @param WP_Theme $old_theme Old theme object.
 */
function cpa_accountant_free_on_theme_switch( $new_name, $new_theme, $old_theme ) {
    if ( ! $old_theme ) {
        return;
    }

    // Check if old theme was our theme by Text Domain, Name, or slug
    $old_text_domain = $old_theme->get( 'TextDomain' );
    $old_theme_name = $old_theme->get( 'Name' );
    $old_theme_slug = $old_theme->get_stylesheet();
    
    $was_our_theme = false;
    if ( $old_text_domain === 'cpa-accountant-free' ) {
        $was_our_theme = true;
    } elseif ( stripos( $old_theme_name, 'Akhada Fitness' ) !== false ) {
        $was_our_theme = true;
    } elseif ( in_array( $old_theme_slug, array( 'free-cpa-accountant-free', 'cpa-accountant-free', 'cpa-accountant-free' ), true ) ) {
        $was_our_theme = true;
    }

    // If old theme was our theme, send deactivation ping and clear schedule
    if ( $was_our_theme ) {
        // Send deactivation ping immediately
        cpa_accountant_free_send_deactivation_ping( $old_theme_slug );
        
        // Clear tracking schedule immediately
        cpa_accountant_free_clear_tracking_schedule();
        
        // Store timestamp for deactivation to prevent duplicate pings
        update_option( 'cpa_accountant_free_last_deactivation_sent', time(), false );
        
        // Clear tracking data
        delete_option( 'cpa_accountant_free_tracker_last_sent' );
        delete_option( 'cpa_accountant_free_tracker_last_response' );
        
        // Store a flag that theme was deactivated (for cleanup)
        update_option( 'cpa_accountant_free_theme_deactivated', time(), false );
    }
}
add_action( 'switch_theme', 'cpa_accountant_free_on_theme_switch', 10, 3 );

/**
 * Hook into theme deletion to send deactivation ping.
 * This runs BEFORE the theme files are deleted, so we can still send the ping.
 * This works even if the theme is not currently active.
 *
 * @param string $theme_slug The slug of the theme being deleted.
 */
function cpa_accountant_free_on_theme_deletion( $theme_slug ) {
    // Check if the theme being deleted is our theme by slug
    $possible_slugs = array( 'free-cpa-accountant-free', 'cpa-accountant-free', 'cpa-accountant-free' );
    
    // If the theme being deleted is our theme, send deactivation ping
    if ( in_array( $theme_slug, $possible_slugs, true ) ) {
        // Get tracking data BEFORE cleanup
        $last_sent = get_option( 'cpa_accountant_free_tracker_last_sent', array() );
        $site_url = home_url();
        $site_hash = hash( 'sha256', strtolower( rtrim( $site_url, '/' ) ) );
        
        // Always send deactivation ping when theme is being deleted
        // Use blocking request with longer timeout to ensure it completes
        $endpoint = cpa_accountant_free_get_tracker_endpoint();
        
        if ( ! empty( $endpoint ) && filter_var( $endpoint, FILTER_VALIDATE_URL ) ) {
            // Get deactivation endpoint
            $deactivation_endpoint = str_replace( '/themes/register', '/themes/deactivate', $endpoint );
            
            $payload = array(
                'theme_slug' => $theme_slug,
                'site_url'   => $site_url,
                'site_hash'  => $site_hash,
                'is_active'  => false,
                'deleted'    => true, // Flag to indicate theme is being deleted
            );
            
            // Send blocking request with longer timeout
            // This ensures the request completes before theme files are deleted
            $response = wp_remote_post(
                $deactivation_endpoint,
                array(
                    'timeout' => 30, // Increased timeout for deletion
                    'blocking' => true, // Blocking request - wait for response
                    'headers' => array(
                        'Content-Type' => 'application/json',
                    ),
                    'body'    => wp_json_encode( $payload ),
                    'sslverify' => true,
                )
            );
            
            // Log the response for debugging
            if ( is_wp_error( $response ) ) {
                // Store error for debugging
                update_option( 'cpa_accountant_free_deletion_error', array(
                    'error' => true,
                    'message' => $response->get_error_message(),
                    'code' => $response->get_error_code(),
                    'time' => current_time( 'mysql' ),
                    'endpoint' => $deactivation_endpoint,
                ), false );
            } else {
                $code = wp_remote_retrieve_response_code( $response );
                $body = wp_remote_retrieve_body( $response );
                
                // Store response for debugging
                update_option( 'cpa_accountant_free_deletion_response', array(
                    'code' => $code,
                    'body' => substr( $body, 0, 500 ),
                    'time' => current_time( 'mysql' ),
                    'endpoint' => $deactivation_endpoint,
                    'success' => ( $code >= 200 && $code < 300 ),
                ), false );
            }
        }
        
        // Store deletion marker in database (persists even after theme deletion)
        // Plugin can check this option to verify theme was deleted
        update_option( 'cpa_accountant_free_theme_deleted', array(
            'theme_slug' => $theme_slug,
            'site_url' => $site_url,
            'site_hash' => $site_hash,
            'deleted_at' => current_time( 'mysql' ),
            'timestamp' => time(),
        ), false );
        
        // Clear tracking schedule immediately
        cpa_accountant_free_clear_tracking_schedule();
        
        // Clean up all tracking-related options (except deletion marker)
        delete_option( 'cpa_accountant_free_tracker_last_sent' );
        delete_option( 'cpa_accountant_free_tracker_last_response' );
        delete_option( 'cpa_accountant_free_theme_deactivated' );
    }
}
add_action( 'delete_theme', 'cpa_accountant_free_on_theme_deletion', 10, 1 );

/**
 * Get tracker status information for admin display.
 *
 * @return array
 */
function cpa_accountant_free_get_tracker_status() {
    $endpoint = cpa_accountant_free_get_tracker_endpoint();
    $last_sent = get_option( 'cpa_accountant_free_tracker_last_sent', array() );
    $last_response = get_option( 'cpa_accountant_free_tracker_last_response', array() );

    $theme = wp_get_theme();
    $site_url = home_url();
    $site_hash = hash( 'sha256', strtolower( rtrim( $site_url, '/' ) ) );
    
    // Check if cron is scheduled
    $hook = 'cpa_accountant_free_tracker_ping';
    $next_cron = wp_next_scheduled( $hook );
    $is_theme_active = cpa_accountant_free_is_theme_active();

    $status = array(
        'endpoint'      => $endpoint,
        'theme_slug'    => $theme->get_stylesheet(),
        'theme_name'    => $theme->get( 'Name' ),
        'theme_version' => $theme->get( 'Version' ),
        'site_url'      => $site_url,
        'site_hash'     => $site_hash,
        'last_sent'     => isset( $last_sent['timestamp'] ) ? $last_sent['timestamp'] : null,
        'last_sent_formatted' => isset( $last_sent['timestamp'] ) ? date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $last_sent['timestamp'] ) : __( 'Never', 'cpa-accountant-free' ),
        'next_send'     => null,
        'next_send_formatted' => null,
        'next_cron'     => $next_cron,
        'next_cron_formatted' => $next_cron ? date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $next_cron ) : __( 'Not Scheduled', 'cpa-accountant-free' ),
        'is_cron_scheduled' => (bool) $next_cron,
        'is_theme_active' => $is_theme_active,
        'last_response' => $last_response,
        'is_plugin_active' => class_exists( 'Notify_Manager' ),
    );

    if ( isset( $last_sent['timestamp'] ) ) {
        $interval = (int) apply_filters( 'cpa_accountant_free_tracker_interval', 12 * HOUR_IN_SECONDS );
        $next_send = $last_sent['timestamp'] + $interval;
        $status['next_send'] = $next_send;
        $status['next_send_formatted'] = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $next_send );
    }

    return $status;
}

/**
 * Force send tracker ping (for admin use).
 * Only works if theme is currently active.
 *
 * @return array Result with success status and message.
 */
function cpa_accountant_free_force_tracker_ping() {
    // Check if theme is active first
    if ( ! cpa_accountant_free_is_theme_active() ) {
        return array(
            'success' => false,
            'message' => __( 'Theme is not active. Tracking only works when theme is active.', 'cpa-accountant-free' ),
        );
    }
    
    // Clear last sent option to force immediate ping
    delete_option( 'cpa_accountant_free_tracker_last_sent' );

    // Add filter to force ping
    add_filter( 'cpa_accountant_free_force_tracker_ping', '__return_true' );

    // Call the ping function directly
    cpa_accountant_free_maybe_send_tracker_ping();

    // Remove filter
    remove_filter( 'cpa_accountant_free_force_tracker_ping', '__return_true' );

    $last_sent = get_option( 'cpa_accountant_free_tracker_last_sent', array() );
    $last_response = get_option( 'cpa_accountant_free_tracker_last_response', array() );

    if ( ! empty( $last_sent ) ) {
        return array(
            'success' => true,
            'message' => __( 'Tracker ping sent successfully!', 'cpa-accountant-free' ),
            'response' => $last_response,
        );
    } else {
        return array(
            'success' => false,
            'message' => __( 'Failed to send tracker ping. Check error logs if WP_DEBUG is enabled.', 'cpa-accountant-free' ),
        );
    }
}

