#!/usr/bin/perl

#                                      Copyright 2025 WebPros International, LLC
#                                                           All rights reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited.

package Cpanel::Server::Handlers::CometWebProsCallback;

use cPstrict;
use Cpanel::Server;

=head1 NAME

Cpanel::Server::Handlers::CometWebProsCallback - Handle WebPros OAuth callbacks for Comet plugin

=head1 DESCRIPTION

This handler intercepts callbacks from WebPros OAuth flow for the Comet plugin.
It serves a JavaScript page that will communicate the authorization code back to
the parent window via postMessage, avoiding the need for a session-aware callback URL.

=cut

sub handler ($r) {

    # This handler serves a simple HTML/JavaScript page that will:
    # 1. Extract code and state from URL parameters
    # 2. Post them to the parent window (the POC page)
    # 3. Close the popup

    my $html = <<'HTML';
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebPros Authentication - Processing...</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background: #f5f5f5;
        }
        .processing {
            text-align: center;
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 1rem;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .message {
            color: #666;
            margin-top: 1rem;
        }
        .error {
            color: #d32f2f;
        }
    </style>
</head>
<body>
    <div class="processing">
        <div class="spinner"></div>
        <h2>Processing Authentication...</h2>
        <p class="message" id="status">Please wait while we complete your authentication.</p>
    </div>

    <script>
        (function() {
            const statusEl = document.getElementById('status');
            
            // Check if this is a Comet OAuth callback
            const urlParams = new URLSearchParams(window.location.search);
            const code = urlParams.get('code');
            const state = urlParams.get('state');
            
            // Try to parse state to check if it's for Comet
            let isComet = false;
            if (state) {
                try {
                    // State format from WebPros provider: redirect-cpanel=URL|JSON
                    const parts = state.split('|');
                    if (parts.length > 1) {
                        const stateData = JSON.parse(parts[1]);
                        if (stateData.purpose === 'comet_backup_license_verification') {
                            isComet = true;
                        }
                    }
                } catch (e) {
                    // Not Comet callback, let standard handler deal with it
                }
            }
            
            if (!isComet) {
                // Not a Comet callback, redirect to standard handler
                statusEl.textContent = 'Redirecting to standard authentication handler...';
                // Let the page continue to load normally and hit the standard handler
                return;
            }
            
            // This IS a Comet callback
            if (code && window.opener) {
                // Send the authorization code back to the parent window
                try {
                    window.opener.postMessage({
                        type: 'webpros_auth_callback',
                        code: code,
                        state: state
                    }, window.location.origin);
                    
                    statusEl.textContent = 'Authentication successful! Closing window...';
                    
                    // Close this popup after a short delay
                    setTimeout(() => {
                        window.close();
                    }, 1000);
                } catch (error) {
                    statusEl.className = 'message error';
                    statusEl.textContent = 'Error communicating with parent window. Please close this window and try again.';
                }
            } else if (!code) {
                statusEl.className = 'message error';
                statusEl.textContent = 'No authorization code received. Please close this window and try again.';
            } else if (!window.opener) {
                statusEl.className = 'message error';
                statusEl.textContent = 'This page must be opened from the authentication dialog. Please close this window.';
            }
        })();
    </script>
</body>
</html>
HTML

    # Set response headers
    $r->content_type('text/html; charset=utf-8');
    $r->status(200);

    # Send the response
    $r->print($html);

    return 200;
}

1;
