<?php
namespace EncypherProvenance;

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

/**
 * PRD E4 `sidebar_rail` preset: a classic widget that emits the fenced
 * sidebar-rail container. Loaded on `widgets_init` (so WP_Widget exists) by
 * AdLayouts::register_widget().
 *
 * The widget carries no settings of its own: the placement key, format, and
 * optional publisher-pasted ad tag all come from the Ad Layouts settings tab,
 * where the ad tag is capability- and nonce-gated. Dropping the widget into a
 * sidebar therefore cannot introduce raw HTML that an editor could not already
 * store.
 */
final class AdSlotWidget extends \WP_Widget
{
    public function __construct()
    {
        parent::__construct(
            'encypher_ad_slot',
            __('Encypher Ad Slot (sidebar rail)', 'encypher-provenance'),
            [
                'classname' => 'encypher-ad-slot-widget',
                'description' => __('Reserved sidebar-rail ad container registered as AdCP inventory. Renders nothing until you paste an ad tag in Encypher > Ad Layouts.', 'encypher-provenance'),
                'show_instance_in_rest' => true,
            ]
        );
    }

    /**
     * @param array $args     Sidebar arguments.
     * @param array $instance Saved widget values (unused).
     */
    public function widget($args, $instance): void
    {
        unset($instance);
        $html = AdLayouts::render_slot('sidebar_rail');
        if ('' === $html) {
            return;
        }

        if (isset($args['before_widget'])) {
            echo wp_kses_post((string) $args['before_widget']);
        }
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- container attributes are esc_attr()'d in AdLayouts::container_html(); the optional inner ad tag is publisher-pasted raw HTML stored under the unfiltered_html capability (same trust class as core's Custom HTML widget).
        echo $html;
        if (isset($args['after_widget'])) {
            echo wp_kses_post((string) $args['after_widget']);
        }
    }

    /**
     * @param array $instance Saved widget values.
     */
    public function form($instance): void
    {
        unset($instance);
        echo '<p>' . esc_html__('This widget renders the sidebar-rail ad container. Activate the slot and paste your ad tag in Encypher > Ad Layouts.', 'encypher-provenance') . '</p>';
    }

    /**
     * @param array $new_instance Submitted values.
     * @param array $old_instance Previous values.
     */
    public function update($new_instance, $old_instance): array
    {
        unset($new_instance, $old_instance);

        return [];
    }
}
