<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
/**
 * StudyTrack — Google OAuth 2.0 Callback Handler
 * URL: /google-auth.php
 *
 * Flow:
 *   1. User clicks "Sign in with Google"  → redirected to Google
 *   2. Google redirects back here          → we exchange code for token
 *   3. We fetch user's Google profile      → create/login user in DB
 *   4. Redirect to dashboard               → done ✅
 */
require_once 'includes/config.php';

// ── Already logged in? Go to dashboard ──────────────────────────
if (isLoggedIn()) {
    header('Location: ' . SITE_URL . '/dashboard.php');
    exit;
}

// ─────────────────────────────────────────────────────────────────
// STEP 1 — Build Google authorization URL (no code yet)
//          Called when user clicks "Sign in with Google"
// ─────────────────────────────────────────────────────────────────
if (!isset($_GET['code']) && !isset($_GET['error'])) {
    // Generate & store CSRF state token
    $state = bin2hex(random_bytes(16));
    $_SESSION['oauth_state'] = $state;

    $params = http_build_query([
        'client_id'     => GOOGLE_CLIENT_ID,
        'redirect_uri'  => GOOGLE_REDIRECT_URI,
        'response_type' => 'code',
        'scope'         => 'openid email profile',
        'access_type'   => 'online',
        'state'         => $state,
        'prompt'        => 'select_account', // Always show account picker
    ]);

    header('Location: https://accounts.google.com/o/oauth2/v2/auth?' . $params);
    exit;
}

// ─────────────────────────────────────────────────────────────────
// STEP 2 — Handle errors from Google
// ─────────────────────────────────────────────────────────────────
if (isset($_GET['error'])) {
    $err = htmlspecialchars($_GET['error']);
    header('Location: ' . SITE_URL . '/login.php?google_error=' . urlencode($err));
    exit;
}

// ─────────────────────────────────────────────────────────────────
// STEP 3 — Validate CSRF state
// ─────────────────────────────────────────────────────────────────
if (empty($_GET['state']) || $_GET['state'] !== ($_SESSION['oauth_state'] ?? '')) {
    header('Location: ' . SITE_URL . '/login.php?google_error=state_mismatch');
    exit;
}
unset($_SESSION['oauth_state']);

// ─────────────────────────────────────────────────────────────────
// STEP 4 — Exchange authorization code for access token
// ─────────────────────────────────────────────────────────────────
$tokenResponse = httpPost('https://oauth2.googleapis.com/token', [
    'code'          => $_GET['code'],
    'client_id'     => GOOGLE_CLIENT_ID,
    'client_secret' => GOOGLE_CLIENT_SECRET,
    'redirect_uri'  => GOOGLE_REDIRECT_URI,
    'grant_type'    => 'authorization_code',
]);

if (!$tokenResponse || empty($tokenResponse['access_token'])) {
    header('Location: ' . SITE_URL . '/login.php?google_error=token_failed');
    exit;
}

// ─────────────────────────────────────────────────────────────────
// STEP 5 — Fetch Google user profile
// ─────────────────────────────────────────────────────────────────
$profile = httpGet(
    'https://www.googleapis.com/oauth2/v3/userinfo',
    $tokenResponse['access_token']
);

if (!$profile || empty($profile['email'])) {
    header('Location: ' . SITE_URL . '/login.php?google_error=profile_failed');
    exit;
}

$googleId     = $profile['sub'];          // Unique Google user ID
$email        = strtolower(trim($profile['email']));
$name         = $profile['name']         ?? explode('@', $email)[0];
$googleAvatar = $profile['picture']      ?? null;
$emailVerified = $profile['email_verified'] ?? false;

// ─────────────────────────────────────────────────────────────────
// STEP 6 — Find or create user in database
// ─────────────────────────────────────────────────────────────────
try {
    // Case A: User already linked with this Google ID
    $stmt = $pdo->prepare("SELECT * FROM users WHERE google_id = ?");
    $stmt->execute([$googleId]);
    $user = $stmt->fetch();

    if (!$user) {
        // Case B: User exists with same email (local account) — link Google to it
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user) {
            // Check if account is disabled
            if (!empty($user['is_disabled'])) {
                header('Location: ' . SITE_URL . '/login.php?suspended=1');
                exit;
            }
            // Link Google ID to existing account + mark as verified
            $pdo->prepare(
                "UPDATE users SET google_id=?, google_avatar=?, auth_provider='google', is_verified=1 WHERE id=?"
            )->execute([$googleId, $googleAvatar, $user['id']]);
            // Refresh user data
            $stmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
            $stmt->execute([$user['id']]);
            $user = $stmt->fetch();

        } else {
            // Case C: Brand new user — store profile in session, redirect to terms page
            $_SESSION['google_pending'] = [
                'name'          => $name,
                'email'         => $email,
                'google_id'     => $googleId,
                'google_avatar' => $googleAvatar,
            ];
            header('Location: ' . SITE_URL . '/google-terms.php');
            exit;
        }
    }

    // Final check — account disabled?
    if (!empty($user['is_disabled'])) {
        header('Location: ' . SITE_URL . '/login.php?suspended=1');
        exit;
    }

    // ─────────────────────────────────────────────────────────────
    // STEP 7 — Log user in (same as normal login)
    // ─────────────────────────────────────────────────────────────
    session_regenerate_id(true);
    $_SESSION['user_id']    = $user['id'];
    $_SESSION['user_name']  = $user['name'];
    $_SESSION['user_email'] = $user['email'];
    $_SESSION['login_time'] = time();

    // Save 7-day DB session + cookie
    createDbSession($user['id']);

    header('Location: ' . SITE_URL . '/dashboard.php');
    exit;

} catch (PDOException $e) {
    error_log('Google auth DB error: ' . $e->getMessage());
    header('Location: ' . SITE_URL . '/login.php?google_error=db_error');
    exit;
}

// ─────────────────────────────────────────────────────────────────
// Helper: POST request using cURL
// ─────────────────────────────────────────────────────────────────
function httpPost(string $url, array $data): ?array {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($data),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/x-www-form-urlencoded'],
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    if ($err) { error_log('Google OAuth cURL POST error: ' . $err); return null; }
    return json_decode($res, true);
}

// ─────────────────────────────────────────────────────────────────
// Helper: GET request using cURL (with Bearer token)
// ─────────────────────────────────────────────────────────────────
function httpGet(string $url, string $accessToken): ?array {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $accessToken],
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    if ($err) { error_log('Google OAuth cURL GET error: ' . $err); return null; }
    return json_decode($res, true);
}