<?php
/**
 * AuctionForge Legal Agreements — Admin Page
 * Provides a rich editor interface for managing Terms & Conditions,
 * Refund & Return Policy, and Chargeback Waiver documents.
 * Includes a Consent Log tab showing which users agreed to which versions.
 *
 * @since 3.6.0.0
 */

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

$agreements = AF_Legal_Agreements::get_all_agreements();
$types = array(
    AF_Legal_Agreements::TYPE_TERMS      => array(
        'label'       => __('Terms & Conditions', 'auctionforge'),
        'description' => __('This document is always displayed during auction approval. Bidders must scroll through it and check the agreement box.', 'auctionforge'),
        'always_on'   => true,
    ),
    AF_Legal_Agreements::TYPE_REFUND     => array(
        'label'       => __('Refund & Return Policy', 'auctionforge'),
        'description' => __('Enable this in Settings to require bidders to read and accept the refund policy during auction approval.', 'auctionforge'),
        'always_on'   => false,
        'enabled'     => AF_Legal_Agreements::is_enabled(AF_Legal_Agreements::TYPE_REFUND),
    ),
    AF_Legal_Agreements::TYPE_CHARGEBACK => array(
        'label'       => __('Chargeback Waiver', 'auctionforge'),
        'description' => __('Enable this in Settings to require bidders to read and accept the chargeback waiver during auction approval.', 'auctionforge'),
        'always_on'   => false,
        'enabled'     => AF_Legal_Agreements::is_enabled(AF_Legal_Agreements::TYPE_CHARGEBACK),
    ),
);

// Handle save
$saved = false;
$saved_versions = array();
if (isset($_POST['af_legal_save']) && wp_verify_nonce($_POST['af_legal_nonce'], 'af_legal_save_agreements')) {
    foreach ($types as $type => $meta) {
        if (isset($_POST['af_legal_content_' . $type])) {
            $content = wp_kses_post($_POST['af_legal_content_' . $type]);
            $new_version = AF_Legal_Agreements::save_agreement($type, $content);
            $saved_versions[$type] = $new_version;
        }
    }
    $saved = true;
    // Refresh data
    $agreements = AF_Legal_Agreements::get_all_agreements();
}

// Consent log tab data
$active_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : '';
$log_search_email = isset($_GET['log_email']) ? sanitize_text_field($_GET['log_email']) : '';
$log_filter_type  = isset($_GET['log_type']) ? sanitize_text_field($_GET['log_type']) : '';
$log_filter_auction = isset($_GET['log_auction']) ? sanitize_text_field($_GET['log_auction']) : '';
$log_page = isset($_GET['log_page']) ? max(1, intval($_GET['log_page'])) : 1;
$log_per_page = 30;

$log_data = null;
if ($active_tab === 'consent_log') {
    $log_filters = array();
    if (!empty($log_search_email)) $log_filters['user_email'] = $log_search_email;
    if (!empty($log_filter_type))  $log_filters['agreement_type'] = $log_filter_type;
    if (!empty($log_filter_auction)) $log_filters['auction_id'] = $log_filter_auction;
    $log_data = AF_Legal_Agreements::get_agreement_logs($log_filters, $log_per_page, $log_page);
}
?>
<div class="wrap">
    <h1><?= esc_html__('Legal Agreements', 'auctionforge') ?></h1>
    <p class="description" style="margin-bottom: 20px;">
        <?= esc_html__('Manage the legal documents that bidders must accept during the auction approval process. Changes to content will automatically increment the version number.', 'auctionforge') ?>
    </p>

    <?php if ($saved): ?>
        <div class="notice notice-success is-dismissible">
            <p><strong><?= esc_html__('Agreements saved successfully.', 'auctionforge') ?></strong>
            <?php foreach ($saved_versions as $type => $ver): ?>
                <?= esc_html($types[$type]['label']) ?>: v<?= $ver ?>
                <?php if ($ver > 1): ?><em>(<?= esc_html__('version bumped', 'auctionforge') ?>)</em><?php endif; ?>
                &nbsp;&bull;&nbsp;
            <?php endforeach; ?>
            </p>
        </div>
    <?php endif; ?>

    <div id="af-legal-tabs">
        <nav class="nav-tab-wrapper" style="margin-bottom: 0;">
            <?php foreach ($types as $type => $meta): ?>
                <a href="#af-tab-<?= esc_attr($type) ?>"
                   class="nav-tab <?= ($active_tab !== 'consent_log' && !isset($first_done)) ? 'nav-tab-active' : '' ?>"
                   data-tab="<?= esc_attr($type) ?>">
                    <?= esc_html($meta['label']) ?>
                    <?php if (isset($agreements[$type])): ?>
                        <span class="af-version-badge">v<?= intval($agreements[$type]->version) ?></span>
                    <?php endif; ?>
                    <?php if (!$meta['always_on'] && empty($meta['enabled'])): ?>
                        <span class="af-disabled-badge"><?= esc_html__('Disabled', 'auctionforge') ?></span>
                    <?php endif; ?>
                </a>
            <?php $first_done = true; endforeach; ?>
            <a href="#af-tab-consent_log"
               class="nav-tab <?= $active_tab === 'consent_log' ? 'nav-tab-active' : '' ?>"
               data-tab="consent_log">
                <?= esc_html__('Consent Log', 'auctionforge') ?>
                <span class="dashicons dashicons-list-view" style="font-size: 16px; width: 16px; height: 16px; vertical-align: middle; margin-left: 2px;"></span>
            </a>
        </nav>

        <!-- Agreement Editor Tabs -->
        <form method="post" action="">
        <?php wp_nonce_field('af_legal_save_agreements', 'af_legal_nonce'); ?>

        <?php $first = true; foreach ($types as $type => $meta): ?>
            <div id="af-tab-<?= esc_attr($type) ?>"
                 class="af-tab-content"
                 style="<?= ($active_tab !== 'consent_log' && $first) ? '' : 'display:none;' ?>
                        background: #fff;
                        border: 1px solid #c3c4c7;
                        border-top: none;
                        padding: 20px;">

                <div style="margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center;">
                    <div>
                        <p class="description" style="margin: 0;"><?= esc_html($meta['description']) ?></p>
                    </div>
                    <div style="text-align: right; min-width: 200px;">
                        <?php if (isset($agreements[$type])): ?>
                            <span style="font-size: 13px; color: #50575e;">
                                <strong><?= esc_html__('Version:', 'auctionforge') ?></strong> <?= intval($agreements[$type]->version) ?>
                                &nbsp;|&nbsp;
                                <strong><?= esc_html__('Updated:', 'auctionforge') ?></strong> <?= esc_html($agreements[$type]->updated_at) ?>
                            </span>
                        <?php else: ?>
                            <span style="font-size: 13px; color: #999;"><?= esc_html__('Not yet saved', 'auctionforge') ?></span>
                        <?php endif; ?>
                    </div>
                </div>

                <?php if (!$meta['always_on'] && empty($meta['enabled'])): ?>
                    <div class="notice notice-warning inline" style="margin: 0 0 15px 0;">
                        <p>
                            <?= sprintf(
                                esc_html__('This agreement is currently disabled. Enable it in %sSettings%s to require it during auction approval.', 'auctionforge'),
                                '<a href="' . admin_url('edit.php?post_type=lot&page=bidspirit_options') . '">',
                                '</a>'
                            ) ?>
                        </p>
                    </div>
                <?php endif; ?>

                <?php
                $content = isset($agreements[$type]) ? $agreements[$type]->content : '';
                $editor_id = 'af_legal_content_' . $type;
                wp_editor($content, $editor_id, array(
                    'textarea_name' => $editor_id,
                    'textarea_rows' => 18,
                    'media_buttons' => false,
                    'teeny'         => false,
                    'wpautop'       => true,
                    'tinymce'       => array(
                        'toolbar1' => 'formatselect,bold,italic,underline,strikethrough,bullist,numlist,blockquote,hr,link,unlink,undo,redo',
                        'toolbar2' => '',
                    ),
                ));
                ?>

                <?php
                // Version history
                $history = AF_Legal_Agreements::get_version_history($type, 10);
                if (!empty($history)):
                ?>
                    <div style="margin-top: 20px;">
                        <h4 style="margin-bottom: 8px;"><?= esc_html__('Version History', 'auctionforge') ?></h4>
                        <table class="widefat striped" style="max-width: 600px;">
                            <thead>
                                <tr>
                                    <th><?= esc_html__('Version', 'auctionforge') ?></th>
                                    <th><?= esc_html__('Date', 'auctionforge') ?></th>
                                    <th><?= esc_html__('Updated By', 'auctionforge') ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($history as $v): ?>
                                    <tr>
                                        <td>v<?= intval($v->version) ?></td>
                                        <td><?= esc_html($v->created_at) ?></td>
                                        <td>
                                            <?php
                                            $user = get_user_by('id', $v->created_by);
                                            echo $user ? esc_html($user->display_name) : '#' . intval($v->created_by);
                                            ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        <?php $first = false; endforeach; ?>

        <p class="submit" style="margin-top: 20px;" id="af-save-btn" <?= $active_tab === 'consent_log' ? 'style="display:none;"' : '' ?>>
            <input type="submit" name="af_legal_save" class="button button-primary button-large"
                   value="<?= esc_attr__('Save All Agreements', 'auctionforge') ?>">
        </p>
        </form>

        <!-- Consent Log Tab -->
        <div id="af-tab-consent_log"
             class="af-tab-content"
             style="<?= $active_tab === 'consent_log' ? '' : 'display:none;' ?>
                    background: #fff;
                    border: 1px solid #c3c4c7;
                    border-top: none;
                    padding: 20px;">

            <p class="description" style="margin: 0 0 15px 0;">
                <?= esc_html__('View which users agreed to which document versions during auction approval requests.', 'auctionforge') ?>
            </p>

            <!-- Filter Form -->
            <?php
            $base_url = admin_url('edit.php?post_type=lot&page=auctionforge-legal-agreements&tab=consent_log');
            ?>
            <form method="get" action="<?= admin_url('edit.php') ?>" style="margin-bottom: 16px;">
                <input type="hidden" name="post_type" value="lot">
                <input type="hidden" name="page" value="auctionforge-legal-agreements">
                <input type="hidden" name="tab" value="consent_log">

                <div style="display: flex; gap: 10px; align-items: flex-end; flex-wrap: wrap;">
                    <div>
                        <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">
                            <?= esc_html__('Email', 'auctionforge') ?>
                        </label>
                        <input type="text" name="log_email" value="<?= esc_attr($log_search_email) ?>"
                               placeholder="<?= esc_attr__('Search by email...', 'auctionforge') ?>"
                               style="width: 260px;">
                    </div>
                    <div>
                        <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">
                            <?= esc_html__('Document Type', 'auctionforge') ?>
                        </label>
                        <select name="log_type" style="min-width: 180px;">
                            <option value=""><?= esc_html__('All Types', 'auctionforge') ?></option>
                            <option value="terms_conditions" <?= selected($log_filter_type, 'terms_conditions', false) ?>>
                                <?= esc_html__('Terms & Conditions', 'auctionforge') ?>
                            </option>
                            <option value="refund_policy" <?= selected($log_filter_type, 'refund_policy', false) ?>>
                                <?= esc_html__('Refund & Return Policy', 'auctionforge') ?>
                            </option>
                            <option value="chargeback_waiver" <?= selected($log_filter_type, 'chargeback_waiver', false) ?>>
                                <?= esc_html__('Chargeback Waiver', 'auctionforge') ?>
                            </option>
                        </select>
                    </div>
                    <div>
                        <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">
                            <?= esc_html__('Auction ID', 'auctionforge') ?>
                        </label>
                        <input type="text" name="log_auction" value="<?= esc_attr($log_filter_auction) ?>"
                               placeholder="<?= esc_attr__('Auction ID...', 'auctionforge') ?>"
                               style="width: 160px;">
                    </div>
                    <div>
                        <button type="submit" class="button button-primary">
                            <?= esc_html__('Filter', 'auctionforge') ?>
                        </button>
                        <?php if (!empty($log_search_email) || !empty($log_filter_type) || !empty($log_filter_auction)): ?>
                            <a href="<?= esc_url($base_url) ?>" class="button"><?= esc_html__('Clear', 'auctionforge') ?></a>
                        <?php endif; ?>
                    </div>
                </div>
            </form>

            <?php if ($log_data !== null): ?>
                <!-- Results Summary -->
                <div style="margin-bottom: 10px; font-size: 13px; color: #50575e;">
                    <?= sprintf(
                        esc_html__('Showing %d of %d records (page %d of %d)', 'auctionforge'),
                        count($log_data['results']),
                        $log_data['total'],
                        $log_data['page'],
                        max(1, $log_data['pages'])
                    ) ?>
                </div>

                <?php if (empty($log_data['results'])): ?>
                    <div class="notice notice-info inline" style="margin: 0;">
                        <p><?= esc_html__('No consent records found matching your filters.', 'auctionforge') ?></p>
                    </div>
                <?php else: ?>
                    <table class="widefat striped" style="margin-bottom: 16px;">
                        <thead>
                            <tr>
                                <th style="width: 50px;">#</th>
                                <th><?= esc_html__('User Email', 'auctionforge') ?></th>
                                <th><?= esc_html__('Document', 'auctionforge') ?></th>
                                <th style="width: 80px; text-align: center;"><?= esc_html__('Version', 'auctionforge') ?></th>
                                <th><?= esc_html__('Auction ID', 'auctionforge') ?></th>
                                <th><?= esc_html__('IP Address', 'auctionforge') ?></th>
                                <th><?= esc_html__('Date', 'auctionforge') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($log_data['results'] as $row): ?>
                                <?php
                                $type_label = AF_Legal_Agreements::get_type_label($row['agreement_type']);
                                $current_agreement = isset($agreements[$row['agreement_type']]) ? $agreements[$row['agreement_type']] : null;
                                $is_outdated = $current_agreement && intval($row['version_agreed']) < intval($current_agreement->version);
                                ?>
                                <tr>
                                    <td style="color: #999;"><?= intval($row['id']) ?></td>
                                    <td>
                                        <strong><?= esc_html($row['user_email']) ?></strong>
                                    </td>
                                    <td>
                                        <span class="af-log-type-badge af-log-type-<?= esc_attr($row['agreement_type']) ?>">
                                            <?= esc_html($type_label) ?>
                                        </span>
                                    </td>
                                    <td style="text-align: center;">
                                        <a href="#" class="af-view-version-link"
                                           data-type="<?= esc_attr($row['agreement_type']) ?>"
                                           data-version="<?= intval($row['version_agreed']) ?>"
                                           data-email="<?= esc_attr($row['user_email']) ?>"
                                           data-ip="<?= esc_attr($row['ip_address']) ?>"
                                           data-agreed-date="<?= esc_attr($row['created_at']) ?>"
                                           data-auction="<?= esc_attr($row['auction_id']) ?>"
                                           title="<?= esc_attr__('Click to view this document version', 'auctionforge') ?>">
                                            <span class="af-log-version <?= $is_outdated ? 'af-log-version-outdated' : 'af-log-version-current' ?>">
                                                v<?= intval($row['version_agreed']) ?>
                                            </span>
                                        </a>
                                        <?php if ($is_outdated): ?>
                                            <span class="af-log-outdated-note"
                                                  title="<?= esc_attr(sprintf(__('Current version is v%d', 'auctionforge'), intval($current_agreement->version))) ?>">
                                                ⓘ
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= esc_html($row['auction_id']) ?></td>
                                    <td><code style="font-size: 12px;"><?= esc_html($row['ip_address']) ?></code></td>
                                    <td><?= esc_html($row['created_at']) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>

                    <!-- Pagination -->
                    <?php if ($log_data['pages'] > 1): ?>
                        <div style="display: flex; gap: 6px; align-items: center;">
                            <?php
                            $pagination_base = add_query_arg(array(
                                'post_type'   => 'lot',
                                'page'        => 'auctionforge-legal-agreements',
                                'tab'         => 'consent_log',
                                'log_email'   => $log_search_email,
                                'log_type'    => $log_filter_type,
                                'log_auction' => $log_filter_auction,
                            ), admin_url('edit.php'));

                            if ($log_page > 1): ?>
                                <a href="<?= esc_url(add_query_arg('log_page', $log_page - 1, $pagination_base)) ?>"
                                   class="button">&laquo; <?= esc_html__('Previous', 'auctionforge') ?></a>
                            <?php endif; ?>

                            <span style="font-size: 13px; color: #50575e; padding: 0 8px;">
                                <?= sprintf(esc_html__('Page %d of %d', 'auctionforge'), $log_page, $log_data['pages']) ?>
                            </span>

                            <?php if ($log_page < $log_data['pages']): ?>
                                <a href="<?= esc_url(add_query_arg('log_page', $log_page + 1, $pagination_base)) ?>"
                                   class="button"><?= esc_html__('Next', 'auctionforge') ?> &raquo;</a>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>

            <?php else: ?>
                <div class="notice notice-info inline" style="margin: 0;">
                    <p><?= esc_html__('Use the filters above and click "Filter" to search consent records.', 'auctionforge') ?></p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Printable Document Modal -->
<div id="af-doc-modal-overlay" style="display:none;">
    <div id="af-doc-modal">
        <div id="af-doc-modal-header">
            <div>
                <h2 id="af-doc-modal-title"></h2>
                <p id="af-doc-modal-meta" style="margin: 4px 0 0; font-size: 13px; color: #666;"></p>
            </div>
            <div style="display: flex; gap: 8px; align-items: center;">
                <button type="button" id="af-doc-print-btn" class="button button-primary">
                    <span class="dashicons dashicons-printer" style="vertical-align: middle; margin-right: 4px;"></span>
                    <?= esc_html__('Print', 'auctionforge') ?>
                </button>
                <button type="button" id="af-doc-close-btn" class="button">
                    <?= esc_html__('Close', 'auctionforge') ?>
                </button>
            </div>
        </div>
        <div id="af-doc-modal-body">
            <!-- Consent Record Details (prints with document) -->
            <div id="af-doc-consent-info" style="display:none;">
                <table>
                    <tbody>
                        <tr>
                            <td><strong><?= esc_html__('Name:', 'auctionforge') ?></strong></td>
                            <td id="af-doc-ci-name"></td>
                            <td><strong><?= esc_html__('Email:', 'auctionforge') ?></strong></td>
                            <td id="af-doc-ci-email"></td>
                        </tr>
                        <tr>
                            <td><strong><?= esc_html__('IP Address:', 'auctionforge') ?></strong></td>
                            <td id="af-doc-ci-ip"></td>
                            <td><strong><?= esc_html__('Agreed On:', 'auctionforge') ?></strong></td>
                            <td id="af-doc-ci-date"></td>
                        </tr>
                        <tr>
                            <td><strong><?= esc_html__('Auction ID:', 'auctionforge') ?></strong></td>
                            <td id="af-doc-ci-auction"></td>
                            <td><strong><?= esc_html__('Document Version:', 'auctionforge') ?></strong></td>
                            <td id="af-doc-ci-version"></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div id="af-doc-modal-loading" style="text-align: center; padding: 40px; color: #999;">
                <?= esc_html__('Loading document...', 'auctionforge') ?>
            </div>
            <div id="af-doc-modal-content"></div>
        </div>
    </div>
</div>

<style>
.af-version-badge {
    display: inline-block;
    background: #2271b1;
    color: #fff;
    font-size: 11px;
    padding: 1px 6px;
    border-radius: 3px;
    margin-left: 4px;
    vertical-align: middle;
    line-height: 1.4;
}
.af-disabled-badge {
    display: inline-block;
    background: #d63638;
    color: #fff;
    font-size: 11px;
    padding: 1px 6px;
    border-radius: 3px;
    margin-left: 4px;
    vertical-align: middle;
    line-height: 1.4;
}
.nav-tab-active .af-version-badge {
    background: #135e96;
}

/* Consent Log Styles */
.af-log-type-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 3px;
    font-size: 12px;
    font-weight: 500;
    line-height: 1.5;
}
.af-log-type-terms_conditions {
    background: #e7f3ff;
    color: #135e96;
}
.af-log-type-refund_policy {
    background: #fcf0e3;
    color: #8a6200;
}
.af-log-type-chargeback_waiver {
    background: #fce4e4;
    color: #a01010;
}
.af-log-version {
    display: inline-block;
    padding: 1px 6px;
    border-radius: 3px;
    font-size: 12px;
    font-weight: 600;
}
.af-log-version-current {
    background: #e6f5e6;
    color: #1a7a1a;
}
.af-log-version-outdated {
    background: #fff3cd;
    color: #856404;
}
.af-log-outdated-note {
    cursor: help;
    font-size: 14px;
    color: #856404;
    vertical-align: middle;
}

/* Consent Info Block */
#af-doc-consent-info {
    background: #f0f6fc;
    border: 1px solid #c3d9ed;
    border-radius: 4px;
    padding: 14px 18px;
    margin-bottom: 20px;
    font-size: 13px;
}
#af-doc-consent-info table {
    width: 100%;
    border-collapse: collapse;
}
#af-doc-consent-info td {
    padding: 3px 12px 3px 0;
    vertical-align: top;
    white-space: nowrap;
}
#af-doc-consent-info td:nth-child(2),
#af-doc-consent-info td:nth-child(4) {
    font-weight: normal;
    color: #1d2327;
    white-space: normal;
}
#af-doc-consent-info td strong {
    color: #50575e;
}
a.af-view-version-link {
    text-decoration: none;
    cursor: pointer;
}
a.af-view-version-link:hover .af-log-version {
    outline: 2px solid #2271b1;
    outline-offset: 1px;
}

/* Document Modal */
#af-doc-modal-overlay {
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.6);
    z-index: 100100;
    display: flex;
    align-items: center;
    justify-content: center;
}
#af-doc-modal {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 8px 40px rgba(0,0,0,0.3);
    width: 90%;
    max-width: 800px;
    max-height: 85vh;
    display: flex;
    flex-direction: column;
}
#af-doc-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid #e0e0e0;
    flex-shrink: 0;
}
#af-doc-modal-header h2 {
    margin: 0;
    font-size: 18px;
    line-height: 1.3;
}
#af-doc-modal-body {
    overflow-y: auto;
    padding: 24px;
    flex: 1;
}
#af-doc-modal-content {
    line-height: 1.7;
    font-size: 14px;
    color: #1d2327;
}
#af-doc-modal-content h3 { font-size: 18px; margin: 16px 0 8px; }
#af-doc-modal-content h4 { font-size: 15px; margin: 14px 0 6px; }
#af-doc-modal-content p { margin: 0 0 12px; }
#af-doc-modal-content ul, #af-doc-modal-content ol { margin: 0 0 12px 20px; }

@media print {
    body * { visibility: hidden !important; }
    #af-doc-modal-overlay,
    #af-doc-modal,
    #af-doc-modal * {
        visibility: visible !important;
    }
    #af-doc-modal-overlay {
        position: static !important;
        background: none !important;
    }
    #af-doc-modal {
        position: static !important;
        box-shadow: none !important;
        width: 100% !important;
        max-width: none !important;
        max-height: none !important;
        border-radius: 0 !important;
    }
    #af-doc-modal-header {
        border-bottom: 2px solid #000 !important;
    }
    #af-doc-modal-header button {
        display: none !important;
    }
    #af-doc-modal-body {
        overflow: visible !important;
    }
    #af-doc-consent-info {
        background: #f5f5f5 !important;
        border: 1px solid #999 !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
}
</style>

<script>
(function($) {
    var tabs = document.querySelectorAll('#af-legal-tabs .nav-tab');
    var saveBtn = document.getElementById('af-save-btn');

    // Tab switching
    tabs.forEach(function(tab) {
        tab.addEventListener('click', function(e) {
            e.preventDefault();
            tabs.forEach(function(t) { t.classList.remove('nav-tab-active'); });
            tab.classList.add('nav-tab-active');
            document.querySelectorAll('.af-tab-content').forEach(function(c) { c.style.display = 'none'; });
            var tabKey = tab.getAttribute('data-tab');
            var target = document.getElementById('af-tab-' + tabKey);
            if (target) target.style.display = 'block';

            if (saveBtn) {
                saveBtn.style.display = (tabKey === 'consent_log') ? 'none' : '';
            }

            if (tabKey === 'consent_log') {
                var url = new URL(window.location);
                url.searchParams.set('tab', 'consent_log');
                window.history.replaceState({}, '', url);
            } else {
                var url = new URL(window.location);
                url.searchParams.delete('tab');
                url.searchParams.delete('log_email');
                url.searchParams.delete('log_type');
                url.searchParams.delete('log_auction');
                url.searchParams.delete('log_page');
                window.history.replaceState({}, '', url);
            }
        });
    });

    // Document version modal
    var $overlay = $('#af-doc-modal-overlay');
    var $title   = $('#af-doc-modal-title');
    var $meta    = $('#af-doc-modal-meta');
    var $content = $('#af-doc-modal-content');
    var $loading = $('#af-doc-modal-loading');

    var $consentInfo = $('#af-doc-consent-info');

    function openDocModal(type, version, consent) {
        $content.empty();
        $loading.show();
        $title.text('Loading...');
        $meta.text('');
        $consentInfo.hide();
        $overlay.css('display', 'flex');

        // Populate consent info block
        if (consent && consent.email) {
            // Try to find the user's name from the table row
            var userName = '';
            // Look up WP user by email via existing row data
            $('#af-doc-ci-name').text(consent.name || '—');
            $('#af-doc-ci-email').text(consent.email);
            $('#af-doc-ci-ip').text(consent.ip || '—');
            $('#af-doc-ci-date').text(consent.agreedDate || '—');
            $('#af-doc-ci-auction').text(consent.auction || '—');
            $('#af-doc-ci-version').text('v' + consent.version);
            $consentInfo.show();
        }

        $.post(ajaxurl, {
            action: 'auctionforge_get_version_content',
            nonce: '<?= wp_create_nonce('auctionforge_admin') ?>',
            agreement_type: type,
            version: version,
            user_email: (consent && consent.email) ? consent.email : ''
        }, function(response) {
            $loading.hide();
            if (response.success && response.data) {
                var d = response.data;
                $title.text(d.label + ' — v' + d.version);
                $meta.text(d.date ? '<?= esc_js(__('Last updated:', 'auctionforge')) ?> ' + d.date : '');
                $content.html(d.content);
                // Fill name from server if returned
                if (d.user_name) {
                    $('#af-doc-ci-name').text(d.user_name);
                }
            } else {
                $content.html('<p style="color:#d63638;"><?= esc_js(__('This document version could not be found. It may have been created before version tracking was enabled.', 'auctionforge')) ?></p>');
                $title.text('<?= esc_js(__('Document Not Found', 'auctionforge')) ?>');
            }
        }).fail(function() {
            $loading.hide();
            $content.html('<p style="color:#d63638;"><?= esc_js(__('Failed to load document. Please try again.', 'auctionforge')) ?></p>');
            $title.text('<?= esc_js(__('Error', 'auctionforge')) ?>');
        });
    }

    // Click handler for version links
    $(document).on('click', '.af-view-version-link', function(e) {
        e.preventDefault();
        var $link = $(this);
        var consentInfo = {
            email:     $link.data('email') || '',
            ip:        $link.data('ip') || '',
            agreedDate: $link.data('agreed-date') || '',
            auction:   $link.data('auction') || '',
            version:   $link.data('version')
        };
        openDocModal($link.data('type'), $link.data('version'), consentInfo);
    });

    // Close modal
    $('#af-doc-close-btn').on('click', function() {
        $overlay.hide();
    });
    $overlay.on('click', function(e) {
        if (e.target === this) $overlay.hide();
    });
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && $overlay.is(':visible')) $overlay.hide();
    });

    // Print
    $('#af-doc-print-btn').on('click', function() {
        window.print();
    });

})(jQuery);
</script>
