<?php
require_once 'vendor/autoload.php';
require_once 'db/config.php';

session_start();

$config = require_once 'hybridauth_config.php';

try {
    $hybridauth = new Hybridauth\Hybridauth($config);
    $adapter = $hybridauth->authenticate('Google');
    $userProfile = $adapter->getUserProfile();

    // Log user profile data for debugging
    $profile_data = date('Y-m-d H:i:s') . ' - User Profile: ' . print_r($userProfile, true) . "\n";
    file_put_contents('logs/hybridauth_debug.log', $profile_data, FILE_APPEND);


    // Check if user exists in our database
    $stmt = db()->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$userProfile->email]);
    $user = $stmt->fetch();

    if ($user) {
        // User exists, log them in
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['name'];
        header('Location: my_drills.php');
        exit();
    } else {
        // User does not exist, create a new account
        $password = password_hash(bin2hex(random_bytes(8)), PASSWORD_DEFAULT);
        $stmt = db()->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?)");
        $stmt->execute([$userProfile->displayName, $userProfile->email, $password]);
        $userId = db()->lastInsertId();

        $_SESSION['user_id'] = $userId;
        $_SESSION['user_name'] = $userProfile->displayName;
        header('Location: my_drills.php');
        exit();
    }
} catch (Exception $e) {
    $error_message = date('Y-m-d H:i:s') . ' - Hybridauth Error: ' . $e->getMessage() . "\n";
    file_put_contents('logs/hybridauth_errors.log', $error_message, FILE_APPEND);
    header('Location: login.php?error=social_login_failed');
    exit();
}
