<?php
require_once __DIR__ . '/../config/user_functions.php';

session_start();
if (!isset($_SESSION['user']) || ($_SESSION['user']['role'] ?? '') !== 'admin') {
    die("Not allowed");
}

$printerFile = __DIR__ . '/../config/printer_settings.json';
if (!file_exists($printerFile)) {
    die("Printer settings not found.");
}
$printerConfig = json_decode(file_get_contents($printerFile), true);
$printer = $printerConfig['selected_printer'] ?? "";

if (!$printer) {
    die("No printer selected.");
}

// File temporaneo da stampare
$baseDir = __DIR__ . '/../temp_reports';
if (!is_dir($baseDir)) mkdir($baseDir, 0777, true);
$tmp = $baseDir . "/test_print.txt";
file_put_contents($tmp, "SM Produce LTD - Test Print\nDate: " . date("Y-m-d H:i:s"));

// Comando stampa base (usa la default printer di Windows)
$psFile = str_replace("'", "''", $tmp);
$cmd = 'powershell -command "Get-Content -Path '''.$psFile."'' | Out-Printer -Name ''".$printer."''"";
shell_exec($cmd);

echo "Test print sent to: " . htmlspecialchars($printer);
