<?php
/**
 * Procedure Class
 *
 * @version     1.0.$Revision:$
 * @version     SVN: $Id:$
 * @package     bplan-base/globals
 * @subpackage  Procedures
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 * @copyright   Copyright (C) 2025, 2026 bplan-solutions GmbH & Co. KG <https://www.bplan-solutions.de/>
 * /Δ\
 */

namespace BplanBase\Globals\Services;


use BplanBase\Globals\Models\Tenant;
use BplanBase\Globals\Support\ModuleStorage;
use BplanModules\VisitorManagement\Repositories\AppointmentRepository;
use BplanModules\VisitorManagement\Repositories\EmployeeRepository;
use BplanModules\VisitorManagement\Repositories\VisitorRepository;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Storage;


/**
 * Procedure Class
 *
 * @version     1.0.0 / 2026-05-06
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
class FillerService
{


/* +++ TRAITS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS CONSTANTS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ OBJECT MEMBERS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS MEMBERS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ OBJECT METHODS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++ */


    /**
     * Create the print-file
     *
     * @param       array $printData
     *
     * @return      string
     *
     * @version     1.0.0 / 2026-05-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function createPrintFile(array $printData, string $dataFileName, $printFileNamePrefix = null): string
    {
        // $Tenant = Tenant::current();

        //$ModuleStorage = new ModuleStorage(false, 'visit', $Tenant->id);
        $ModuleStorage = new ModuleStorage(false, 'visit');

        $config = config('globals.filler');

        if($config['binary'] === null) {
            throw new Exception('No binary configured');

        } elseif (file_exists($config['binary']) === false) {
            throw new Exception('Could not find binary');

        } elseif (is_executable($config['binary']) === false) {
            throw new Exception('['.$config['binary'].'] is not executable');
        }
        $binaryPath = dirname($config['binary']);
        $executable = basename($config['binary']);
        $iniFile    = $binaryPath.'/InitialCustomer/'.$config['ini-file-name'];

        if (file_exists($iniFile) === false) {
            throw new Exception('Could not find ini file '.$iniFile);
        }
        /*
        **  Alle Verzeichnisnamen und Pfade sind für die Speicherung der Queue-Datei (Json). Lediglich der
        **  Verzeichnisname in "$dirName" wird auch für die Ausgabedateien des Fillers verwendet und muss
        **  in der ini-Datei genutzt werden. */
        $dirName = 'filler';
        $subPath = 'queue/'.$dirName;

        $targetPath = $ModuleStorage->path($subPath);

        if ($ModuleStorage->exists($subPath) === false) {
            if (mkdir($targetPath, 0777, true) === false) {
                throw new Exception('Could not create target directory');
            }
        } elseif (is_writable($targetPath) === false) {
            throw new Exception('Target directory is not writable');
        }
        $fileName = $dataFileName.'.json';
        $queueFile = $ModuleStorage->path($subPath).'/'.$fileName;

        if ($ModuleStorage->put($subPath.'/'.$fileName, json_encode($printData, JSON_PRETTY_PRINT)) === false) {
            throw new Exception('Could not create file');
        }
        $command = '"'.$executable.'" '.$config['ini-file-name'].' "'.$queueFile.'"';

        $cwd = getcwd();
        /*
        **  Ins Verzeichnis des Layouters wechseln. */
        chdir($binaryPath);

        ob_start(); {
            $lastOutputLine = system($command, $resultCode);

        } ob_end_clean();

        chdir($cwd);

        if ($resultCode !== false) {
            switch ($resultCode) {
                case 1:
                    throw new Exception('Error while creating print file: error code '.$resultCode.', '.$lastOutputLine);
                    break;

                case 0:
                    if(!empty($lastOutputLine)) {
                        throw new Exception('Error while creating print file: error code '.$resultCode.', '.$lastOutputLine);
                    }
                    // no break
                default:
                    // Success
            }
        }
        try {
            // unlink($queueFile);

        } catch (\Throwable $th) {
            //
        }
        /*
        **  Dateien für das Ergebnis zusammenstellen. */
        $PublicStorage = new ModuleStorage(true, 'visit', false);

        $printFileName = $dataFileName.'_'.$config['output-file-name'].'.'.$config['output-file-extension'];

        return $PublicStorage->url($dirName.'/'.$printFileName);

    } // createPrintFile()


/* +++ CLASS METHODS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++++ */


} // class FillerService extends Procedure {}
