<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

session_start();

use Google\Client;
use Google\Service\Drive;

$client = new Client();
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('http://YOUR-VPS-IP/index.php');

$client->addScope(Drive::DRIVE_READONLY);
$client->setAccessType('offline');
$client->setPrompt('consent');

if (!isset($_SESSION['token']) && !isset($_GET['code'])) {
    echo "<a href='" . $client->createAuthUrl() . "'>Login with Google</a>";
    exit;
}

if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $_SESSION['token'] = $token;
    header("Location: index.php");
    exit;
}

$client->setAccessToken($_SESSION['token']);

$service = new Drive($client);

try {
    $files = $service->files->listFiles([
        'pageSize' => 10,
        'fields' => 'files(id,name)'
    ]);
} catch (Exception $e) {
    die("Drive error: " . $e->getMessage());
}

echo "<h2>Drive Files</h2>";

foreach ($files->getFiles() as $file) {
    echo $file->getName() . "<br>";
}