<?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, Authorization, X-Customer-Number, X-Release-Trace, X-Release-Channel, X-Frontend-Version, Cache-Control, Pragma");

// 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;
}

http_response_code(410);
echo 'Booking completion must be completed through POS desktop or mobile steps.';
exit;
