<?php
/* *************************************************** */
// Google Docs Creator
// Gets a Tempalate copies it and inserts data,
// Then saves into the specified folder as a Doc and as a PDF
// In future it will email the pdf to customer email
// (c) 2023 Benjamin Harris ben@tazz.com.au
/* *************************************************** */

//phpinfo();

error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
//error_reporting(E_ERROR | E_PARSE);
//
require_once 'vendor/autoload.php';
session_start();

date_default_timezone_set("Australia/Hobart");

$today = date("Y-m-d");
$datetime = date("D dS M y  @  h:i a");

//Variables to insert into Google Doc
$date = date("D dS M y");
$first_name = 'John';
$last_name = 'Doe';
$name = $first_name . ' ' . $last_name;
$company = 'ABC Company';
$postal_address = '123 Some Street, Some Town, Some State, Some PC';
$drg = '301003';
$building_description = 'Commercial Extension';
$site_address = '456 black Street, Black Town, Black State, Black PC';
$street = explode(",", $site_address);
$site_address_street = substr($street[0], 0);
$agent = 'Benjamin Harris';
$agent_company = 'Agent Company';
$file_name = $drg . ' - ' . $name . ' - LOA - ' . $today;

$redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

// Set up Google API Client
$client = new Google\Client();
$client->setAuthConfig('oauth-credentials.json');
$client->setAccessType('offline');
$client->setRedirectUri($redirect_uri);
$client->setScopes([Google_Service_Drive::DRIVE, Google_Service_Docs::DOCUMENTS]);
$service = new Google\Service\Drive($client);

// Authorize with Google
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 Google Drive and Google Docs service
$driveService = new Google\Service\Drive($client);
$docsService = new Google\Service\Docs($client);

// Following may be required to future proof, here you can specify the title of the document instead of the document id
/*
// Specify the title (name) of your Google Doc
$docTitle = 'Your Google Doc Title';

// List files in your Google Drive
$files = $driveService->files->listFiles([
    'q' => "name='$docTitle' and mimeType='application/vnd.google-apps.document'",
]);

if (count($files->getFiles()) > 0) {
    // Get the first matching document
    $documentId = $files->getFiles()[0]->getId();
} else {
    echo 'Google Doc not found.';
    die;
}
*/

// Replace with your Google Doc's Template file ID
$documentId = '1RaPRLceht4bElaIqwFVWBaH92428PJciu9sCZ5lQimU';

// Copy the template into a new file — replacements happen on the copy, not the template
$driveFile = new Google\Service\Drive\DriveFile(['name' => $file_name]);
$driveFile = $driveService->files->copy($documentId, $driveFile);

// Replace template placeholders using the Docs batchUpdate API.
// getBody()->getContent() returns an array of objects, not a string — str_replace cannot be used here.
$replacements = [
    '<<DATE>>'                  => $date,
    '<<NAME>>'                  => $name,
    '<<FIRST_NAME>>'            => $first_name,
    '<<COMPANY>>'               => $company,
    '<<POSTAL_ADDRESS>>'        => $postal_address,
    '<<DRG>>'                   => $drg,
    '<<BUILDING_DESCRTIPTION>>' => $building_description,
    '<<SITE_ADDRESS>>'          => $site_address,
    '<<AGENT>>'                 => $agent,
    '<<AGENT_COMPANY>>'         => $agent_company,
];

$requests = [];
foreach ($replacements as $placeholder => $value) {
    $requests[] = new Google\Service\Docs\Request([
        'replaceAllText' => [
            'containsText' => ['text' => $placeholder, 'matchCase' => true],
            'replaceText'  => $value,
        ],
    ]);
}
$docsService->documents->batchUpdate(
    $driveFile->getId(),
    new Google\Service\Docs\BatchUpdateDocumentRequest(['requests' => $requests])
);


// Find the Specified Folder to save documents in,

// Specify the title (name) of your Google Doc
$folderTitle = $drg . ' - ' . $site_address_street;

// List files in your Google Drive
$files = $driveService->files->listFiles([
    'q' => "name='$folderTitle' and mimeType='application/vnd.google-apps.folder'",
]);

if (count($files->getFiles()) > 0) {
    // Get the first matching document
    $folderId = $files->getFiles()[0]->getId();
} else {
    echo 'Google folder not found.';
	// Create the folder if it doesnt exist,
	// folder needs to be created inside folder called  [03]Projects 2023   which is "[0Y] Projects YYYY"
	// $parent_folder = '[0' . substr(date(y), -1) . '] Projects' . date(Y);
    
}


// Move the copied file to a specific folder
$driveService->files->update($driveFile->getId(), null, [
    'addParents' => '1ZwFTZ-YzFwYs1mN772WSET570E9ec-7O',
    'removeParents' => $driveFile->getParents()[0],
]);

// Export the Google Doc as a PDF using the Drive export endpoint.
// files->copy() with a mimeType option does not convert formats — export() must be used instead.
$pdfResponse = $driveService->files->export($driveFile->getId(), 'application/pdf', ['alt' => 'media']);
$pdfBytes    = $pdfResponse->getBody()->getContents();
file_put_contents($file_name . '.pdf', $pdfBytes);


echo 'Letter copied, variables replaced, and saved in the client folder.';
