<?php
/**
 * Google OAuth 2.0 callback handler.
 * Receives the authorization code from Google, exchanges it for tokens,
 * and stores them in the database.
 */

// Bootstrap using the Audit Engine (same DB, same services)
define('ROOT_PATH', dirname(__DIR__) . '/Audit');
define('VIEWS_PATH', ROOT_PATH . '/views');

require_once ROOT_PATH . '/lib/Env.php';
\Crawl\Lib\Env::load(ROOT_PATH . '/.env');

spl_autoload_register(function (string $class): void {
    $prefix = 'Crawl\\';
    if (strpos($class, $prefix) !== 0) return;
    $file = ROOT_PATH . '/' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
    if (file_exists($file)) require_once $file;
});

session_start();

$savitBase = dirname($_SERVER['SCRIPT_NAME'], 2);  // e.g. /Savit

$code  = $_GET['code']  ?? '';
$state = $_GET['state'] ?? '';
$error = $_GET['error'] ?? '';

if ($error) {
    $msg = htmlspecialchars($error . ': ' . ($_GET['error_description'] ?? 'Authorization denied'));
    header("Location: {$savitBase}/?oauth_error=" . urlencode($msg));
    exit;
}

if (!$code || !$state) {
    header("Location: {$savitBase}/?oauth_error=missing_params");
    exit;
}

try {
    $oauth = new \Crawl\Services\GoogleOAuthService();

    // Detect bulk vs single-project flow from state param
    $stateData = $state ? json_decode(base64_decode($state), true) : [];
    $isBulk    = ($stateData['type'] ?? '') === 'bulk';

    if ($isBulk) {
        $result      = $oauth->handleBulkCallback($code);
        $analyticsBase = $savitBase . '/Analytics/public';
        header("Location: {$analyticsBase}/?bulk_connected=" . urlencode($result['email']));
        exit;
    }

    $result    = $oauth->handleCallback($code, $state);
    $projectId = $result['project_id'];
    $service   = $result['service'];

    $contentBase = $savitBase . '/Content';
    header("Location: {$contentBase}/projects/{$projectId}/edit?oauth_success={$service}#tab-integrations");
    exit;

} catch (\Exception $e) {
    $msg = htmlspecialchars($e->getMessage());
    header("Location: {$savitBase}/?oauth_error=" . urlencode($msg));
    exit;
}
