<?php
require_once __DIR__ . '/../models/User.php';
require_once __DIR__ . '/../helpers/GoogleOAuthHelper.php';

/**
 * Controller for handling OAuth authentication
 */
class AuthController {
    private $user;
    private $googleOAuthHelper;

    public function __construct() {
        $this->user = new User();
        $this->googleOAuthHelper = new GoogleOAuthHelper();
    }

    /**
     * Redirect to Google OAuth authorization URL
     */
    public function googleAuth() {
        if (!$this->googleOAuthHelper->isEnabled()) {
            header('Location: /login?error=google_auth_disabled');
            exit;
        }

        // Get authorization URL
        $authUrl = $this->googleOAuthHelper->getAuthorizationUrl();

        // Store state in session for CSRF protection
        $_SESSION['oauth2state'] = $this->googleOAuthHelper->getState();

        // Redirect to Google
        header('Location: ' . $authUrl);
        exit;
    }

    /**
     * Handle Google OAuth callback
     */
    public function googleCallback() {
        // Check for errors
        if (isset($_GET['error'])) {
            header('Location: /login?error=google_auth_error&details=' . urlencode($_GET['error']));
            exit;
        }

        // Validate state parameter
        if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
            // State validation failed, clear session and redirect
            unset($_SESSION['oauth2state']);
            header('Location: /login?error=invalid_state');
            exit;
        }

        // Check for authorization code
        if (empty($_GET['code'])) {
            header('Location: /login?error=missing_code');
            exit;
        }

        try {
            // Get user details from Google
            $googleUser = $this->googleOAuthHelper->getUserFromToken($_GET['code']);

            if (!$googleUser) {
                header('Location: /login?error=google_auth_failed');
                exit;
            }

            // Register or login user
            $user = $this->user->registerOrLoginWithGoogle($googleUser);

            if (!$user) {
                header('Location: /login?error=registration_failed');
                exit;
            }

            // Set session variables
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['user_role'] = $user['role'];

            // Redirect to profile
            header('Location: /profile');
            exit;
        } catch (Exception $e) {
            error_log('Google OAuth error: ' . $e->getMessage());
            header('Location: /login?error=google_auth_exception');
            exit;
        }
    }
}
