<?php
/**
 * Name: Header & Footer Code
 * Description: Insert custom HTML, CSS, or JavaScript code in header, body start, or footer sections without editing theme files for analytics tracking or scripts
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Add Useful Functionality",
 *     "description": "Extend WordPress with helpful tools that make site management easier."
 *   },
 *   {
 *     "title": "Save Time",
 *     "description": "Automate or simplify tasks that would otherwise require manual work or additional tools."
 *   }
 * ]
 * WhereToFind: {
 *   "location": "Page Source (HTML)",
 *   "url": "/",
 *   "instructions": "View page source (Ctrl+U / Cmd+U) to see code in <head> or before </body>",
 *   "newTab": true
 * }
 * Added: 2025-08-08
 * Tags: code, header, footer, tracking, analytics, scripts
 */

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

class SwitchboardHeaderFooterCode {
    
    public function __construct() {
        add_action('wp_head', [$this, 'add_header_code']);
        add_action('wp_body_open', [$this, 'add_body_code']);
        add_action('wp_footer', [$this, 'add_footer_code']);
    }

    /**
     * Register data locations for this module
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_header-footer-code_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => []
        ];
    }
    
    /**
     * Render settings panel for Header & Footer Code
     *
     * Displays settings interface for injecting custom code in three locations with:
     * - Header code textarea for wp_head hook (inside <head> tag)
     * - Body code textarea for wp_body_open hook (right after <body> tag)
     * - Footer code textarea for wp_footer hook (before </body> closing tag)
     * - All textareas use monospace font for code readability
     * - Clear descriptions for each injection point
     *
     * The interface provides a simple way to add custom HTML, CSS, or JavaScript without
     * editing theme files. The header textarea is ideal for meta tags, CSS links, analytics
     * code, or verification codes (Google Search Console, Facebook Pixel setup). The body
     * code textarea is perfect for tag manager containers like Google Tag Manager that
     * recommend placement immediately after opening body tag. The footer textarea suits
     * deferred JavaScript, chat widgets, or analytics that don't need to block page
     * rendering. Each textarea accepts raw HTML/CSS/JavaScript and outputs it exactly as
     * entered, allowing maximum flexibility. This is essential for adding third-party
     * integrations, custom tracking, or performance optimization scripts without theme
     * modifications that would be lost during theme updates.
     *
     * @param array $settings Current module settings with 'header_code', 'body_code', 'footer_code' keys
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $header_code = isset($settings['header_code']) ? $settings['header_code'] : '';
        $body_code = isset($settings['body_code']) ? $settings['body_code'] : '';
        $footer_code = isset($settings['footer_code']) ? $settings['footer_code'] : '';
        ?>
        <input type="hidden" name="module" value="header-footer-code">

        <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm">How It Works</h4>
            <p class="sb-sp-description" style="margin: 0;">Insert custom HTML, CSS, or JavaScript code in header, body start, or footer sections without editing theme files. Perfect for analytics tracking, verification codes, or custom scripts.</p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Header Code</h3>
            <p class="sb-sp-description">Code inserted in the <code>&lt;head&gt;</code> section via <code>wp_head</code> hook. Ideal for meta tags, CSS links, analytics code, or verification codes.</p>
            <label for="setting_header_code" class="sb-sp-label"><?php esc_html_e('Header Code (wp_head)', 'wpswitchboard'); ?></label>
            <textarea name="setting_header_code" id="setting_header_code" rows="8" class="sb-sp-textarea sb-sp-font-mono" style="width: 100%; font-family: 'Courier New', monospace; font-size: 13px;"><?php echo esc_textarea($header_code); ?></textarea>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Body Code</h3>
            <p class="sb-sp-description">Code inserted right after the opening <code>&lt;body&gt;</code> tag via <code>wp_body_open</code> hook. Perfect for tag manager containers like Google Tag Manager.</p>
            <label for="setting_body_code" class="sb-sp-label"><?php esc_html_e('Body Code (wp_body_open)', 'wpswitchboard'); ?></label>
            <textarea name="setting_body_code" id="setting_body_code" rows="8" class="sb-sp-textarea sb-sp-font-mono" style="width: 100%; font-family: 'Courier New', monospace; font-size: 13px;"><?php echo esc_textarea($body_code); ?></textarea>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Footer Code</h3>
            <p class="sb-sp-description">Code inserted before the closing <code>&lt;/body&gt;</code> tag via <code>wp_footer</code> hook. Ideal for deferred JavaScript, chat widgets, or analytics that don't need to block page rendering.</p>
            <label for="setting_footer_code" class="sb-sp-label"><?php esc_html_e('Footer Code (wp_footer)', 'wpswitchboard'); ?></label>
            <textarea name="setting_footer_code" id="setting_footer_code" rows="8" class="sb-sp-textarea sb-sp-font-mono" style="width: 100%; font-family: 'Courier New', monospace; font-size: 13px;"><?php echo esc_textarea($footer_code); ?></textarea>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-tip">
            <h4 class="sb-sp-heading-sm">Tips</h4>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item"><?php esc_html_e('All code is output exactly as entered - no modifications are made', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('PHP tags are automatically removed for security', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('Changes persist through theme updates since they\'re stored in the database', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('View page source (Ctrl+U / Cmd+U) to verify your code is inserted correctly', 'wpswitchboard'); ?></li>
            </ul>
        </div>
        <?php
    }
    
    public function add_header_code() {
        $settings = get_option('switchboard_header-footer-code_settings', []);
        $code = isset($settings['header_code']) ? $settings['header_code'] : '';
        if (!empty($code)) {
            // Security: Remove PHP tags but allow tracking codes with inline scripts
            $code = str_replace(['<?php', '<?', '?>'], '', $code);
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Intentional: admin-entered header/footer code
            echo $code . "\n";
        }
    }

    public function add_body_code() {
        $settings = get_option('switchboard_header-footer-code_settings', []);
        $code = isset($settings['body_code']) ? $settings['body_code'] : '';
        if (!empty($code)) {
            // Security: Remove PHP tags but allow tracking codes with inline scripts
            $code = str_replace(['<?php', '<?', '?>'], '', $code);
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Intentional: admin-entered header/footer code
            echo $code . "\n";
        }
    }

    public function add_footer_code() {
        $settings = get_option('switchboard_header-footer-code_settings', []);
        $code = isset($settings['footer_code']) ? $settings['footer_code'] : '';
        if (!empty($code)) {
            // Security: Remove PHP tags but allow tracking codes with inline scripts
            $code = str_replace(['<?php', '<?', '?>'], '', $code);
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Intentional: admin-entered header/footer code
            echo $code . "\n";
        }
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardHeaderFooterCode();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
