<?php
/**
 * C2PA Provenance Report Template
 *
 * Renders a structured, human-readable verification report replacing the
 * former raw-JSON display. Consumes $data (WP_REST_Response or WP_Error)
 * from handle_provenance_request().
 *
 * Sections: Trust Verdict Banner, Signer Identity Card, Content Summary,
 * Rights & Permissions, Provenance Chain, Manifest Details (collapsed), and an
 * optional technical JSON disclosure inside it.
 */

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

require_once __DIR__ . '/../includes/class-encypher-verification-normalizer.php';

$encypher_is_error = is_wp_error($data);
$encypher_report = $encypher_is_error ? [] : ($data->get_data() ?: []);
$encypher_sections = Encypher_Verification_Normalizer::normalize($encypher_report);

$encypher_verdict = $encypher_sections['trust_verdict'];
$encypher_signer = $encypher_sections['signer_info'];
$encypher_summary = $encypher_sections['content_summary'];
$encypher_rights = $encypher_sections['rights_permissions'];
$encypher_chain = $encypher_sections['provenance_chain'];
$encypher_details = $encypher_sections['manifest_details'];
$encypher_technical_json = $encypher_sections['technical_json'];

// Discoverability metadata: only a trusted verdict is indexable and gets
// positive structured data. Every other state, and every error page, stays
// noindex and emits no structured-data claims.
$encypher_seo = Encypher_Verification_Normalizer::seo_metadata($encypher_sections, $encypher_is_error);
$encypher_canonical_url = '';
if (!empty($encypher_signer['instance_id']) && function_exists('home_url') && class_exists('\\EncypherProvenance\\Plugin')) {
    $encypher_canonical_url = home_url('/' . \EncypherProvenance\Plugin::get_verify_slug() . '/' . rawurlencode((string) $encypher_signer['instance_id']));
}

$encypher_mark_url = ENCYPHER_PROVENANCE_PLUGIN_URL . 'assets/images/brand/encypher-mark-navy.svg';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo esc_html($encypher_seo['title']); ?></title>
    <meta name="description" content="<?php echo esc_attr($encypher_seo['description']); ?>">
    <?php if ($encypher_seo['indexable']) : ?>
    <meta name="robots" content="index,follow">
    <?php if ('' !== $encypher_canonical_url) : ?><link rel="canonical" href="<?php echo esc_url($encypher_canonical_url); ?>"><?php endif; ?>
    <meta property="og:type" content="article">
    <meta property="og:title" content="<?php echo esc_attr($encypher_seo['title']); ?>">
    <meta property="og:description" content="<?php echo esc_attr($encypher_seo['description']); ?>">
    <?php if ('' !== $encypher_canonical_url) : ?><meta property="og:url" content="<?php echo esc_url($encypher_canonical_url); ?>"><?php endif; ?>
    <meta name="twitter:card" content="summary">
    <?php if (is_array($encypher_seo['jsonld'])) : ?>
    <script type="application/ld+json"><?php echo wp_json_encode($encypher_seo['jsonld']); ?></script>
    <?php endif; ?>
    <?php else : ?>
    <meta name="robots" content="noindex,follow">
    <?php endif; ?>
    <style>
        /* The report is a branded trust artifact and always renders its
         * light design: color-scheme + explicit colors prevent UA dark mode
         * from repainting text over the light verdict/json backgrounds
         * (the old partial dark theme produced unreadable light-on-light). */
        :root { color-scheme: light; }
        *, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: #f8f9fa;
            color: #1a1a1a;
            line-height: 1.6;
        }
        .container { max-width: 800px; margin: 0 auto; padding: 32px 16px; }
        .report-header {
            background: #1B2F50;
            color: white;
            padding: 24px 32px;
            border-radius: 12px 12px 0 0;
            text-align: center;
        }
        .report-header h1 { font-size: 22px; font-weight: 600; margin-bottom: 4px; }
        .report-header p { font-size: 13px; opacity: 0.85; }
        .report-card {
            background: white;
            border-radius: 0 0 12px 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            overflow: hidden;
        }
        .verdict-banner {
            padding: 20px 32px;
            display: flex;
            align-items: center;
            gap: 16px;
            border-bottom: 1px solid rgba(0,0,0,0.06);
        }
        .verdict-icon {
            width: 48px; height: 48px; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            flex-shrink: 0;
        }
        .verdict-icon .verdict-mark { width: 30px; height: 30px; display: block; }
        /* One status glyph per verdict, so the five states are distinguishable
         * without reading the banner text and without colour being the only
         * signal. The check variant is reachable only from a trusted verdict. */
        .verdict-glyph {
            position: absolute; margin: 26px 0 0 26px;
            width: 20px; height: 20px; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            font-size: 13px; font-weight: 700; line-height: 1;
            background: #fff; color: inherit;
            box-shadow: 0 0 0 1px rgba(0,0,0,0.12);
        }
        .verdict-glyph--check::before { content: "\2713"; }
        .verdict-glyph--caution::before { content: "\0021"; }
        .verdict-glyph--changed::before { content: "\2260"; }
        .verdict-glyph--unknown::before,
        .verdict-glyph[data-encypher-glyph="unknown"]::before { content: "\003F"; }
        .verdict-glyph--absent::before { content: "\2013"; }
        .verdict-glyph--record::before { content: "\00B7"; }
        .verdict-glyph--checking::before { content: "\2026"; }
        .verdict-text h2 { font-size: 20px; font-weight: 650; margin-bottom: 2px; }
        .verdict-text p { font-size: 14px; color: #374151; }
        .report-body { padding: 32px; }
        .section { margin-bottom: 28px; }
        .section:last-child { margin-bottom: 0; }
        .section-title {
            font-size: 15px; font-weight: 600; color: #1B2F50;
            padding-bottom: 8px; margin-bottom: 16px;
            border-bottom: 2px solid #B7D5ED;
            text-transform: uppercase; letter-spacing: 0.5px;
        }
        .detail-grid { display: grid; grid-template-columns: 160px 1fr; gap: 10px 16px; }
        @media (max-width: 600px) { .detail-grid { grid-template-columns: 1fr; gap: 4px; } }
        .detail-label { font-size: 13px; font-weight: 600; color: #6b7280; }
        .detail-value { font-size: 14px; color: #1a1a1a; word-break: break-word; }
        .code-value {
            background: #f3f4f6; padding: 2px 6px; border-radius: 3px;
            font-family: 'SF Mono', 'Fira Code', Consolas, monospace;
            font-size: 12px; word-break: break-all;
        }
        .permission-row {
            display: flex; align-items: center; gap: 8px;
            padding: 8px 0; border-bottom: 1px solid rgba(0,0,0,0.04);
        }
        .permission-row:last-child { border-bottom: none; }
        .permission-label { font-size: 14px; flex: 1; }
        .permission-value {
            font-size: 13px; font-weight: 600; padding: 3px 10px;
            border-radius: 12px;
        }
        .perm-prohibited { background: #fee2e2; color: #991b1b; }
        .perm-allowed { background: #dcfce7; color: #166534; }
        .perm-constrained { background: #fef3c7; color: #92400e; }
        .perm-unknown { background: #f3f4f6; color: #6b7280; }
        .chain-list { list-style: none; position: relative; padding-left: 24px; }
        .chain-item { position: relative; padding: 8px 0 8px 20px; }
        .chain-connector {
            position: absolute; left: 7px; top: 0; bottom: 0; width: 2px;
            background: #d1d5db;
        }
        .chain-item:last-child .chain-connector { display: none; }
        .chain-node {
            position: absolute; left: 0; top: 14px; width: 16px; height: 16px;
            border-radius: 50%; border: 2px solid #d1d5db; background: white;
            z-index: 1;
        }
        .chain-item.current .chain-node { border-color: #22c55e; background: #dcfce7; }
        .chain-item.ingredient .chain-node { border-color: #3b82f6; background: #dbeafe; }
        .chain-title { font-size: 14px; font-weight: 500; }
        .chain-meta { font-size: 12px; color: #6b7280; }
        .collapsible-header {
            background: #f9fafb; padding: 12px 16px; cursor: pointer;
            display: flex; align-items: center; justify-content: space-between;
            border-radius: 8px; font-size: 14px; font-weight: 500;
            user-select: none;
        }
        .collapsible-header:hover { background: #f3f4f6; }
        .collapsible-arrow { transition: transform 0.2s; font-size: 12px; }
        .collapsible-content {
            display: none; padding: 16px; margin-top: 4px;
            border: 1px solid #e5e7eb; border-radius: 8px;
        }
        .collapsible-content.open { display: block; }
        .raw-json-block {
            background: #f8f9fa; padding: 16px; border-radius: 6px;
            font-family: 'SF Mono', 'Fira Code', Consolas, monospace;
            font-size: 11px; overflow-x: auto; white-space: pre-wrap;
            word-break: break-word; max-height: 400px; overflow-y: auto;
            border: 1px solid #e5e7eb; margin-top: 12px;
        }
        .footer {
            text-align: center; margin-top: 32px; padding: 16px;
            color: #6b7280; font-size: 13px;
        }
        .footer a { color: #2563eb; text-decoration: none; }
        .footer a:hover { text-decoration: underline; }
        .deep-link {
            display: inline-block; margin-top: 16px; padding: 8px 20px;
            background: #1B2F50; color: white; border-radius: 6px;
            text-decoration: none; font-size: 13px; font-weight: 500;
        }
        .deep-link:hover { background: #2a4470; }
    </style>
</head>
<body>
    <div class="container">
        <div class="report-header">
            <h1>C2PA Provenance Report</h1>
            <p>Content Authenticity & Provenance Verification</p>
        </div>

        <div class="report-card">
            <?php if ($encypher_is_error): ?>
                <!-- Error state: no check completed, so no verdict is claimed. -->
                <div class="verdict-banner" data-encypher-verdict="unavailable" style="background: <?php echo esc_attr(Encypher_Verification_Normalizer::VERDICT_STATES['unavailable']['bg']); ?>;">
                    <div class="verdict-icon" style="background: rgba(107,114,128,0.15);"><img class="verdict-mark" src="<?php echo esc_url($encypher_mark_url); ?>" alt="" aria-hidden="true" /><span class="verdict-glyph" data-encypher-glyph="unknown" aria-hidden="true"></span></div>
                    <div class="verdict-text">
                        <h2 style="color: <?php echo esc_attr(Encypher_Verification_Normalizer::VERDICT_STATES['unavailable']['color']); ?>;">Verification unavailable</h2>
                        <p><?php echo esc_html($data->get_error_message()); ?></p>
                    </div>
                </div>
            <?php else: ?>
                <!-- Trust verdict banner: one canonical reader verdict. -->
                <div class="verdict-banner"
                     data-encypher-verdict="<?php echo esc_attr($encypher_verdict['state']); ?>"
                     data-encypher-tone="<?php echo esc_attr($encypher_verdict['tone']); ?>"
                     <?php if ($encypher_verdict['trusted']): ?>data-encypher-trusted="1"<?php endif; ?>
                     style="background: <?php echo esc_attr($encypher_verdict['bg']); ?>;">
                    <div class="verdict-icon" style="background: rgba(255,255,255,0.5);">
                        <img class="verdict-mark" src="<?php echo esc_url($encypher_mark_url); ?>" alt="" aria-hidden="true" />
                        <span class="verdict-glyph verdict-glyph--<?php echo esc_attr($encypher_verdict['glyph']); ?>" data-encypher-glyph="<?php echo esc_attr($encypher_verdict['glyph']); ?>" aria-hidden="true"></span>
                    </div>
                    <div class="verdict-text">
                        <h2 style="color: <?php echo esc_attr($encypher_verdict['color']); ?>;"><?php echo esc_html($encypher_verdict['label']); ?></h2>
                        <p><?php echo esc_html($encypher_verdict['description']); ?></p>
                    </div>
                </div>

                <div class="report-body">
                    <?php if ($encypher_signer['publisher_name'] !== null): ?>
                    <!-- Signer identity. The name's label comes from the verdict's
                         own signer trust: an unanchored certificate subject is a
                         claimed publisher, never an established one. -->
                    <div class="section">
                        <div class="section-title">Signer Identity</div>
                        <div class="detail-grid">
                            <div class="detail-label"><?php echo esc_html($encypher_signer['name_label']); ?></div>
                            <div class="detail-value"><?php echo esc_html($encypher_signer['publisher_name']); ?></div>

                            <div class="detail-label"><?php echo esc_html($encypher_signer['trust_label']); ?></div>
                            <div class="detail-value" data-encypher-signer-trust="<?php echo esc_attr($encypher_signer['signer_trust']); ?>"><?php echo esc_html($encypher_signer['trust_value']); ?></div>

                            <?php if ($encypher_signer['trust_anchor']): ?>
                            <div class="detail-label">Trust anchor</div>
                            <div class="detail-value"><?php echo esc_html($encypher_signer['trust_anchor']); ?></div>
                            <?php endif; ?>

                            <?php if ($encypher_signer['certificate_subject']): ?>
                            <div class="detail-label">Certificate</div>
                            <div class="detail-value"><span class="code-value"><?php echo esc_html($encypher_signer['certificate_subject']); ?></span></div>
                            <?php endif; ?>

                            <?php if ($encypher_signer['signed_date']): ?>
                            <div class="detail-label">Signed</div>
                            <div class="detail-value"><?php echo esc_html($encypher_signer['signed_date']); ?></div>
                            <?php endif; ?>

                            <?php if ($encypher_signer['instance_id']): ?>
                            <div class="detail-label">Instance ID</div>
                            <div class="detail-value"><span class="code-value"><?php echo esc_html($encypher_signer['instance_id']); ?></span></div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Content Summary -->
                    <?php if ($encypher_summary['title'] !== null): ?>
                    <div class="section">
                        <div class="section-title">Content Summary</div>
                        <div class="detail-grid">
                            <div class="detail-label">Title</div>
                            <div class="detail-value"><?php echo esc_html($encypher_summary['title']); ?></div>

                            <?php if ($encypher_summary['author']): ?>
                            <div class="detail-label">Author</div>
                            <div class="detail-value"><?php echo esc_html($encypher_summary['author']); ?></div>
                            <?php endif; ?>

                            <?php if ($encypher_summary['published']): ?>
                            <div class="detail-label">Published</div>
                            <div class="detail-value"><?php echo esc_html($encypher_summary['published']); ?></div>
                            <?php endif; ?>

                            <?php if ($encypher_summary['modified']): ?>
                            <div class="detail-label">Last Modified</div>
                            <div class="detail-value"><?php echo esc_html($encypher_summary['modified']); ?></div>
                            <?php endif; ?>

                            <?php if ($encypher_summary['url']): ?>
                            <div class="detail-label">URL</div>
                            <div class="detail-value"><a href="<?php echo esc_url($encypher_summary['url']); ?>" target="_blank" rel="noopener"><?php echo esc_html($encypher_summary['url']); ?></a></div>
                            <?php endif; ?>

                            <?php if ($encypher_summary['total_sentences'] > 0): ?>
                            <div class="detail-label">Sentences</div>
                            <div class="detail-value"><?php echo (int) $encypher_summary['total_sentences']; ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Rights and permissions, as the manifest recorded them.
                         Present only for a verdict whose manifest validated;
                         the normalizer omits the whole section otherwise. -->
                    <?php if ($encypher_rights['has_permissions']): ?>
                    <div class="section" data-encypher-section="rights">
                        <div class="section-title">Rights &amp; Permissions</div>
                        <?php
                        $encypher_perm_items = [
                            'AI Training' => $encypher_rights['ai_training'],
                            'AI Inference' => $encypher_rights['ai_inference'],
                            'Data Mining' => $encypher_rights['data_mining'],
                        ];
                        foreach ($encypher_perm_items as $encypher_label => $encypher_value):
                            if ($encypher_value === null) continue;
                            $encypher_css_class = 'perm-unknown';
                            if ($encypher_value === 'Prohibited') $encypher_css_class = 'perm-prohibited';
                            elseif ($encypher_value === 'Allowed') $encypher_css_class = 'perm-allowed';
                            elseif ($encypher_value === 'Constrained') $encypher_css_class = 'perm-constrained';
                        ?>
                        <div class="permission-row">
                            <span class="permission-label"><?php echo esc_html($encypher_label); ?></span>
                            <span class="permission-value <?php echo esc_attr($encypher_css_class); ?>"><?php echo esc_html($encypher_value); ?></span>
                        </div>
                        <?php endforeach; ?>

                        <?php if ($encypher_rights['license_type']): ?>
                        <div class="permission-row">
                            <span class="permission-label">License</span>
                            <span class="permission-value perm-unknown"><?php echo esc_html(ucwords(str_replace('_', ' ', $encypher_rights['license_type']))); ?></span>
                        </div>
                        <?php endif; ?>

                        <?php if ($encypher_rights['usage_terms']): ?>
                        <div class="permission-row">
                            <span class="permission-label">Usage terms</span>
                            <span class="detail-value"><?php echo esc_html($encypher_rights['usage_terms']); ?></span>
                        </div>
                        <?php endif; ?>

                        <?php if ($encypher_rights['copyright_holder']): ?>
                        <div class="permission-row">
                            <span class="permission-label">Copyright holder</span>
                            <span class="detail-value"><?php echo esc_html($encypher_rights['copyright_holder']); ?></span>
                        </div>
                        <?php endif; ?>

                        <?php if ($encypher_rights['constraint_url']): ?>
                        <div class="permission-row">
                            <span class="permission-label">Rights Info</span>
                            <span class="detail-value"><a href="<?php echo esc_url($encypher_rights['constraint_url']); ?>" target="_blank" rel="noopener"><?php echo esc_html($encypher_rights['constraint_url']); ?></a></span>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>

                    <!-- Provenance Chain -->
                    <?php if (!empty($encypher_chain)): ?>
                    <div class="section" data-encypher-section="chain">
                        <div class="section-title">Provenance Chain</div>
                        <ul class="chain-list">
                            <?php foreach ($encypher_chain as $encypher_entry): ?>
                            <li class="chain-item <?php echo esc_attr($encypher_entry['type']); ?>">
                                <div class="chain-connector"></div>
                                <div class="chain-node"></div>
                                <div>
                                    <div class="chain-title">
                                        <?php if ($encypher_entry['title']): ?>
                                            <?php echo esc_html($encypher_entry['title']); ?>
                                        <?php endif; ?>
                                    </div>
                                    <div class="chain-meta">
                                        <?php if ($encypher_entry['signer']): ?>
                                            <?php echo esc_html($encypher_entry['signer']); ?> -
                                        <?php endif; ?>
                                        <?php echo esc_html($encypher_entry['action']); ?>
                                    </div>
                                </div>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                    <?php endif; ?>

                    <!-- Manifest details: the questions a publisher asks about a
                         signed work, not a dump of internal identifiers. The raw
                         payload is a separate, closed technical disclosure. -->
                    <?php if (!empty($encypher_details)): ?>
                    <div class="section" data-encypher-section="manifest-details">
                        <div class="collapsible-header" onclick="this.nextElementSibling.classList.toggle('open'); this.querySelector('.collapsible-arrow').style.transform = this.nextElementSibling.classList.contains('open') ? 'rotate(90deg)' : '';">
                            <span>Manifest Details</span>
                            <span class="collapsible-arrow">&#9654;</span>
                        </div>
                        <div class="collapsible-content">
                            <div class="detail-grid">
                                <?php foreach ($encypher_details as $encypher_label => $encypher_value): ?>
                                <div class="detail-label"><?php echo esc_html($encypher_label); ?></div>
                                <div class="detail-value"><?php echo esc_html($encypher_value); ?></div>
                                <?php endforeach; ?>
                            </div>

                            <?php if ($encypher_technical_json): ?>
                            <div class="collapsible-header" style="margin-top: 12px;" onclick="this.nextElementSibling.classList.toggle('open'); this.querySelector('.collapsible-arrow').style.transform = this.nextElementSibling.classList.contains('open') ? 'rotate(90deg)' : '';">
                                <span>Technical data (JSON)</span>
                                <span class="collapsible-arrow">&#9654;</span>
                            </div>
                            <div class="collapsible-content" data-encypher-section="technical-json">
                                <pre class="raw-json-block"><?php echo esc_html($encypher_technical_json); ?></pre>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- View Full Report link -->
                    <div style="text-align: center; margin-top: 24px;">
                        <a href="https://encypher.com/tools/verify" target="_blank" rel="noopener" class="deep-link">View Full Report on Encypher</a>
                        <p style="font-size: 12px; color: #6b7280; margin-top: 8px;">
                            Deep-inspection tools: ProvenanceTree canvas, developer mode, and re-verification
                        </p>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <div class="footer">
            <p>Powered by <a href="https://encypher.com" target="_blank" rel="noopener">Encypher</a></p>
            <p style="margin-top: 8px; font-size: 11px;">Content authenticity verified using C2PA standards.</p>
        </div>
    </div>
</body>
</html>
