<?php

require __DIR__.'/../src/init.php';
global $globalContext;

\engine\http\RequestHandler::resolveAndDispatch(only_set_project: true);

$name = $_GET['name'] ?? '';
$theme = $_GET['theme'] ?? '';

if ($theme != 'light' && $theme != 'dark') {
    http_response_code(403);
    exit;
}

if (!isDev() || !$name || !file_exists($path = APP_ROOT.'/public/'.$globalContext->project.'/scss/'.$name.'@'.$theme.'.scss')) {
    logDebug($path.' not found');
    http_response_code(403);
    exit;
}

$cmd = 'sassc -t expanded '.escapeshellarg($path);
$descriptorspec = [
   0 => ['pipe', 'r'], // stdin
   1 => ['pipe', 'w'], // stdout
   2 => ['pipe', 'w'], // stderr
];

$process = proc_open($cmd, $descriptorspec, $pipes, APP_ROOT);
if (!is_resource($process)) {
    http_response_code(500);
    logError('could not open sassc process');
    exit;
}

$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);

$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);

$code = proc_close($process);
if ($code) {
    http_response_code(500);
    logError('sassc('.$path.') returned '.$code);
    logError($stderr);
    exit;
}

header('Content-Type: text/css');
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

echo $stdout;
