<?php
declare(strict_types=1);

namespace Instinctor\Core;

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

/**
 * First-admin-visit consent notice.
 *
 * Renders a dismissible admin_notices banner on every wp-admin page until
 * the site owner has either granted or declined consent for the plugin
 * to talk to platform.instinctor.com.
 *
 * Hooks (registered from Plugin::boot when running in WordPress mode):
 *   - admin_notices  → renderBanner()
 *   - wp_ajax_instinctor_consent_grant   → ajaxGrant()
 *   - wp_ajax_instinctor_consent_dismiss → ajaxDismiss()
 *
 * Standalone is unaffected — PlatformConsent::granted() / seen() short-circuit
 * to true there, so renderBanner() bails immediately.
 *
 * @since 2.1.956
 */
class PlatformConsentNotice
{
    public static function init(): void
    {
        // Standalone mode has no opt-in surface — skip the whole subsystem.
        if (defined('INSTINCTOR_ENV') && INSTINCTOR_ENV === 'standalone') {
            return;
        }
        if (!function_exists('add_action')) {
            return;
        }

        \add_action('admin_notices', [self::class, 'renderBanner']);
        \add_action('wp_ajax_instinctor_consent_grant',   [self::class, 'ajaxGrant']);
        \add_action('wp_ajax_instinctor_consent_dismiss', [self::class, 'ajaxDismiss']);
    }

    public static function renderBanner(): void
    {
        if (!function_exists('current_user_can') || !\current_user_can('manage_options')) {
            return;
        }
        if (PlatformConsent::seen()) {
            return;
        }

        $nonce   = \wp_create_nonce('instinctor_consent');
        $ajaxUrl = \admin_url('admin-ajax.php');
        $privacy = 'https://instinctor.com/privacy';
        $terms   = 'https://instinctor.com/terms';
        ?>
        <div id="instinctor-consent-notice" class="notice notice-info is-dismissible" style="
            padding:14px 16px;border-left-color:#1d2327;">
            <h3 style="margin:0 0 6px;font-size:14px;color:#1d2327;">
                <?php \esc_html_e('Connect Instinctor to platform.instinctor.com?', 'instinctor'); ?>
            </h3>
            <p style="margin:0 0 10px;font-size:13px;color:#555;max-width:780px;">
                <?php \esc_html_e(
                    'Instinctor uses platform.instinctor.com to deliver transactional email, validate licenses, fetch plugin updates, run the writing assistant, and host curated section + 3D image libraries. None of these features run unless you opt in here. You can change this any time in Instinctor → Settings → Privacy.',
                    'instinctor'
                ); ?>
            </p>
            <p style="margin:0 0 12px;font-size:12px;color:#999;">
                <a href="<?php echo \esc_url($privacy); ?>" target="_blank" rel="noopener"><?php \esc_html_e('Privacy policy', 'instinctor'); ?></a>
                &nbsp;·&nbsp;
                <a href="<?php echo \esc_url($terms); ?>" target="_blank" rel="noopener"><?php \esc_html_e('Terms', 'instinctor'); ?></a>
            </p>
            <p style="margin:0;display:flex;gap:8px;align-items:center;">
                <button type="button" id="instinctor-consent-grant" class="button button-primary" style="
                    height:26px;line-height:24px;padding:0 12px;font-size:12px;">
                    <?php \esc_html_e('Connect', 'instinctor'); ?>
                </button>
                <button type="button" id="instinctor-consent-decline" class="button" style="
                    height:26px;line-height:24px;padding:0 12px;font-size:12px;">
                    <?php \esc_html_e('No thanks', 'instinctor'); ?>
                </button>
                <span id="instinctor-consent-msg" style="font-size:11px;color:#999;margin-left:6px;"></span>
            </p>
        </div>
        <script>
        (function(){
            var notice  = document.getElementById('instinctor-consent-notice');
            var grant   = document.getElementById('instinctor-consent-grant');
            var decline = document.getElementById('instinctor-consent-decline');
            var msg     = document.getElementById('instinctor-consent-msg');
            var nonce   = <?php echo \wp_json_encode($nonce); ?>;
            var ajaxUrl = <?php echo \wp_json_encode($ajaxUrl); ?>;

            function post(action, after) {
                var fd = new FormData();
                fd.append('action', action);
                fd.append('_wpnonce', nonce);
                fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
                    .then(function(r){ return r.json(); })
                    .then(function(d){ after(d && d.success); })
                    .catch(function(){ after(false); });
            }

            grant.addEventListener('click', function() {
                grant.disabled = true; decline.disabled = true;
                msg.textContent = '<?php echo \esc_js(\__('Saving…', 'instinctor')); ?>';
                post('instinctor_consent_grant', function(ok){
                    if (ok) {
                        msg.textContent = '<?php echo \esc_js(\__('Connected.', 'instinctor')); ?>';
                        notice.style.display = 'none';
                    } else {
                        grant.disabled = false; decline.disabled = false;
                        msg.textContent = '<?php echo \esc_js(\__('Could not save. Try again.', 'instinctor')); ?>';
                    }
                });
            });

            decline.addEventListener('click', function() {
                grant.disabled = true; decline.disabled = true;
                post('instinctor_consent_dismiss', function(){ notice.style.display = 'none'; });
            });

            // WP's built-in dismiss button counts as "no thanks" too.
            notice.addEventListener('click', function(e){
                if (e.target && e.target.classList.contains('notice-dismiss')) {
                    post('instinctor_consent_dismiss', function(){});
                }
            });
        })();
        </script>
        <?php
    }

    public static function ajaxGrant(): void
    {
        if (!\current_user_can('manage_options')) {
            \wp_send_json_error(['message' => 'forbidden'], 403);
            return;
        }
        if (!\check_ajax_referer('instinctor_consent', '_wpnonce', false)) {
            \wp_send_json_error(['message' => 'bad_nonce'], 403);
            return;
        }
        PlatformConsent::grant();
        \wp_send_json_success(['consent' => '1']);
    }

    public static function ajaxDismiss(): void
    {
        if (!\current_user_can('manage_options')) {
            \wp_send_json_error(['message' => 'forbidden'], 403);
            return;
        }
        if (!\check_ajax_referer('instinctor_consent', '_wpnonce', false)) {
            \wp_send_json_error(['message' => 'bad_nonce'], 403);
            return;
        }
        PlatformConsent::markSeen();
        \wp_send_json_success(['consent' => '0']);
    }
}
