<?php
/**
 * Ad Layouts settings tab (PRD E4).
 *
 * Independent of signing and of the enrollment card: the mode is OFF by
 * default and turning it on changes nothing about how content is signed.
 * Included from AdLayouts::render_admin_page(), which has already checked
 * `manage_options`; the form itself is submitted to options.php with the
 * settings-group nonce from settings_fields().
 */

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- template locals scoped to AdLayouts::render_admin_page().

namespace EncypherProvenance;

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

$settings = AdLayouts::settings();
$state = AdLayouts::state();
$enrollment_id = AdLayouts::enrollment_id();
$can_raw_html = current_user_can('unfiltered_html');
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only status written by the nonce-protected seed action.
$demo_created = isset($_GET['encypher_demo_created']) && 1 === (int) $_GET['encypher_demo_created'];
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- numeric post id used only for capability-checked links.
$demo_post_id = isset($_GET['encypher_demo_post']) ? (int) $_GET['encypher_demo_post'] : 0;
?>
<div class="wrap encypher-ad-layouts-page">
    <h1><?php esc_html_e('Encypher Ad Layouts', 'encypher-provenance'); ?></h1>
    <p class="description">
        <?php esc_html_e('Optional. Reserve structured ad containers on this site and register them as enumerable AdCP inventory. Choose fixed placements, then add your ad-server tag to any slot you want to fill.', 'encypher-provenance'); ?>
    </p>

    <?php settings_errors(AdLayouts::OPTION); ?>
    <?php if ($demo_created && $demo_post_id > 0 && current_user_can('edit_post', $demo_post_id)) : ?>
        <div class="notice notice-success is-dismissible">
            <p>
                <strong><?php esc_html_e('Signed demo article created.', 'encypher-provenance'); ?></strong>
                <?php esc_html_e('The article and its image, audio, and video are queued on the normal Encypher rich-signing path.', 'encypher-provenance'); ?>
                <a href="<?php echo esc_url(get_permalink($demo_post_id)); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e('View article', 'encypher-provenance'); ?></a>
                &nbsp;|&nbsp;
                <a href="<?php echo esc_url(get_edit_post_link($demo_post_id)); ?>"><?php esc_html_e('Edit article', 'encypher-provenance'); ?></a>
            </p>
        </div>
    <?php endif; ?>

    <?php if ('' === $enrollment_id) : ?>
        <div class="notice notice-warning">
            <p>
                <strong><?php esc_html_e('Enroll first.', 'encypher-provenance'); ?></strong>
                <?php esc_html_e('This site is not enrolled in the AdCP managed seller network, so no placement can be registered. Complete enrollment from the Encypher setup screen. You can still switch the mode on and lay out containers now: each activated slot is registered as soon as this site is enrolled.', 'encypher-provenance'); ?>
            </p>
        </div>
    <?php endif; ?>

    <?php if (! $can_raw_html) : ?>
        <div class="notice notice-info">
            <p>
                <?php esc_html_e('Your account cannot store ad tags. An ad tag is output as raw HTML, so changing one requires the unfiltered_html capability, the same rule WordPress applies to its Custom HTML widget. You can still activate and deactivate slots.', 'encypher-provenance'); ?>
            </p>
        </div>
    <?php endif; ?>

    <form method="post" action="options.php">
        <?php settings_fields(AdLayouts::SETTINGS_GROUP); ?>

        <table class="form-table" role="presentation">
            <tbody>
                <tr>
                    <th scope="row"><?php esc_html_e('Ad Layouts mode', 'encypher-provenance'); ?></th>
                    <td>
                        <label for="encypher-ad-layouts-enabled">
                            <input
                                id="encypher-ad-layouts-enabled"
                                type="checkbox"
                                name="<?php echo esc_attr(AdLayouts::OPTION); ?>[enabled]"
                                value="1"
                                <?php checked($settings['enabled']); ?>
                            />
                            <?php esc_html_e('Enable ad layouts on this site', 'encypher-provenance'); ?>
                        </label>
                        <p class="description">
                            <?php esc_html_e('Off by default. While off, no container is rendered anywhere and every registered placement is soft-removed.', 'encypher-provenance'); ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="encypher-ad-layouts-every-n"><?php esc_html_e('In-content frequency', 'encypher-provenance'); ?></label>
                    </th>
                    <td>
                        <input
                            id="encypher-ad-layouts-every-n"
                            type="number"
                            min="1"
                            max="20"
                            step="1"
                            class="small-text"
                            name="<?php echo esc_attr(AdLayouts::OPTION); ?>[in_content_every_n]"
                            value="<?php echo esc_attr((string) $settings['in_content_every_n']); ?>"
                        />
                        <p class="description">
                            <?php esc_html_e('Insert the in-content container after every N paragraphs of a single post or page. Never after the final paragraph.', 'encypher-provenance'); ?>
                        </p>
                    </td>
                </tr>
            </tbody>
        </table>

        <h2><?php esc_html_e('Layout presets', 'encypher-provenance'); ?></h2>
        <p class="description">
            <?php esc_html_e('Activating a slot registers one placement whose key is stable for this site and slot. Deactivating it soft-removes that placement; the key is reused if you activate the slot again.', 'encypher-provenance'); ?>
        </p>

        <?php foreach (AdLayouts::layout_keys() as $layout_key) : ?>
            <?php
            $slot = $settings['slots'][$layout_key];
            $placement_key = AdLayouts::placement_key_for($layout_key);
            $record = isset($state[$placement_key]) && is_array($state[$placement_key]) ? $state[$placement_key] : [];
            $field_id = 'encypher-ad-slot-' . AdLayouts::slug_for($layout_key);
            if ('' !== ($record['last_error'] ?? '')) {
                $registration = __('Queued', 'encypher-provenance');
            } elseif (! empty($record['synced']) && 'active' === ($record['state'] ?? '')) {
                $registration = __('Registered', 'encypher-provenance');
            } elseif (! empty($record['synced']) && 'removed' === ($record['state'] ?? '')) {
                $registration = __('Removed', 'encypher-provenance');
            } else {
                $registration = __('Not registered', 'encypher-provenance');
            }
            ?>
            <table class="form-table" role="presentation">
                <tbody>
                    <tr>
                        <th scope="row"><?php echo esc_html(AdLayouts::label_for($layout_key)); ?></th>
                        <td>
                            <label for="<?php echo esc_attr($field_id . '-active'); ?>">
                                <input
                                    id="<?php echo esc_attr($field_id . '-active'); ?>"
                                    type="checkbox"
                                    name="<?php echo esc_attr(AdLayouts::OPTION); ?>[slots][<?php echo esc_attr($layout_key); ?>][active]"
                                    value="1"
                                    <?php checked($slot['active']); ?>
                                />
                                <?php esc_html_e('Activate this slot', 'encypher-provenance'); ?>
                            </label>
                            <p class="description">
                                <?php esc_html_e('layout_key:', 'encypher-provenance'); ?> <code><?php echo esc_html($layout_key); ?></code>
                                &nbsp;<?php esc_html_e('format_id:', 'encypher-provenance'); ?> <code><?php echo esc_html(AdLayouts::format_for($layout_key)); ?></code>
                                <br />
                                <?php esc_html_e('placement_key:', 'encypher-provenance'); ?> <code><?php echo esc_html($placement_key); ?></code>
                                &nbsp;&mdash;&nbsp;<?php echo esc_html($registration); ?>
                            </p>
                            <p>
                                <label for="<?php echo esc_attr($field_id . '-tag'); ?>">
                                    <?php esc_html_e('Ad tag for this slot (optional)', 'encypher-provenance'); ?>
                                </label>
                                <br />
                                <textarea
                                    id="<?php echo esc_attr($field_id . '-tag'); ?>"
                                    class="large-text code"
                                    rows="4"
                                    name="<?php echo esc_attr(AdLayouts::OPTION); ?>[slots][<?php echo esc_attr($layout_key); ?>][ad_tag]"
                                    <?php disabled(! $can_raw_html); ?>
                                ><?php echo esc_textarea((string) $slot['ad_tag']); ?></textarea>
                            </p>
                            <p class="description">
                                <?php esc_html_e('Pasted exactly as your ad server gave it to you and output verbatim inside this slot\'s container only. Treat it like the Custom HTML widget: anything you paste here runs on your site.', 'encypher-provenance'); ?>
                            </p>
                        </td>
                    </tr>
                </tbody>
            </table>
        <?php endforeach; ?>

        <?php submit_button(); ?>
    </form>

    <hr />
    <h2><?php esc_html_e('Showcase the full flow', 'encypher-provenance'); ?></h2>
    <p class="description">
        <?php esc_html_e('Create a polished public article with a hero image, source-note audio, a short video, and an in-content Ad Layout block. The plugin publishes it and queues the whole multimedia record for signing through the same path used by real editorial content. Running this again refreshes the existing demo instead of creating duplicates.', 'encypher-provenance'); ?>
    </p>
    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
        <input type="hidden" name="action" value="encypher_seed_ad_layouts_demo" />
        <?php wp_nonce_field('encypher_seed_ad_layouts_demo'); ?>
        <?php submit_button(__('Create signed demo article', 'encypher-provenance'), 'secondary', 'submit', false); ?>
    </form>
</div>
