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

require_once 'vendor/autoload.php'; // Include the Google API Client Library

// Initialize the Google API Client
//$client = new Google_Client();
$client = new Google\Client();
$client->setAuthConfig('oauth-credentials.json'); // Path to your OAuth credentials JSON file
$client->addScope(Google_Service_Docs::DOCUMENTS); // Set the appropriate scope for Google Docs
//$client->addScope(Google\Service\Drive::DRIVE);

$client->setAccessType('offline');        // offline access
$client->setIncludeGrantedScopes(true);   // incremental auth


$redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);

// Create a Google Docs service
$service = new Google_Service_Docs($client);

if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code'], $_SESSION['code_verifier']);
    $client->setAccessToken($token);

    // store in the session also
    $_SESSION['upload_token'] = $token;

    // redirect back to the example
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

// set the access token as part of the client
if (!empty($_SESSION['upload_token'])) {
    $client->setAccessToken($_SESSION['upload_token']);
    if ($client->isAccessTokenExpired()) {
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            $_SESSION['upload_token'] = $client->getAccessToken();
        } else {
            unset($_SESSION['upload_token']);
        }
    }
} else {
    $_SESSION['code_verifier'] = $client->getOAuth2Service()->generateCodeVerifier();
    $authUrl = $client->createAuthUrl();
}

// Create a Google Docs service
$service = new Google_Service_Docs($client);


// Form data
$clientName = $_POST['first_name']; // Assuming you have a form input named 'first_name'

// Define the Google Doc ID of your template document
$templateDocumentId = '1RaPRLceht4bElaIqwFVWBaH92428PJciu9sCZ5lQimU'; // Replace with the actual template document ID

// Create a copy of the template document using Google Drive API
$driveService = new Google_Service_Drive($client);
$driveCopyMetadata = new Google_Service_Drive_DriveFile(array(
    'name' => 'Copy of Template Document', // Set the name of the copy
));
$copyDocument = $driveService->files->copy($templateDocumentId, $driveCopyMetadata);

// Access the copied document using Google Docs API
$service = new Google_Service_Docs($client);

// Define the content you want to replace
$replacements = [
    '<<CLIENT>>' => $clientName,
    // Add more placeholders and corresponding form values here
];

// Loop through the placeholders and replace them in the copy document
foreach ($replacements as $placeholder => $value) {
    $searchReplaceRequest = new Google_Service_Docs_Request(array(
        'replaceAllText' => array(
            'containsText' => array(
                'text' => $placeholder,
                'matchCase' => true,
            ),
            'replaceText' => $value,
        ),
    ));
    $service->documents->batchUpdate($copyDocument->documentId, new Google_Service_Docs_BatchUpdateDocumentRequest(array(
        'requests' => [$searchReplaceRequest],
    )));
}

// Export the copy document as a PDF (or any other format you prefer)
$pdfFile = 'copied_document.pdf'; // Define the path where you want to save the copied document
$pdfContent = $service->documents->get($copyDocument->documentId, array('exportFormat' => 'PDF'));
file_put_contents($pdfFile, $pdfContent->getBody());

// Provide a link to download the modified document (PDF)
echo json_encode(array('download_link' => $pdfFile));
?>
