<?php
// Include configuration and Google Client setup
require_once 'config.php';

// Start the session (ensure this is done in config.php or here)
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

$message = '';
$redirect_to = 'index.php'; // Default redirect location

try {
    // 1. Check if the 'code' parameter exists, which signals the Google redirect
    if (!isset($_GET['code'])) {
        throw new Exception("Authorization code missing from Google response.");
    }
    
    $client = getGoogleClient();
    
    // 2. Exchange the authorization code for an access token
    $accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    
    if (isset($accessToken['error'])) {
        // Handle token exchange errors
        throw new Exception("Error fetching access token: " . $accessToken['error_description']);
    }

    $client->setAccessToken($accessToken);
    
    // 3. Get user profile information (email and profile)
    $oauth2Service = new Google\Service\Oauth2($client);
    $userInfo = $oauth2Service->userinfo->get();

    // Required user data
    $google_id = $userInfo->getId();
    $email = $userInfo->getEmail();
    $first_name = $userInfo->getGivenName() ?: 'User';
    $last_name = $userInfo->getFamilyName() ?: '';
    $image_url = $userInfo->getPicture() ?: 'https://placehold.co/150x150/e5e7eb/4b5563?text=User';

    // 4. Check if the user exists in your database by email
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user) {
        // User exists, check if we need to update their Google ID or image
        $update_fields = [];
        $params = [];
        
        if (empty($user['google_id']) || $user['google_id'] !== $google_id) {
            $update_fields[] = 'google_id = ?';
            $params[] = $google_id;
        }
        if ($user['image_url'] !== $image_url) {
            $update_fields[] = 'image_url = ?';
            $params[] = $image_url;
        }

        if (!empty($update_fields)) {
            $params[] = $user['id'];
            $update_sql = "UPDATE users SET " . implode(', ', $update_fields) . " WHERE id = ?";
            $pdo->prepare($update_sql)->execute($params);
        }
        
        // Use existing user data for session
        $user_data = $user;

    } else {
        // 5. New User: Register them automatically
        $role = 'student'; // Default role for Google sign-ups
        
        // Note: Password is set to NULL/empty since they use Google auth
        $stmt = $pdo->prepare(
            "INSERT INTO users (first_name, last_name, email, google_id, role, image_url, password) 
             VALUES (?, ?, ?, ?, ?, ?, NULL)"
        );
        $stmt->execute([$first_name, $last_name, $email, $google_id, $role, $image_url]);
        
        // Fetch the newly inserted user
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user_data = $stmt->fetch();
        
        if (!$user_data) {
             throw new Exception("Failed to retrieve newly created user record.");
        }

        $message = "Registration successful via Google!";
    }

    // 6. Log the user into the session
    $_SESSION['user_id'] = $user_data['id'];
    $full_name = $user_data['first_name'] . (isset($user_data['last_name']) ? ' ' . $user_data['last_name'] : '');
    $_SESSION['user_name'] = trim($full_name) ?: $user_data['first_name'];
    $_SESSION['user_role'] = $user_data['role'];
    $_SESSION['image_url'] = $user_data['image_url'];

    // 7. Determine final redirect based on role
    if ($user_data['role'] === 'admin') {
        $redirect_to = 'dashboard.php';
    } else {
        $redirect_to = 'studentdash.php';
    }

} catch (Exception $e) {
    // Log error and redirect to login page with an error message
    error_log("Google Auth Error: " . $e->getMessage());
    $redirect_to = 'index (1).php?msg=' . urlencode('Google Sign-In failed: ' . $e->getMessage());
}

// Final Redirect
header("Location: " . $redirect_to);
exit();
?>