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

try {
    $client = new Google\Client();
    $client->setClientId('507547805046-7l61dd343l1656r1i7lbuilv5qnkp09b.apps.googleusercontent.com');
    $client->setClientSecret('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');
    $client->setRedirectUri('https://airsignsoul.online/space_php/login-google.php');
    $client->addScope(['email', 'profile']);

    if (isset($_GET['code'])) {
        $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
        
        if (isset($token['error'])) {
            die('Error: ' . $token['error_description'] ?? $token['error']);
        }
        
        $client->setAccessToken($token);
        
        $oauth = new Google\Service\Oauth2($client);
        $userInfo = $oauth->userinfo->get();
        
        $googleId = $userInfo->id;
        $email = $userInfo->email;
        $name = $userInfo->name ?? explode('@', $email)[0];
        
        $stmt = db()->prepare('SELECT * FROM users WHERE google_id = ? OR email = ?');
        $stmt->execute([$googleId, $email]);
        $user = $stmt->fetch();
        
        if ($user) {
            if (empty($user['full_name'])) {
                $update = db()->prepare('UPDATE users SET full_name = ? WHERE id = ?');
                $update->execute([$name, $user['id']]);
            }
            session_regenerate_id(true);
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['full_name'] = $user['full_name'] ?? $name;
            $_SESSION['logged_at'] = time();
            
            $token = bin2hex(random_bytes(32));
            $hash = hash('sha256', $token);
            $exp = date('Y-m-d H:i:s', time() + 60 * 60 * 24 * 365);
            db()->prepare('INSERT INTO remember_tokens (user_id, token_hash, expires_at) VALUES (?,?,?)')->execute([$user['id'], $hash, $exp]);
            setcookie('remember_token', $token, time() + 60 * 60 * 24 * 365, '/', '', false, true);
            
            redirect('dashboard.php');
        } else {
            $stmt = db()->prepare('INSERT INTO users (username, email, google_id, full_name, is_active) VALUES (?,?,?,?,1)');
            $stmt->execute([$name, $email, $googleId, $name]);
            $userId = db()->lastInsertId();
            $_SESSION['user_id'] = $userId;
            $_SESSION['username'] = $name;
            $_SESSION['full_name'] = $name;
            $_SESSION['logged_at'] = time();
            
            $token = bin2hex(random_bytes(32));
            $hash = hash('sha256', $token);
            $exp = date('Y-m-d H:i:s', time() + 60 * 60 * 24 * 365);
            db()->prepare('INSERT INTO remember_tokens (user_id, token_hash, expires_at) VALUES (?,?,?)')->execute([$userId, $hash, $exp]);
            setcookie('remember_token', $token, time() + 60 * 60 * 24 * 365, '/', '', false, true);
            
            redirect('dashboard.php');
        }
    } elseif (isset($_GET['error'])) {
        die('Error: ' . ($_GET['error_description'] ?? $_GET['error']));
    }
} catch (Exception $e) {
    error_log('Google Login Error: ' . $e->getMessage());
    die('An error occurred. Please try again later. Error: ' . $e->getMessage());
}