<?php
require_once __DIR__ . '/../vendor/autoload.php';

use League\OAuth2\Client\Provider\Google;
use League\OAuth2\Client\Provider\GoogleUser;

/**
 * Helper class for Google OAuth authentication
 */
class GoogleOAuthHelper {
    private $provider;
    private $clientId;
    private $clientSecret;
    private $redirectUri;
    private $isEnabled = false;

    /**
     * Constructor
     */
    public function __construct() {
        $this->clientId = $_ENV['GOOGLE_CLIENT_ID'] ?? '';
        $this->clientSecret = $_ENV['GOOGLE_CLIENT_SECRET'] ?? '';
        $this->redirectUri = $this->getBaseUrl() . '/auth/google/callback';

        // Check if Google OAuth is enabled
        $this->isEnabled = !empty($this->clientId) && !empty($this->clientSecret);

        if ($this->isEnabled) {
            $this->provider = new Google([
                'clientId'     => $this->clientId,
                'clientSecret' => $this->clientSecret,
                'redirectUri'  => $this->redirectUri,
                'scopes'       => ['email', 'profile'],
            ]);
        }
    }

    /**
     * Check if Google OAuth is enabled
     */
    public function isEnabled() {
        return $this->isEnabled;
    }

    /**
     * Get the authorization URL
     */
    public function getAuthorizationUrl() {
        if (!$this->isEnabled) {
            return '#';
        }

        $options = [
            'scope' => ['email', 'profile'],
        ];

        return $this->provider->getAuthorizationUrl($options);
    }

    /**
     * Get the state parameter
     */
    public function getState() {
        return $this->provider->getState();
    }

    /**
     * Get user details from the access token
     */
    public function getUserFromToken($token) {
        if (!$this->isEnabled) {
            return null;
        }

        try {
            // Get access token
            $accessToken = $this->provider->getAccessToken('authorization_code', [
                'code' => $token
            ]);

            // Get user details
            $user = $this->provider->getResourceOwner($accessToken);

            return $user;
        } catch (Exception $e) {
            error_log('Google OAuth error: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Get the base URL of the application
     */
    private function getBaseUrl() {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'];
        return $protocol . '://' . $host;
    }
}
