<?php
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);

$middleware = [
    'xprt-export' => 'xprt-export',
    'xprt-import' => 'xprt-import',
    'pim-import' => 'pim-import'
];
$tasks = [
    'order-export' => 'app:export-order',
    'voucher-export' => 'app:export-sample-voucher',
    'order-return' => 'app:request-return-product',
    'get-log' => 'get-log'
];

$mid = $_GET['middleware'];
$job = $_GET['task'];
$params = $_GET['params'] ?? [];

if(empty($mid) || !$middleware[$mid]) {
    echo ('No middleware found');
    die;
}
if(empty($job) || !$tasks[$job]) {
    echo('No task found');
    die;
}

if ($job == 'get-log') { // --- only for getting logs
    $logPath = __DIR__ . '/var/log/' . $middleware[$mid] . '/' . 'log-' . date('Y-m-d') . '.log';
//    $logPath = __DIR__ . '/' . $middleware[$mid] . '/var/log/' . 'virt-' . date('Y-m-d') . '.log'; // for local only

    try {
        $lines = readLastLines($logPath, 100);
    } catch (Exception $e) {
        echo "Log file not found.";
        die;
    }
    $echoLineNumbers = false;
    $lineNum = 1;
    foreach ($lines as $line) {
        // --- $key does not work here, as iterator has file line numbers filled in as keys
        if ($echoLineNumbers) {
            echo $lineNum  . '.&nbsp;&nbsp;';
        }
        echo $line . '<br>';
        $lineNum++;
    }
    die; // exit when log is read
} else {
    $rawPost = file_get_contents('php://input');
    if ($rawPost && $rawPost != '') {
        $postParams = json_decode(base64_decode($rawPost), true);
        $params = array_merge($params, $postParams);
    }
    echo "Running command... ";
    $cmd = 'php ./' . $middleware[$mid] . '/bin/console ' . $tasks[$job] . ' ' . implode($params, ' ');
    echo shell_exec($cmd);
    echo "Done";
}

function readLastLines($filename, $num, $reverse = false) {
    $file = new \SplFileObject($filename, 'r');
    $file->seek(PHP_INT_MAX);
    $lastLine = $file->key();
    $readLast = $lastLine <= $num ? 0 : $lastLine - $num;
    $lines = new \LimitIterator($file, $readLast, $lastLine);
    $arr = iterator_to_array($lines);
    if($reverse) $arr = array_reverse($arr);
    return $arr;
}

?>
