<?php
// callback.php - OAuth Callback Handler (FIXED - No parameter reuse)

session_start();

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/src/OAuth.php';
require_once __DIR__ . '/src/Database.php';

// Check for error in callback
if (isset($_GET['error'])) {
    $error = htmlspecialchars($_GET['error']);
    die("⚠️ OAuth Error: " . $error);
}

// Check for authorization code
if (!isset($_GET['code'])) {
    die("⚠️ No authorization code received");
}

// Verify state to prevent CSRF
if (!isset($_GET['state']) || !isset($_SESSION['oauth_state']) || $_GET['state'] !== $_SESSION['oauth_state']) {
    die("⚠️ Invalid state parameter. Possible CSRF attack.");
}

try {
    // Initialize OAuth
    $oauth = new OAuth(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URI);
    
    // Exchange authorization code for tokens
    $code = $_GET['code'];
    $tokens = $oauth->exchangeCodeForTokens($code);
    
    if (!$tokens || !isset($tokens['access_token'])) {
        die("⚠️ Failed to exchange code for tokens");
    }
    
    // Get user info
    $userInfo = $oauth->getUserInfo($tokens['access_token']);
    
    if (!$userInfo || !isset($userInfo['email'])) {
        die("⚠️ Failed to get user info");
    }
    
    // Get database connection
    $db = Database::getInstance();
    
    // Check if user exists
    $stmt = $db->prepare("SELECT id FROM users WHERE email = :email LIMIT 1");
    $stmt->execute([':email' => $userInfo['email']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($user) {
        // User exists, update
        $user_id = $user['id'];
        
        $stmt = $db->prepare("
            UPDATE users 
            SET name = :name,
                picture = :picture,
                last_login = NOW()
            WHERE id = :id
        ");
        
        $stmt->execute([
            ':name' => $userInfo['name'] ?? '',
            ':picture' => $userInfo['picture'] ?? '',
            ':id' => $user_id
        ]);
    } else {
        // Create new user
        $stmt = $db->prepare("
            INSERT INTO users (email, name, picture, created_at, last_login)
            VALUES (:email, :name, :picture, NOW(), NOW())
        ");
        
        $stmt->execute([
            ':email' => $userInfo['email'],
            ':name' => $userInfo['name'] ?? '',
            ':picture' => $userInfo['picture'] ?? ''
        ]);
        
        $user_id = $db->lastInsertId();
    }
    
    // Save or update OAuth tokens
    $expires_at = date('Y-m-d H:i:s', time() + ($tokens['expires_in'] ?? 3600));
    
    // Check if token exists for this user
    $stmt = $db->prepare("SELECT id FROM oauth_tokens WHERE user_id = :user_id LIMIT 1");
    $stmt->execute([':user_id' => $user_id]);
    $existing_token = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existing_token) {
        // Update existing token
        $stmt = $db->prepare("
            UPDATE oauth_tokens 
            SET access_token = :access_token,
                refresh_token = :refresh_token,
                token_type = :token_type,
                expires_at = :expires_at,
                scope = :scope,
                updated_at = NOW()
            WHERE user_id = :user_id
        ");
        
        $stmt->execute([
            ':access_token' => $tokens['access_token'],
            ':refresh_token' => $tokens['refresh_token'] ?? null,
            ':token_type' => $tokens['token_type'] ?? 'Bearer',
            ':expires_at' => $expires_at,
            ':scope' => $tokens['scope'] ?? '',
            ':user_id' => $user_id
        ]);
    } else {
        // Insert new token
        $stmt = $db->prepare("
            INSERT INTO oauth_tokens (
                user_id,
                access_token,
                refresh_token,
                token_type,
                expires_at,
                scope,
                created_at,
                updated_at
            ) VALUES (
                :user_id,
                :access_token,
                :refresh_token,
                :token_type,
                :expires_at,
                :scope,
                NOW(),
                NOW()
            )
        ");
        
        $stmt->execute([
            ':user_id' => $user_id,
            ':access_token' => $tokens['access_token'],
            ':refresh_token' => $tokens['refresh_token'] ?? null,
            ':token_type' => $tokens['token_type'] ?? 'Bearer',
            ':expires_at' => $expires_at,
            ':scope' => $tokens['scope'] ?? ''
        ]);
    }
    
    // Set session variables
    $_SESSION['user_id'] = $user_id;
    $_SESSION['user_email'] = $userInfo['email'];
    $_SESSION['user_name'] = $userInfo['name'] ?? '';
    $_SESSION['user_picture'] = $userInfo['picture'] ?? '';
    $_SESSION['access_token'] = $tokens['access_token'];
    $_SESSION['refresh_token'] = $tokens['refresh_token'] ?? null;
    $_SESSION['token_expires_at'] = time() + ($tokens['expires_in'] ?? 3600);
    
    // Clear OAuth state
    unset($_SESSION['oauth_state']);
    
    // Redirect to dashboard
    header('Location: /admob-manager/pages/dashboard.php');
    exit;
    
} catch (PDOException $e) {
    error_log('OAuth Token Save Error: ' . $e->getMessage());
    die("⚠️ Database error: " . $e->getMessage());
} catch (Exception $e) {
    error_log('OAuth Callback Error: ' . $e->getMessage());
    die("⚠️ Authentication failed: " . $e->getMessage());
}
?>