#!/usr/bin/php -q
<?php /** @noinspection PhpUnused @noinspection DuplicatedCode */

// we only support 30min
ini_set("max_execution_time", "1800");

// only register_shutdown_function() allows access to fatal script errors; therefore
// create our own shutdown function to catch those out of memory errors
register_shutdown_function('fatal_error_handler');

// the shutdown handler
function fatal_error_handler()
{
    // check for last error
    $last_error = error_get_last();
    if (isset($last_error) && is_array($last_error) && $last_error['type'] === E_ERROR)
    {
        // fatal error
        header('WWW-Authenticate: Basic realm="mlu-recordum airfamily"');
        header('HTTP/1.0 500 Internal Server Error');
        echo $last_error['message'];
    }
}

// Debug Mode for IDE runtime debugger
const SCRIPTDEBUG = 0;
const DEFAULTVALUES = 0;
// is config->debug set
$GLOBALS['IS_DEBUG'] = 0;

// change to web server root to load scripts
chdir("/var/www");
// db access; uses config file
require_once "src/foundation/class.common.php";
// access global config
require_once "src/class/class.globalconfig.php";
// converter
require_once "libs/phpexcel/Classes/PHPExcel/IOFactory.php";

/**
 * @noinspection DuplicatedCode
 */
function init()
{
    $oConf = new GlobalConfig('en');
    $settings = $oConf->GetParams(array(179));
    $GLOBALS['IS_DEBUG'] = isset($settings[179]) ? intval($settings[179]['str_val']) : 0;
}

// helpers
function writeError($id, $msg)
{
    fwrite($GLOBALS['stderr'], "ERROR: (" . $id . ") " . $msg . "\n");
}

function writeUsage()
{
    fwrite($GLOBALS['stdout'], "Usage: " . $GLOBALS['argv'][0] . " filename\n\tconnection.list\n");
}

class CSVToExcelConverter
{
    /**
     * Read given csv file and write all rows to given xls file
     *
     * @param string $csv_file Resource path of the csv file
     * @param string $xls_file Resource path of the Excel file
     * @param string $csv_enc Encoding of the csv file, use utf8 if null
     *
     * @throws Exception
     */
    public static function convert($csv_file, $xls_file, $csv_enc = 'UTF-8')
    {
        $nl = "\n";

        // set cache
        $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
        // Use PCLZip rather than ZipArchive to read the Excel2007 OfficeOpenXML file
        PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);

        if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
        {
            $method = PHPExcel_CachedObjectStorageFactory::getCacheStorageMethod();
            var_dump($method);
        }

        /**
         * @var $objReader PHPExcel_Reader_CSV
         */
        $objReader = PHPExcel_IOFactory::createReader('CSV')->setDelimiter(',')
            ->setEnclosure('"')
            ->setSheetIndex(0);
        $objReader->setReadDataOnly(true);
        $objReader->setInputEncoding($csv_enc);

        $callStartTime = 0.0;
        if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
        {
            echo date('H:i:s'), " Read from CSV format", $nl;
            $callStartTime = microtime(true);
        }

        $objPHPExcelFromCSV = $objReader->load($csv_file);

        if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
        {
            $callEndTime = microtime(true);
            $callTime = $callEndTime - $callStartTime;
            echo 'Call time to load Workbook was ', sprintf('%.4f', $callTime), " seconds", $nl;
            echo date('H:i:s'), ' Current memory usage: ', (memory_get_usage(true) / 1024 / 1024), " MB", $nl;
            echo date('H:i:s'), " Write to Excel2007 format", $nl;
            $callStartTime = microtime(true);
        }

        /**
         * @var $objWriter2007 PHPExcel_Writer_Excel2007
         */
        $objWriter2007 = PHPExcel_IOFactory::createWriter($objPHPExcelFromCSV, 'Excel2007');
        $objWriter2007->setPreCalculateFormulas(false);

        if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
        {
            $callEndTime = microtime(true);
            $callTime = $callEndTime - $callStartTime;
            echo 'Call time to createWriter() was ', sprintf('%.4f', $callTime), " seconds", $nl;
            $callStartTime = microtime(true);
        }

        $objWriter2007->save($xls_file);

        if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
        {
            $callEndTime = microtime(true);
            $callTime = $callEndTime - $callStartTime;
            echo 'Call time to write Workbook was ', sprintf('%.4f', $callTime), " seconds", $nl;
            echo date('H:i:s'), ' Current memory usage: ', (memory_get_usage(true) / 1024 / 1024), " MB", $nl;
        }
    }
}

function doCreate($name)
{
    $nl = "\n";

    try
    {
        $path_parts = pathinfo($name);
        $file_name = $path_parts['dirname'] . "/" . $path_parts['filename'];

        $callStartTime = 0.0;
        if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
        {
            $callStartTime = microtime(true);
        }

        CSVToExcelConverter::convert($file_name . '.csv', $file_name . '.xlsx');

        if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
        {
            $callEndTime = microtime(true);
            $callTime = $callEndTime - $callStartTime;
            echo "Call time to convert Workbook was " . sprintf('%.4f', $callTime) . " seconds" . $nl;
        }

    } catch (Exception $e)
    {
        writeError(1, "Error creating: " . $e->getMessage());
        exit(1);
    }
}

function main($argc, $argv)
{
    if (SCRIPTDEBUG && DEFAULTVALUES)
    {
        doCreate("20220907_165228_2014_00ts1_201400ts1_19878.csv");
        exit(0);
    } else
    {
        if ($argc < 2)
        {
            writeUsage();
            writeError(2, "Wrong or missing command line parameters");
            exit(2);
        }
        doCreate($argv[1]);
        exit(0);
    }
}

// supported STDIN/OUT/ERR syntax for php version 4.3 till 5.3
$stderr = fopen('php://stderr', 'w');
$stdout = fopen('php://stdout', 'w');
// fetch our debug flag, ...
init();
// $argc, $argv are filled in by the CLI engine and defined as globals
main($argc, $argv);
