<?php
/**
 * AdCP managed-seller enrollment card.
 *
 * Included from SellerEnrollment::render_page(), which only reaches this file
 * after a manage_options check and after the server confirmed the enrollment
 * API exists. Every state change posts to admin-post.php with its own nonce.
 *
 * @var array{
 *   domain:string,
 *   identity_id:string,
 *   identity_verified:bool,
 *   challenge_url:string,
 *   enrollment:array<string,mixed>|null,
 *   enrollment_id:string,
 *   evidence_count:int,
 *   placement_count:int,
 *   sales_house:array<string,mixed>|null,
 *   terms:array{document_key:string,document_sha256:string,content:string}|null,
 *   status_error:string,
 *   notice:array{type:string,message:string}|null,
 *   action_url:string,
 *   is_connected:bool
 * } $view
 *
 * @package EncypherProvenance
 */

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Included inside SellerEnrollment::render_page(); $view is local to that method.

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

$enrollment = $view['enrollment'];
$state = is_array($enrollment) ? (string) ($enrollment['state'] ?? '') : '';
$is_enrolled = 'enrolled' === $state;
?>
<div class="wrap encypher-settings-page">
    <header class="encypher-page-header">
        <h1 class="encypher-page-title">
            <img
                class="encypher-brand-lockup"
                src="<?php echo esc_url(ENCYPHER_PROVENANCE_PLUGIN_URL . 'assets/images/encypher_full_logo_color.svg'); ?>"
                alt="<?php echo esc_attr__('Encypher', 'encypher-provenance'); ?>"
            />
            <span class="encypher-title-divider" aria-hidden="true">/</span>
            <span><?php esc_html_e('AdCP Seller Network', 'encypher-provenance'); ?></span>
        </h1>
        <p class="description">
            <?php esc_html_e('Enroll this property as managed-seller inventory backed by your signed content. Encypher never serves ads and never exposes your inventory to a buyer without a contract and an explicit grant.', 'encypher-provenance'); ?>
        </p>
    </header>

    <?php if (null !== $view['notice']) : ?>
        <div class="notice notice-<?php echo esc_attr('success' === $view['notice']['type'] ? 'success' : 'error'); ?>">
            <p><?php echo esc_html($view['notice']['message']); ?></p>
        </div>
    <?php endif; ?>

    <?php if ('' !== $view['status_error']) : ?>
        <div class="notice notice-warning">
            <p><?php echo esc_html($view['status_error']); ?></p>
        </div>
    <?php endif; ?>

    <?php if (! $view['is_connected']) : ?>
        <div class="notice notice-info">
            <p><?php esc_html_e('Connect this site to an Encypher organization on the Setup & Health screen before enrolling.', 'encypher-provenance'); ?></p>
        </div>
        </div>
        <?php return; ?>
    <?php endif; ?>

    <section class="encypher-connect-card" aria-labelledby="encypher-adcp-domain-title">
        <h2 id="encypher-adcp-domain-title"><?php esc_html_e('1. Verify this domain', 'encypher-provenance'); ?></h2>
        <p>
            <?php esc_html_e('Domain:', 'encypher-provenance'); ?>
            <strong><?php echo esc_html($view['domain']); ?></strong>
        </p>

        <?php if ($view['identity_verified']) : ?>
            <p><?php esc_html_e('Status: verified. WordPress served the verification document for you; no DNS record or file upload was needed.', 'encypher-provenance'); ?></p>
        <?php else : ?>
            <p>
                <?php esc_html_e('One click registers this exact domain with Encypher, serves the challenge document from WordPress at /.well-known/encypher.json, and asks Encypher to read it back. No filesystem or DNS access is required.', 'encypher-provenance'); ?>
            </p>
            <?php if ('' !== $view['challenge_url']) : ?>
                <p class="description">
                    <?php esc_html_e('Challenge document:', 'encypher-provenance'); ?>
                    <code><?php echo esc_html($view['challenge_url']); ?></code>
                </p>
            <?php endif; ?>
            <form method="post" action="<?php echo esc_url($view['action_url']); ?>">
                <?php wp_nonce_field(\EncypherProvenance\SellerEnrollment::ACTION_VERIFY); ?>
                <input type="hidden" name="action" value="<?php echo esc_attr(\EncypherProvenance\SellerEnrollment::ACTION_VERIFY); ?>" />
                <button type="submit" class="button button-primary">
                    <?php esc_html_e('Verify this domain', 'encypher-provenance'); ?>
                </button>
            </form>
        <?php endif; ?>
    </section>

    <?php if ($view['identity_verified'] && ! $is_enrolled) : ?>
        <section class="encypher-connect-card" aria-labelledby="encypher-adcp-terms-title">
            <h2 id="encypher-adcp-terms-title"><?php esc_html_e('2. Accept the enrollment terms and enroll', 'encypher-provenance'); ?></h2>

            <?php if (null === $view['terms']) : ?>
                <p><?php esc_html_e('The enrollment terms document could not be loaded, so enrollment is unavailable right now. Reload this page to try again.', 'encypher-provenance'); ?></p>
            <?php else : ?>
                <div class="encypher-adcp-terms" style="max-height:18em;overflow:auto;padding:.75em;border:1px solid #dcdcde;background:#fff;">
                    <pre style="white-space:pre-wrap;margin:0;"><?php echo esc_html($view['terms']['content']); ?></pre>
                </div>
                <p class="description">
                    <?php
                    printf(
                        /* translators: 1: terms document key, 2: sha256 of the terms document. */
                        esc_html__('Document %1$s, sha256 %2$s. This exact hash is recorded with your acceptance.', 'encypher-provenance'),
                        esc_html($view['terms']['document_key']),
                        esc_html($view['terms']['document_sha256'])
                    );
                    ?>
                </p>

                <form method="post" action="<?php echo esc_url($view['action_url']); ?>">
                    <?php wp_nonce_field(\EncypherProvenance\SellerEnrollment::ACTION_ENROLL); ?>
                    <input type="hidden" name="action" value="<?php echo esc_attr(\EncypherProvenance\SellerEnrollment::ACTION_ENROLL); ?>" />
                    <input type="hidden" name="encypher_adcp_terms_sha256" value="<?php echo esc_attr($view['terms']['document_sha256']); ?>" />

                    <p>
                        <label for="encypher-adcp-accept-terms">
                            <input type="checkbox" id="encypher-adcp-accept-terms" name="encypher_adcp_accept_terms" value="1" required />
                            <?php esc_html_e('I have read and accept the AdCP enrollment terms above on behalf of this organization.', 'encypher-provenance'); ?>
                        </label>
                    </p>

                    <fieldset>
                        <legend><?php esc_html_e('Sales house (optional)', 'encypher-provenance'); ?></legend>
                        <p class="description">
                            <?php esc_html_e('If a sales house monetizes this property, declare it now. Delegation routes fulfillment only: a sales house can never change your enrollment or your offers.', 'encypher-provenance'); ?>
                        </p>
                        <p>
                            <label for="encypher-adcp-sh-key"><?php esc_html_e('Registry key', 'encypher-provenance'); ?></label><br />
                            <input type="text" id="encypher-adcp-sh-key" name="encypher_adcp_sales_house_key" class="regular-text" pattern="[a-z0-9][a-z0-9_]{1,62}" />
                        </p>
                        <p>
                            <label for="encypher-adcp-sh-name"><?php esc_html_e('Display name', 'encypher-provenance'); ?></label><br />
                            <input type="text" id="encypher-adcp-sh-name" name="encypher_adcp_sales_house_name" class="regular-text" />
                        </p>
                        <p>
                            <label for="encypher-adcp-sh-seat"><?php esc_html_e('Seat or network ID (optional)', 'encypher-provenance'); ?></label><br />
                            <input type="text" id="encypher-adcp-sh-seat" name="encypher_adcp_sales_house_seat" class="regular-text" />
                        </p>
                    </fieldset>

                    <button type="submit" class="button button-primary">
                        <?php esc_html_e('Accept terms and enroll', 'encypher-provenance'); ?>
                    </button>
                </form>
            <?php endif; ?>
        </section>
    <?php endif; ?>

    <?php if (is_array($enrollment)) : ?>
        <section class="encypher-connect-card" aria-labelledby="encypher-adcp-status-title">
            <h2 id="encypher-adcp-status-title"><?php esc_html_e('Enrollment status', 'encypher-provenance'); ?></h2>
            <table class="widefat striped">
                <tbody>
                    <tr>
                        <th scope="row"><?php esc_html_e('State', 'encypher-provenance'); ?></th>
                        <td><?php echo esc_html('' !== $state ? $state : __('unknown', 'encypher-provenance')); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Signed publications backing this property', 'encypher-provenance'); ?></th>
                        <td><?php echo esc_html(number_format_i18n($view['evidence_count'])); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Registered placements', 'encypher-provenance'); ?></th>
                        <td><?php echo esc_html(number_format_i18n($view['placement_count'])); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Sales house', 'encypher-provenance'); ?></th>
                        <td>
                            <?php
                            if (is_array($view['sales_house']) && '' !== (string) ($view['sales_house']['display_name'] ?? '')) {
                                echo esc_html((string) $view['sales_house']['display_name']);
                                if ('' !== (string) ($view['sales_house']['declared_seat_or_network_id'] ?? '')) {
                                    echo ' — ' . esc_html((string) $view['sales_house']['declared_seat_or_network_id']);
                                }
                            } else {
                                esc_html_e('None declared', 'encypher-provenance');
                            }
                            ?>
                        </td>
                    </tr>
                </tbody>
            </table>
            <p class="description">
                <?php esc_html_e('Enrollment alone never makes this inventory visible to a buyer: exposure still requires a signed Encypher contract and an explicit grant.', 'encypher-provenance'); ?>
            </p>
        </section>

        <?php if ($is_enrolled) : ?>
            <section class="encypher-connect-card" aria-labelledby="encypher-adcp-sh-title">
                <h2 id="encypher-adcp-sh-title"><?php esc_html_e('Sales-house declaration', 'encypher-provenance'); ?></h2>
                <form method="post" action="<?php echo esc_url($view['action_url']); ?>">
                    <?php wp_nonce_field(\EncypherProvenance\SellerEnrollment::ACTION_SALES_HOUSE); ?>
                    <input type="hidden" name="action" value="<?php echo esc_attr(\EncypherProvenance\SellerEnrollment::ACTION_SALES_HOUSE); ?>" />
                    <p>
                        <label for="encypher-adcp-sh-key-2"><?php esc_html_e('Registry key', 'encypher-provenance'); ?></label><br />
                        <input type="text" id="encypher-adcp-sh-key-2" name="encypher_adcp_sales_house_key" class="regular-text" pattern="[a-z0-9][a-z0-9_]{1,62}" value="<?php echo esc_attr(is_array($view['sales_house']) ? (string) ($view['sales_house']['sales_house_key'] ?? '') : ''); ?>" />
                    </p>
                    <p>
                        <label for="encypher-adcp-sh-name-2"><?php esc_html_e('Display name', 'encypher-provenance'); ?></label><br />
                        <input type="text" id="encypher-adcp-sh-name-2" name="encypher_adcp_sales_house_name" class="regular-text" value="<?php echo esc_attr(is_array($view['sales_house']) ? (string) ($view['sales_house']['sales_house_display_name'] ?? $view['sales_house']['display_name'] ?? '') : ''); ?>" />
                    </p>
                    <p>
                        <label for="encypher-adcp-sh-seat-2"><?php esc_html_e('Seat or network ID (optional)', 'encypher-provenance'); ?></label><br />
                        <input type="text" id="encypher-adcp-sh-seat-2" name="encypher_adcp_sales_house_seat" class="regular-text" value="<?php echo esc_attr(is_array($view['sales_house']) ? (string) ($view['sales_house']['declared_seat_or_network_id'] ?? '') : ''); ?>" />
                    </p>
                    <button type="submit" class="button button-secondary">
                        <?php esc_html_e('Declare sales house', 'encypher-provenance'); ?>
                    </button>
                    <?php if (is_array($view['sales_house'])) : ?>
                        <button type="submit" name="encypher_adcp_revoke_sales_house" value="1" class="button button-link-delete">
                            <?php esc_html_e('Revoke delegation', 'encypher-provenance'); ?>
                        </button>
                    <?php endif; ?>
                </form>
            </section>

            <section class="encypher-connect-card" aria-labelledby="encypher-adcp-withdraw-title">
                <h2 id="encypher-adcp-withdraw-title"><?php esc_html_e('Withdraw', 'encypher-provenance'); ?></h2>
                <p><?php esc_html_e('Withdrawal takes effect immediately and always wins. There is no grace period.', 'encypher-provenance'); ?></p>
                <form method="post" action="<?php echo esc_url($view['action_url']); ?>">
                    <?php wp_nonce_field(\EncypherProvenance\SellerEnrollment::ACTION_WITHDRAW); ?>
                    <input type="hidden" name="action" value="<?php echo esc_attr(\EncypherProvenance\SellerEnrollment::ACTION_WITHDRAW); ?>" />
                    <p>
                        <label for="encypher-adcp-withdraw-reason"><?php esc_html_e('Reason (optional)', 'encypher-provenance'); ?></label><br />
                        <input type="text" id="encypher-adcp-withdraw-reason" name="encypher_adcp_withdrawal_reason" class="regular-text" maxlength="255" />
                    </p>
                    <button type="submit" class="button button-link-delete">
                        <?php esc_html_e('Withdraw this property', 'encypher-provenance'); ?>
                    </button>
                </form>
            </section>
        <?php endif; ?>
    <?php endif; ?>
</div>
