<?php
/**
 * Simple OAuth Callback Server
 * 
 * This script creates a local server to capture the OAuth callback
 * Usage: php auth-server.php
 */

echo "Starting OAuth callback server on http://localhost:8080\n";
echo "Waiting for authorization callback...\n\n";

// Start built-in PHP server
$server = stream_socket_server("tcp://127.0.0.1:8080", $errno, $errstr);

if (!$server) {
    die("Error: $errstr ($errno)\n");
}

while ($conn = stream_socket_accept($server)) {
    $request = fread($conn, 1024);
    
    // Parse the request
    if (preg_match('/GET \/callback\?code=([^\s&]+)/', $request, $matches)) {
        $auth_code = $matches[1];
        
        // Send response
        $response = "HTTP/1.1 200 OK\r\n";
        $response .= "Content-Type: text/html\r\n\r\n";
        $response .= "<html><body>";
        $response .= "<h1>Authorization Successful!</h1>";
        $response .= "<p>Authorization code received. You can close this window.</p>";
        $response .= "<p>Code: <code>$auth_code</code></p>";
        $response .= "<p>Copy this code and paste it in the terminal.</p>";
        $response .= "</body></html>";
        
        fwrite($conn, $response);
        fclose($conn);
        
        echo "Authorization code received: $auth_code\n";
        echo "Copy this code to your terminal.\n";
        
        // Keep server running to display the page
        sleep(10);
        break;
    } else {
        // Send 404 for other requests
        $response = "HTTP/1.1 404 Not Found\r\n";
        $response .= "Content-Type: text/html\r\n\r\n";
        $response .= "<html><body><h1>404 Not Found</h1></body></html>";
        
        fwrite($conn, $response);
        fclose($conn);
    }
}

fclose($server);
echo "\nServer stopped.\n";