<?php
if (!defined('ABSPATH')) exit;

// AJAX: Mint a fresh nonce for the statement save.
//
// WP nonces expire (12-24h) and are bound to the session token. The common
// failure (see GlitchTip statement_save_failed: bad_nonce) is a caching plugin
// serving the admin page — and its inlined nonce — stale, so the printed nonce
// is already dead by the time the user clicks "Publish as Page", and reloading
// the (still-cached) page doesn't help. admin-ajax.php is never page-cached, so
// it can always hand back a valid nonce; the client calls this and retries the
// save once. Gated by login (wp_ajax_) + manage_options and read-only, so it
// needs no nonce of its own (same-origin policy keeps the response unreadable to
// a cross-site attacker — the standard WP nonce-refresh pattern).
add_action('wp_ajax_webability_acwg_refresh_nonce', function () {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['msg' => 'forbidden'], 403);
    }
    wp_send_json_success(['nonce' => wp_create_nonce('webability_acwg_verify_nonce')]);
});

// AJAX: Save statement as a WordPress page
add_action('wp_ajax_webability_acwg_save_statement', function () {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['msg' => 'forbidden'], 403);
    }
    if (!check_ajax_referer('webability_acwg_verify_nonce', 'nonce', false)) {
        if (function_exists('webability_acwg_report')) {
            webability_acwg_report('statement_save_failed: bad_nonce', 'warning', ['reason' => 'bad_nonce']);
        }
        wp_send_json_error(['msg' => 'Your session expired. Please reload this page and try again.', 'code' => 'bad_nonce'], 403);
    }

    $statement = isset($_POST['statement']) ? wp_kses_post(wp_unslash($_POST['statement'])) : '';
    if (empty($statement)) {
        wp_send_json_error(['msg' => 'Empty statement']);
    }

    // Save to option for preview persistence
    update_option('webability_acwg_statement', $statement);

    // Check if we already have a statement page (treat a trashed page as missing
    // so we create a fresh one instead of failing to update a deleted post).
    $page_id = get_option('webability_acwg_statement_page_id', 0);
    $page_status = $page_id ? get_post_status($page_id) : false;
    $page_exists = $page_status && $page_status !== 'trash';

    $page_data = [
        'post_title'   => 'Accessibility Statement',
        'post_content' => $statement,
        'post_status'  => 'publish',
        'post_type'    => 'page',
        'post_author'  => get_current_user_id(),
    ];

    if ($page_exists) {
        $page_data['ID'] = $page_id;
        $result = wp_update_post($page_data, true);
    } else {
        $result = wp_insert_post($page_data, true);
        if (!is_wp_error($result)) {
            update_option('webability_acwg_statement_page_id', $result);
        }
    }

    if (is_wp_error($result)) {
        if (function_exists('webability_acwg_report')) {
            webability_acwg_report('statement_save_failed: wp_error', 'error', [
                'reason'     => 'wp_insert_or_update_post',
                'wp_error'   => $result->get_error_code(),
                'error_msg'  => $result->get_error_message(),
                'was_update' => $page_exists,
            ]);
        }
        wp_send_json_error(['msg' => $result->get_error_message()]);
    }

    wp_send_json_success(['url' => get_permalink($result), 'page_id' => $result]);
});

function webability_acwg_render_statement_page() {
    $statement = get_option('webability_acwg_statement', '');
    $industries = [
        'E-commerce', 'Healthcare', 'Education', 'Financial Services',
        'Technology', 'Government', 'Non-profit', 'Real Estate',
        'Travel & Hospitality', 'Media & Entertainment', 'Professional Services', 'Other',
    ];
    ?>
    <div id="webability-statement" class="wa-statement-wrap">
        <div class="wa-design-grid">
            <!-- Left: Form -->
            <div class="wa-design-settings">
                <!-- Company Information -->
                <div class="wa-design-card">
                    <h3 class="wa-design-card-title">Company Information</h3>

                    <div class="wa-form-group">
                        <label for="wa-stmt-company" class="wa-label">Company Name <span class="wa-required">*</span></label>
                        <input type="text" id="wa-stmt-company" class="wa-input" value="<?php echo esc_attr(get_bloginfo('name')); ?>" placeholder="Your Company Name" required>
                    </div>
                    <div class="wa-form-group">
                        <label for="wa-stmt-url" class="wa-label">Website URL <span class="wa-required">*</span></label>
                        <input type="url" id="wa-stmt-url" class="wa-input" value="<?php echo esc_attr(home_url('/')); ?>" required>
                    </div>
                    <div class="wa-form-group">
                        <label for="wa-stmt-email" class="wa-label">Contact Email <span class="wa-required">*</span></label>
                        <input type="email" id="wa-stmt-email" class="wa-input" value="<?php echo esc_attr(get_option('admin_email')); ?>" required>
                    </div>
                    <div class="wa-form-group">
                        <label for="wa-stmt-industry" class="wa-label">Industry <span class="wa-required">*</span></label>
                        <select id="wa-stmt-industry" class="wa-select">
                            <option value="">Select Industry</option>
                            <?php foreach ($industries as $ind): ?>
                            <option value="<?php echo esc_attr($ind); ?>"><?php echo esc_html($ind); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <!-- Optional Information -->
                <div class="wa-design-card">
                    <h3 class="wa-design-card-title wa-toggle-optional" id="wa-toggle-optional">
                        Optional Information
                        <span class="wa-toggle-arrow" id="wa-toggle-arrow">&#9660;</span>
                    </h3>
                    <div class="wa-optional-fields" id="wa-optional-fields" style="display:none;">
                        <div class="wa-form-group">
                            <label for="wa-stmt-brand-name" class="wa-label">Widget Brand Name</label>
                            <input type="text" id="wa-stmt-brand-name" class="wa-input" placeholder="Your Brand Name">
                        </div>
                        <div class="wa-form-group">
                            <label for="wa-stmt-brand-url" class="wa-label">Widget Brand URL</label>
                            <input type="url" id="wa-stmt-brand-url" class="wa-input" placeholder="https://yourbrand.com">
                        </div>
                        <div class="wa-form-group">
                            <label for="wa-stmt-phone" class="wa-label">Phone Number</label>
                            <input type="tel" id="wa-stmt-phone" class="wa-input" placeholder="+1 (555) 000-0000">
                        </div>
                        <div class="wa-form-group">
                            <label for="wa-stmt-form-url" class="wa-label">Online Feedback Form URL</label>
                            <input type="url" id="wa-stmt-form-url" class="wa-input" placeholder="https://yoursite.com/contact">
                        </div>
                        <div class="wa-form-group">
                            <label for="wa-stmt-visitor-address" class="wa-label">Visitor Address</label>
                            <input type="text" id="wa-stmt-visitor-address" class="wa-input" placeholder="123 Main St, City, State">
                        </div>
                        <div class="wa-form-group">
                            <label for="wa-stmt-postal-address" class="wa-label">Postal Address</label>
                            <input type="text" id="wa-stmt-postal-address" class="wa-input" placeholder="PO Box 123, City, State">
                        </div>
                    </div>
                </div>

                <!-- Enhancements removed — these were generic boilerplate, not real product features -->

                <button type="button" id="wa-generate-stmt" class="button button-primary wa-btn-generate">Generate Statement</button>
                <p class="wa-stmt-lang-note">Need a different language? Generate translated statements in 35+ languages from the <a href="https://app.webability.io/statement-generator" target="_blank" rel="noopener">WebAbility Dashboard</a>.</p>
            </div>

            <!-- Right: Preview -->
            <div class="wa-design-preview">
                <div class="wa-preview-card wa-statement-preview">
                    <div class="wa-stmt-header-row">
                        <h3 class="wa-design-card-title">Statement Preview</h3>
                        <div class="wa-format-tabs" id="wa-format-tabs" style="display:none;">
                            <button type="button" class="wa-format-tab wa-format-active" data-format="html">
                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
                                HTML
                            </button>
                            <button type="button" class="wa-format-tab" data-format="markdown">
                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 7V4a2 2 0 0 1 2-2h8.5L20 7.5V20a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-3"/></svg>
                                Markdown
                            </button>
                            <button type="button" class="wa-format-tab" data-format="text">
                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="17" y1="10" x2="3" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="17" y1="18" x2="3" y2="18"/></svg>
                                Text
                            </button>
                        </div>
                    </div>
                    <div id="wa-stmt-output" class="wa-stmt-output">
                        <?php if ($statement): ?>
                            <?php echo wp_kses_post($statement); ?>
                        <?php else: ?>
                            <div class="wa-stmt-empty">
                                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#c3c4c7" stroke-width="1.5"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
                                <p>Your statement will be shown here after generation.</p>
                                <p class="wa-stmt-hint">Fill in the form and click "Generate Statement" to create your accessibility statement.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="wa-stmt-actions" id="wa-stmt-actions" style="display:<?php echo $statement ? 'flex' : 'none'; ?>;">
                        <button type="button" id="wa-save-stmt" class="button button-primary">Publish as Page</button>
                        <button type="button" id="wa-copy-stmt" class="button">Copy</button>
                        <button type="button" id="wa-download-stmt" class="button">Download</button>
                    </div>
                    <div id="wa-stmt-msg" class="wa-stmt-msg" role="alert" style="display:none;"></div>
                </div>
            </div>
        </div>
    </div>
    <?php
}
