<?php
/**
 * Name: Heartbeat Control
 * Description: Control WordPress Heartbeat API frequency to reduce server load by limiting automatic background AJAX requests in admin dashboard, frontend, and post editor
 * Category: Optimization
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Reduce Server Load",
 *     "description": "Limit Heartbeat API frequency on shared hosting to prevent excessive AJAX requests from draining server resources during peak traffic."
 *   },
 *   {
 *     "title": "Multi-User Sites",
 *     "description": "Optimize Heartbeat for sites with 20+ simultaneous editors to prevent admin slowdown from constant post locking checks."
 *   },
 *   {
 *     "title": "Low-Resource Hosting",
 *     "description": "Disable or slow down Heartbeat on budget hosting plans where frequent AJAX calls impact site performance."
 *   }
 * ]
 * Added: 2025-07-12
 * Tags: heartbeat, performance, optimization, ajax
 * WhereToFind: {
 *   "location": "Switchboard Settings",
 *   "url": "",
 *   "instructions": "Set Heartbeat API frequency or disable entirely in module settings. Check Browser DevTools → Network tab → Filter 'heartbeat' to verify request frequency.",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardHeartbeatControl {
    
    public function __construct() {
        add_filter('heartbeat_settings', [$this, 'modify_heartbeat_settings']);
        add_action('init', [$this, 'maybe_disable_heartbeat'], 11);
    }
    
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_heartbeat-control_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'term_meta' => [],
            'transients' => []
        ];
    }
    
    /**
     * Render settings panel for Heartbeat Control
     * 
     * Displays settings interface for controlling WordPress Heartbeat API with:
     * - Location selector dropdown (everywhere, admin only, disable dashboard, disable all)
     * - Frequency selector dropdown (15s, 30s, 60s, 120s intervals)
     * 
     * The Heartbeat API is WordPress's built-in system for sending periodic AJAX requests
     * to check for updates, autosave content, and maintain session connectivity. Controlling
     * it helps reduce server load and improve performance.
     * 
     * @param array $settings Current module settings with 'location' and 'frequency' keys
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $location = isset($settings['location']) ? $settings['location'] : 'everywhere';
        $frequency = isset($settings['frequency']) ? intval($settings['frequency']) : 15;
        ?>
        <input type="hidden" name="module" value="heartbeat-control">
        
        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_location" class="sb-sp-label"><?php esc_html_e('Heartbeat Location', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Control where the WordPress Heartbeat API is active.', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_location" id="setting_location" class="sb-sp-select">
                <option value="everywhere" <?php selected($location, 'everywhere'); ?>><?php esc_html_e('Allow Everywhere', 'wpswitchboard'); ?></option>
                <option value="admin_only" <?php selected($location, 'admin_only'); ?>><?php esc_html_e('Admin Only', 'wpswitchboard'); ?></option>
                <option value="disable_dashboard" <?php selected($location, 'disable_dashboard'); ?>><?php esc_html_e('Disable on Dashboard', 'wpswitchboard'); ?></option>
                <option value="disable_all" <?php selected($location, 'disable_all'); ?>><?php esc_html_e('Disable Everywhere', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_frequency" class="sb-sp-label"><?php esc_html_e('Heartbeat Frequency', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('How often the heartbeat should check for updates.', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_frequency" id="setting_frequency" class="sb-sp-select">
                <option value="15" <?php selected($frequency, 15); ?>><?php esc_html_e('15 seconds (Default)', 'wpswitchboard'); ?></option>
                <option value="30" <?php selected($frequency, 30); ?>><?php esc_html_e('30 seconds', 'wpswitchboard'); ?></option>
                <option value="60" <?php selected($frequency, 60); ?>><?php esc_html_e('60 seconds', 'wpswitchboard'); ?></option>
                <option value="120" <?php selected($frequency, 120); ?>><?php esc_html_e('120 seconds', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-info">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('About Heartbeat API', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description" style="margin: 0;">
                <?php esc_html_e('The Heartbeat API sends periodic AJAX requests to check for updates, autosave content, and maintain session connectivity. Controlling it helps reduce server load and improve performance, especially on shared hosting or sites with many simultaneous users.', 'wpswitchboard'); ?>
            </p>
        </div>
        <?php
    }
    
    private function get_settings() {
        $modules = get_option('switchboard_modules', []);
        if (isset($modules['heartbeat-control']['settings']) && is_array($modules['heartbeat-control']['settings'])) {
            return $modules['heartbeat-control']['settings'];
        }
        return [];
    }
    
    public function modify_heartbeat_settings($settings) {
        $module_settings = $this->get_settings();
        $frequency = isset($module_settings['frequency']) ? intval($module_settings['frequency']) : 15;
        $settings['interval'] = $frequency;
        return $settings;
    }
    
    public function maybe_disable_heartbeat() {
        $module_settings = $this->get_settings();
        $location = isset($module_settings['location']) ? $module_settings['location'] : 'everywhere';
        
        if ($location === 'disable_all') {
            wp_deregister_script('heartbeat');
        } elseif ($location === 'admin_only' && !is_admin()) {
            wp_deregister_script('heartbeat');
        } elseif ($location === 'disable_dashboard' && is_admin()) {
            global $pagenow;
            if (!empty($pagenow) && $pagenow === 'index.php') {
                wp_deregister_script('heartbeat');
            }
        }
    }
}

$switchboard_instance = new SwitchboardHeartbeatControl();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
