<?php

defined('BASEPATH') or exit('No direct script access allowed');

class GoogleDrive_test extends CI_Controller
{

    public function test_google()
    {
        require_once APPPATH . '../vendor/autoload.php';

        $client = new Google_Client();
        $client->setAuthConfig(APPPATH . 'credentials/credentials.json');
        $client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
        $client->setRedirectUri('https://ms1crmdev.progiweb.net/index.php/GoogleDrive_test/test_google');
        $client->setAccessType('offline');
        $client->setPrompt('consent');

        if (!isset($_GET['code'])) {
            // Redirige vers la page de consentement
            $auth_url = $client->createAuthUrl();
            header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
            exit;
        } else {
            // Récupère et enregistre le token
            $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
            if (isset($token['access_token'])) {
                file_put_contents(APPPATH . 'credentials/token.json', json_encode($token));
                echo '✅ Token enregistré avec succès.';
            } else {
                echo '❌ Erreur de token : ';
                print_r($token);
            }
        }
    }
}
