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

// DEBUG (puoi disattivare dopo i test)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
if (!isset($_SESSION['user'])) {
    header('Location: /smproduce/auth/login.php');
    exit;
}

$role = $_SESSION['user']['role'] ?? 'viewer';
// Se vuoi solo admin:
// if ($role !== 'admin') { http_response_code(403); die('Forbidden'); }

$printerFile = __DIR__ . '/../config/printer_settings.json';

$currentPrinter = '';
if (file_exists($printerFile)) {
    $cfg = json_decode(file_get_contents($printerFile), true);
    if (is_array($cfg) && !empty($cfg['selected_printer'])) {
        $currentPrinter = $cfg['selected_printer'];
    }
}

$msg = null;
$err = null;

// Salvataggio stampante
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['save_printer'])) {
        $name = trim($_POST['printer_name'] ?? '');
        if ($name === '') {
            $err = 'Printer name cannot be empty.';
        } else {
            $data = ['selected_printer' => $name];
            if (!is_dir(dirname($printerFile))) {
                mkdir(dirname($printerFile), 0777, true);
            }
            file_put_contents($printerFile, json_encode($data, JSON_PRETTY_PRINT));
            $currentPrinter = $name;
            $msg = "Printer saved: {$name}";
        }
    }

    // Test print
    if (isset($_POST['test_print'])) {
        if ($currentPrinter === '') {
            $err = 'No printer configured. Save a printer first.';
        } else {
            $testZPL = "^XA
^FO50,50^A0N,40,40^FD TEST LABEL ^FS
^FO50,100^A0N,30,30^FD SM PRODUCE LTD ^FS
^FO50,150^A0N,25,25^FD Printer: " . str_replace('^',' ',$currentPrinter) . " ^FS
^XZ";

            $tmp = tempnam(sys_get_temp_dir(), 'zpl_test_');
            file_put_contents($tmp, $testZPL);

            $printerEsc = str_replace('"', '\"', $currentPrinter);
            $fileEsc    = str_replace('"', '\"', $tmp);
            $cmd = 'powershell -command "Get-Content \"' . $fileEsc . '\" | Out-Printer -Name \"' . $printerEsc . '\""';
            @shell_exec($cmd);

            $msg = "Test label sent to printer: {$currentPrinter}";
        }
    }
}

include('../includes/header.php');
include('../includes/sidebar.php');
?>
<div class="container mt-4">
    <h3>Printer Settings</h3>

    <?php if ($msg): ?>
        <div class="alert alert-success"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>
    <?php if ($err): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($err) ?></div>
    <?php endif; ?>

    <div class="card mb-4">
        <div class="card-header">Select Windows Printer</div>
        <div class="card-body">
            <form method="post" class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">Printer name (Windows spooler)</label>
                    <input type="text" name="printer_name" class="form-control"
                           value="<?= htmlspecialchars($currentPrinter) ?>"
                           placeholder="e.g. Zebra ZT610">
                    <div class="form-text">
                        Use the exact name as shown in Windows &gt; Printers.
                    </div>
                </div>
                <div class="col-12 d-flex gap-2 mt-2">
                    <button class="btn btn-primary" name="save_printer" value="1">Save</button>
                    <button class="btn btn-secondary" name="test_print" value="1">Send Test Label</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include('../includes/footer.php'); ?>
