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

if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/../config/users_local.php';
require_once __DIR__ . '/../config/orders_lib.php';

if (!user_has_permission('orders')) {
    http_response_code(403);
    echo "Access denied";
    exit;
}

$id = (int)($_GET['id'] ?? 0);
$orders = load_orders();
list($idx, $order) = find_order_by_id($orders, $id);
if ($order === null) {
    echo "Order not found.";
    exit;
}

// get orders printer from config
$printerFile = __DIR__ . '/../config/printer_settings.json';
$printerCfg = file_exists($printerFile) ? (json_decode(file_get_contents($printerFile), true) ?: []) : [];
$printer = $printerCfg['orders_printer'] ?? '';

if ($printer === '') {
    echo "<p>No orders printer configured. Go to Settings → Orders Printer Settings.</p>";
    echo "<p><a href='orders.php'>Back to orders</a></p>";
    exit;
}

// build simple text content for printing
$lines = [];
$lines[] = "SM PRODUCE - ORDER #" . (int)$order['id'];
$lines[] = str_repeat("=", 40);
$lines[] = "PO: " . ($order['po'] ?? '');
$lines[] = "Client: " . ($order['client'] ?? '');
$lines[] = "Ship date: " . ($order['ship_date'] ?? '');
$lines[] = "Product: " . ($order['product'] ?? '');
$lines[] = "Quantity: " . (int)($order['qty'] ?? 0);
$lines[] = "Notes: " . ($order['notes'] ?? '');
$lines[] = "";
$lines[] = "Printed at: " . date('Y-m-d H:i:s');

$tmp = tempnam(sys_get_temp_dir(), "ord");
file_put_contents($tmp, implode("\r\n", $lines));

// send via Windows spooler
$ps  = 'Get-Content -Path "' . $tmp . '" | Out-Printer -Name "' . $printer . '"';
$cmd = 'powershell -command "' . $ps . '"';
@shell_exec($cmd);

include '../includes/header.php';
include '../includes/sidebar.php';
?>
<div class="container-fluid py-4">
  <h3>Order #<?= (int)$order['id'] ?> sent to printer</h3>
  <p>Printer: <strong><?= htmlspecialchars($printer) ?></strong></p>
  <p>
    PO: <?= htmlspecialchars($order['po'] ?? '') ?><br>
    Client: <?= htmlspecialchars($order['client'] ?? '') ?><br>
    Ship date: <?= htmlspecialchars($order['ship_date'] ?? '') ?><br>
    Product: <?= htmlspecialchars($order['product'] ?? '') ?><br>
    Quantity: <?= (int)($order['qty'] ?? 0) ?>
  </p>

  <a href="orders.php" class="btn btn-primary mt-3">Back to Orders</a>
</div>
<?php include '../includes/footer.php'; ?>
