<?php
/**
 * This is the generator for the wash certificates (Used by the WordPress plugin)
 * The reason behind this being outside the WordPress plugin is that the PHPExcel library is not compatible with the WordPress plugin, and it is easier to maintain the generator here.
 */

// Load the config file
require_once '../../config.php';
require_once '../../vendor/autoload.php';
/** Load the relevant classes */
require_once '../../interfaces/minio_wash_certificates_i.php';
require_once '../../traits/minio_t.php';
require_once '../../classes/wash_certificate_store.php';

use classes\wash_certificate_store;
use objects\bookings_o;

global $WORDPRESS_STATIC_TOKEN;
// Validate the token was loaded from the config file
if (!isset($WORDPRESS_STATIC_TOKEN) || $WORDPRESS_STATIC_TOKEN === '') {
    echo 'Missing token in config file';
    exit;
}
require 'vendor/autoload.php';
require_once 'twc_spreadsheet_class.php';

// Set CORS headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Content-Type");

// Set the timezone
date_default_timezone_set('Europe/Copenhagen');
// Set the time format
setlocale(LC_TIME, 'da_DK');
// Create the output directory if it does not exist
if (!file_exists('output/certificates')) {
    mkdir('output/certificates', 0777, true);
}
// Create the output/certificates directory if it does not exist
if (!file_exists('output/certificates')) {
    mkdir('output/certificates', 0777, true);
}
// If the request is from the command line
if (php_sapi_name() === 'cli') {
    // Set the $_GET variable to default values
    $_GET['secret_token'] = $WORDPRESS_STATIC_TOKEN;
    $_GET['sealOrPlumber'] = '12345';
    $_GET['performedBy'] = 'JH';
    $_GET['bookingId'] = '12345';
    $_GET['regNumber'] = 'AB12345';
    $_GET['regNumberTrailer'] = 'AB12345';
    $_GET['department'] = 'taastrup';
}
// Require the $_GET variable secret_token to be set
if (!isset($_GET['secret_token'])) {
    echo 'Invalid request';
    exit;
}

// make sure the secret token is correct
if ($_GET['secret_token'] !== $WORDPRESS_STATIC_TOKEN) {
    echo 'Invalid secret token';
    exit;
}

// Check if the $_GET variable justDownload is set
if (isset($_GET['justDownload'])) {
    // Require the $_GET variable bookingId to be set
    if (!isset($_GET['bookingId'])) {
        echo 'Missing required fields';
        exit;
    }
    // Usage example
    $wash_certificate_store = new wash_certificate_store();
    // Return the certificate download URL
    echo $wash_certificate_store->getWashCertificateDownload($_GET['bookingId']);
    // Exit the script
    exit;
}

// Require the $_GET variables sealOrPlumber, safetySeal, performedBy, and bookingId, regNumber, and regNumberTrailer to be set
if (!isset($_GET['sealOrPlumber']) || !isset($_GET['performedBy']) || !isset($_GET['bookingId']) || !isset($_GET['regNumber']) || !isset($_GET['regNumberTrailer']) || !isset($_GET['department'])) {
    // We are missing some required fields in the query string
    echo 'Missing required fields';
    exit;
}

// Check if the certificate already exists in the bucket
$wash_certificate_store = new wash_certificate_store();
if ($wash_certificate_store->washCertificateExists($_GET['bookingId'])) {
    // Return the certificate url
    echo $wash_certificate_store->getWashCertificateDownload($_GET['bookingId']);
    // Exit the script
    exit;
} else {
    // Check if the certificate exists in the filesystem (legacy system)
    if (file_exists(dirname(__FILE__) . "/output/certificates/wash_certificate_" . $_GET['bookingId'] . ".pdf")) {
        // Upload the certificate to the bucket
        $success = $wash_certificate_store->uploadFile("wash_certificate_" . $_GET['bookingId'] . ".pdf", dirname(__FILE__) . "/output/certificates/wash_certificate_" . $_GET['bookingId'] . ".pdf");
        // If the certificate was uploaded successfully, delete the local copy
        if ($success) {
            //unlink(dirname(__FILE__) . "/output/certificates/wash_certificate_" . $_GET['bookingId'] . ".pdf");
            // Return the certificate url
            echo $wash_certificate_store->getWashCertificateDownload($_GET['bookingId']);
            exit;
        }
        // If the certificate was not uploaded successfully, return an error
        echo 'Failed to upload the certificate';
        // Exit the script
        exit;
    }
}

// Usage example
$template = "templates/template2024julv3.xlsx";
$generator = new WashCertificateGenerator($template, $_GET['department']);
$generator->generateCertificate(dirname(__FILE__) . "/output/certificates/wash_certificate_" . $_GET['bookingId'] . ".pdf", $_GET['sealOrPlumber'], $_GET['regNumber'], $_GET['regNumberTrailer'], $_GET['performedBy']);

// Determine the generated certificate name
$generatedCertificateName = "wash_certificate_" . $_GET['bookingId'] . ".pdf";

// Return the generated certificate path
$generatedCertificatePath = "output/certificates/wash_certificate_" . $_GET['bookingId'] . ".pdf";

// Upload the certificate to the bucket
$wash_certificate_store->uploadFile($generatedCertificateName, dirname(__FILE__) . '/' . $generatedCertificatePath);

// Delete the local copy of the certificate
//unlink(dirname(__FILE__) . '/' . $generatedCertificatePath);

// Set the status of the booking to completed
$booking = new bookings_o();
$booking->id = $_GET['bookingId'];
$booking->getObjectProperties();
$booking->status->set('completed');
$booking->washCertificateUrl->set('Protected URL');
$booking->washCertificateStatus->set('completed');

// Return the generated certificate object download URL
echo $wash_certificate_store->getWashCertificateDownload($_GET['bookingId']);
// Exit the script
exit;