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

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

if (!user_has_permission('settings')) {
    http_response_code(403);
    include '../includes/header.php';
    include '../includes/sidebar.php';
    echo "<div class='container-fluid py-4'><h3 class='text-danger'>Access denied</h3></div>";
    include '../includes/footer.php';
    exit;
}

$printerFile   = __DIR__ . '/../config/printer_settings.json';
$printerConfig = file_exists($printerFile) ? (json_decode(file_get_contents($printerFile), true) ?: []) : [];

function smp_get_printers_windows_orders() {
    $printers = [];
    $out = shell_exec('powershell -command "Get-Printer | Select-Object -ExpandProperty Name"');
    if ($out) {
        foreach (explode("\n", $out) as $line) {
            $line = trim($line);
            if ($line !== '' && $line !== 'Name') {
                $printers[] = $line;
            }
        }
    }
    return $printers;
}

$printers = smp_get_printers_windows_orders();
$msg = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save';

    if ($action === 'save') {
        $printerConfig['orders_printer']    = $_POST['orders_printer'] ?? '';
        $printerConfig['auto_print_orders'] = isset($_POST['auto_print_orders']);
        file_put_contents($printerFile, json_encode($printerConfig, JSON_PRETTY_PRINT));
        $msg = "Orders printer settings saved.";
    } elseif ($action === 'test_order') {
        $printer = $printerConfig['orders_printer'] ?? '';
        if ($printer) {
            $tmp = tempnam(sys_get_temp_dir(), "ord");
            $content  = "SM PRODUCE - ORDERS TEST PRINT\r\n";
            $content .= "Printer: {$printer}\r\n";
            $content .= "Date: " . date('Y-m-d H:i:s') . "\r\n";
            $content .= "This is a test print for orders.\r\n";
            file_put_contents($tmp, $content);
            $ps  = 'Get-Content -Path "' . $tmp . '" | Out-Printer -Name "' . $printer . '"';
            $cmd = 'powershell -command "' . $ps . '"';
            @shell_exec($cmd);
            $msg = "Test order print sent to orders printer.";
        } else {
            $msg = "No orders printer selected.";
        }
    }
}

include '../includes/header.php';
include '../includes/sidebar.php';
?>
<div class="container-fluid py-4">
  <h3 class="mb-3">Orders Printer Settings</h3>
  <p class="text-muted mb-3">Select which printer to use for orders and configure automatic print.</p>

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

  <form method="post" class="card p-4 mb-4" style="max-width:520px;">
    <input type="hidden" name="action" value="save">

    <div class="mb-3">
      <label class="form-label">Orders Printer</label>
      <select name="orders_printer" class="form-select">
        <option value="">-- Select printer --</option>
        <?php foreach ($printers as $p): ?>
          <option value="<?= htmlspecialchars($p) ?>"
            <?= (($printerConfig['orders_printer'] ?? '') === $p) ? 'selected' : '' ?>>
            <?= htmlspecialchars($p) ?>
          </option>
        <?php endforeach; ?>
      </select>
      <div class="form-text">This printer will be used for printing orders.</div>
    </div>

    <div class="form-check mb-3">
      <input class="form-check-input" type="checkbox" id="auto_print_orders"
             name="auto_print_orders" <?= !empty($printerConfig['auto_print_orders']) ? 'checked' : '' ?>>
      <label class="form-check-label" for="auto_print_orders">
        Print order automatically right after saving
      </label>
    </div>

    <button class="btn btn-primary">Save Orders Printer</button>
  </form>

  <form method="post" class="card p-4" style="max-width:520px;">
    <input type="hidden" name="action" value="test_order">
    <h5>Test Order Print</h5>
    <p class="text-muted">Send a simple test page to the configured orders printer.</p>
    <button class="btn btn-outline-success">Print Test Order</button>
  </form>
</div>
<?php include '../includes/footer.php'; ?>
