<?php
/**
 * Name: Ads.txt Manager
 * Description: Manage ads.txt file directly from WordPress dashboard to authorize digital sellers and prevent unauthorized ad inventory sales for programmatic advertising revenue protection
 * 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."
 *   }
 * ]
 * Added: 2025-07-06
 * Tags: ads, advertising, monetization, txt, google-adsense
 * WhereToFind: {
 *   "location": "Configure in module settings",
 *   "url": "",
 *   "instructions": "Edit ads.txt content - live at /ads.txt",
 *   "newTab": false
 * }
 */

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

class SwitchboardAdsTxt {
    
    public function __construct() {
        // Use do_parse_request filter to intercept very early
        add_filter('do_parse_request', [$this, 'intercept_ads_txt'], 0, 3);
    }

    /**
     * Register data locations for this module
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_ads-txt_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => []
        ];
    }
    
    /**
     * Render settings panel for Ads.txt Manager
     *
     * Displays settings interface for managing ads.txt file with:
     * - Large monospace textarea for ads.txt content entry
     * - Clear labeling and helpful description with URL display
     * - Example ads.txt entry format for Google AdSense
     * - Direct display of where the file will be accessible
     *
     * The interface provides simple management of the ads.txt file for authorized
     * digital sellers verification. Publishers can add entries from advertising networks
     * like Google AdSense, MediaVine, or other programmatic advertising partners. The
     * textarea uses monospace font for better readability of technical content. Each
     * entry typically includes domain name, publisher account ID, relationship type
     * (DIRECT/RESELLER), and certification authority ID. The module intercepts requests
     * to /ads.txt very early in the WordPress loading process to serve the custom content
     * with proper text/plain headers. This prevents unauthorized inventory sales and helps
     * combat ad fraud by clearly identifying who is authorized to sell the site's ad inventory.
     * Essential for sites using programmatic advertising or participating in ad networks.
     *
     * @param array $settings Current module settings with 'content' key containing ads.txt entries
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $content = isset($settings['content']) ? $settings['content'] : '';
        ?>
        <input type="hidden" name="module" value="ads-txt">

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading"><?php esc_html_e('Ads.txt Manager', 'wpswitchboard'); ?></h3>
            <p class="sb-sp-description"><?php esc_html_e('Manage your ads.txt file directly from WordPress dashboard to authorize digital sellers and prevent unauthorized ad inventory sales.', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <label for="setting_content" class="sb-sp-label"><?php esc_html_e('Ads.txt Content', 'wpswitchboard'); ?></label>
            <textarea name="setting_content" id="setting_content" rows="12" class="sb-sp-textarea sb-sp-w-full" style="font-family: 'Courier New', monospace; font-size: 13px;"><?php echo esc_textarea($content); ?></textarea>
            <p class="sb-sp-description"><?php
            // translators: %s is the URL where ads.txt is accessible
            printf(esc_html__('Enter your ads.txt content for advertising networks. This will be accessible at %s', 'wpswitchboard'), '<code>' . esc_url(home_url('/ads.txt')) . '</code>'); ?></p>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-tip">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Example Format', 'wpswitchboard'); ?></h4>
            <div style="background: #ffffff; border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px; margin-top: 8px;">
                <code style="font-family: 'Courier New', monospace; font-size: 13px; color: #111827; display: block; white-space: pre-wrap; word-break: break-all;">google.com, pub-0000000000000000, DIRECT, f08c47fec0942fa0</code>
            </div>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-top: 24px;">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('About Ads.txt', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description" style="margin: 0;">
                <?php esc_html_e('The ads.txt file helps prevent unauthorized inventory sales and combat ad fraud by clearly identifying who is authorized to sell your site\'s ad inventory. Essential for sites using programmatic advertising or participating in ad networks like Google AdSense, MediaVine, or other partners.', 'wpswitchboard'); ?>
            </p>
        </div>
        <?php
    }
    
    public function intercept_ads_txt($do_parse, $wp, $extra_query_vars) {
        // Get the request path
        $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
        $path = wp_parse_url($request_uri, PHP_URL_PATH);
        
        // Normalize path
        $path = trim($path, '/');
        
        // Check if this is an ads.txt request
        if ($path === 'ads.txt') {
            $settings = get_option('switchboard_ads-txt_settings', []);
            $content = isset($settings['content']) ? $settings['content'] : '';

            // Output the content (no escaping needed - plain text content already sanitized on save)
            status_header(200);
            header('Content-Type: text/plain; charset=utf-8');
            header('X-Robots-Tag: noindex');
            echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Raw text output for ads.txt
            exit;
        }
        
        return $do_parse;
    }
}

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