<?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;
}

include '../includes/header.php';
include '../includes/sidebar.php'];

// =============================
// LOAD / CREATE SETTINGS JSON
// =============================
$settingsFile = __DIR__ . '/../config/printer_settings.json';

if (!file_exists($settingsFile)) {
    file_put_contents($settingsFile, json_encode([], JSON_PRETTY_PRINT));
}

$cfg = json_decode(file_get_contents($settingsFile), true);
if (!is_array($cfg)) $cfg = [];

// =============================
// DETECT INSTALLED PRINTERS
// =============================
$installedPrinters = [];

$cmd = 'wmic printer get name';
$out = shell_exec($cmd);

if ($out) {
    $lines = explode("\n", trim($out));
    foreach ($lines as $i => $line) {
        if ($i === 0) continue; // skip header
        $p = trim($line);
        if ($p !== "") $installedPrinters[] = $p;
    }
}

if (empty($installedPrinters)) {
    $installedPrinters = ["No printers detected"];
}

// =============================
// ZEBRA DIAGNOSTICS ENGINE
// =============================
function zebra_query($ip, $cmd) {
    $socket = @fsockopen($ip, 9100, $errno, $errstr, 1.2);
    if (!$socket) return false;

    fwrite($socket, $cmd);
    usleep(160000);

    $response = "";
    while (!feof($socket)) {
        $response .= fgets($socket, 1024);
    }
    fclose($socket);
    return trim($response);
}

$zebra_status = null;
$zebra_info   = null;

if (isset($_GET["zebra_test"])) {
    $ip = $_GET["zebra_test"];

    // Ping
    $ping = shell_exec("ping -n 1 $ip");
    $ping_ok = (stripos($ping, "TTL=") !== false);

    // Port test
    $port_ok = false;
    $fp = @fsockopen($ip, 9100, $errno, $errstr, 0.8);
    if ($fp) { $port_ok = true; fclose($fp); }

    // Model
    $info = zebra_query($ip, "~HI");
    // Config dump
    $cfgDump = zebra_query($ip, "^XA^HH^XZ");

    $zebra_status = [
        "ping"   => $ping_ok,
        "port"   => $port_ok,
        "info"   => $info ?: "No response",
        "config" => $cfgDump ?: "No config response",
    ];
}

// =============================
// SAVE CONFIG
// =============================
$message = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $cfg["printer_fullbins"]   = $_POST["printer_fullbins"] ?? "";
    $cfg["printer_bin_group"]  = $_POST["printer_bin_group"] ?? "";
    $cfg["printer_reports"]    = $_POST["printer_reports"] ?? "";
    $cfg["printer_orders"]     = $_POST["printer_orders"] ?? "";
    $cfg["zebra_fullbin_ip"]   = $_POST["zebra_fullbin_ip"] ?? "";

    file_put_contents($settingsFile, json_encode($cfg, JSON_PRETTY_PRINT));

    $message = "Printer settings saved successfully!";
}
?>

<div class="container-fluid py-4" style="max-width:850px">
    <h3 class="mb-3">Printer Settings</h3>

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

<form method="post" class="card p-4 mb-4">

    <h5 class="mb-3">🖨 Full Bin Label Printer</h5>
    <select name="printer_fullbins" class="form-select mb-3">
        <?php foreach ($installedPrinters as $p): ?>
            <option value="<?= htmlspecialchars($p) ?>"
                <?= ($cfg["printer_fullbins"] ?? "") == $p ? "selected" : "" ?>>
                <?= htmlspecialchars($p) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <label class="form-label fw-semibold">Zebra IP address</label>
    <input type="text" class="form-control mb-3"
           name="zebra_fullbin_ip"
           value="<?= htmlspecialchars($cfg["zebra_fullbin_ip"] ?? "") ?>"
           placeholder="Example: 192.168.1.50">

    <?php if (!empty($cfg["zebra_fullbin_ip"])): ?>
        <a href="?zebra_test=<?= $cfg["zebra_fullbin_ip"] ?>" class="btn btn-outline-primary mb-3">
            🔍 Test Zebra Printer
        </a>
    <?php endif; ?>

    <h5 class="mt-4 mb-3">📦 Group Bins Printer</h5>
    <select name="printer_bin_group" class="form-select mb-3">
        <?php foreach ($installedPrinters as $p): ?>
            <option value="<?= htmlspecialchars($p) ?>"
                <?= ($cfg["printer_bin_group"] ?? "") == $p ? "selected" : "" ?>>
                <?= htmlspecialchars($p) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <h5 class="mt-4 mb-3">📑 Reports Printer</h5>
    <select name="printer_reports" class="form-select mb-3">
        <?php foreach ($installedPrinters as $p): ?>
            <option value="<?= htmlspecialchars($p) ?>"
                <?= ($cfg["printer_reports"] ?? "") == $p ? "selected" : "" ?>>
                <?= htmlspecialchars($p) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <h5 class="mt-4 mb-3">🧾 Orders Printer</h5>
    <select name="printer_orders" class="form-select mb-3">
        <?php foreach ($installedPrinters as $p): ?>
            <option value="<?= htmlspecialchars($p) ?>"
                <?= ($cfg["printer_orders"] ?? "") == $p ? "selected" : "" ?>>
                <?= htmlspecialchars($p) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <button class="btn btn-primary mt-3">Save Settings</button>
</form>


<!-- ========================= -->
<!-- ZEBRA DIAGNOSTICS PANEL -->
<!-- ========================= -->

<?php if ($zebra_status): ?>
<div class="card p-4 border-primary">

    <h4>🖨 Zebra Diagnostic</h4>
    <p class="text-muted">IP: <?= htmlspecialchars($_GET["zebra_test"]) ?></p>

    <ul class="list-group mb-3">

        <li class="list-group-item">
            <strong>Ping:</strong>
            <?= $zebra_status["ping"] ? "🟢 Reachable" : "🔴 No response" ?>
        </li>

        <li class="list-group-item">
            <strong>Port 9100:</strong>
            <?= $zebra_status["port"] ? "🟢 Open" : "🔴 Closed" ?>
        </li>

        <li class="list-group-item">
            <strong>Printer Info (~HI):</strong><br>
            <pre><?= htmlspecialchars($zebra_status["info"]) ?></pre>
        </li>

        <li class="list-group-item">
            <strong>Configuration (^HH):</strong><br>
            <pre><?= htmlspecialchars($zebra_status["config"]) ?></pre>
        </li>

    </ul>
</div>
<?php endif; ?>

</div>

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