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

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

$user = $_SESSION['user'] ?? null;
$role = $user['role'] ?? 'viewer';
if ($role !== 'admin') {
    die("You do not have permission to view this page.");
}

$serviceName = 'KeyenceTCPListener';
$actionMsg = '';

function getServiceStatus($serviceName) {
    $output = [];
    @exec('sc query "'.$serviceName.'" 2>&1', $output, $ret);
    $text = implode("\n", $output);
    $state = 'UNKNOWN';
    if (preg_match('/STATE\s*:\s*\d+\s+(\w+)/', $text, $m)) {
        $state = $m[1];
    }
    return [$state, $text];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if (in_array($action, ['start','stop','restart'], true)) {
        if ($action === 'restart') {
            @exec('sc stop "'.$serviceName.'" 2>&1', $outStop, $retStop);
            @exec('sc start "'.$serviceName.'" 2>&1', $outStart, $retStart);
            $actionMsg = 'Restart command sent.';
        } elseif ($action === 'start') {
            @exec('sc start "'.$serviceName.'" 2>&1', $outStart, $retStart);
            $actionMsg = 'Start command sent.';
        } elseif ($action === 'stop') {
            @exec('sc stop "'.$serviceName.'" 2>&1', $outStop, $retStop);
            $actionMsg = 'Stop command sent.';
        }
    }
}

list($state, $rawStatus) = getServiceStatus($serviceName);

// derive simple label
$stateLabel = $state;
$badgeClass = 'secondary';
if ($state === 'RUNNING') { $badgeClass = 'success'; }
elseif ($state === 'STOPPED') { $badgeClass = 'danger'; }
elseif ($state === 'PAUSED') { $badgeClass = 'warning'; }

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

<div class="container-fluid mt-3">
  <div class="row">
    <div class="col-md-6">
      <div class="card shadow-sm mb-3">
        <div class="card-header d-flex justify-content-between align-items-center">
          <span>Keyence Listener Service</span>
          <span class="badge bg-<?= $badgeClass ?>"><?= htmlspecialchars($stateLabel) ?></span>
        </div>
        <div class="card-body">
          <?php if ($actionMsg): ?>
            <div class="alert alert-info py-1"><?= htmlspecialchars($actionMsg) ?></div>
          <?php endif; ?>
          <p class="mb-2">Service name: <code><?= htmlspecialchars($serviceName) ?></code></p>
          <form method="post" class="d-flex gap-2">
            <button name="action" value="start" class="btn btn-sm btn-success">Start</button>
            <button name="action" value="stop" class="btn btn-sm btn-danger">Stop</button>
            <button name="action" value="restart" class="btn btn-sm btn-warning">Restart</button>
          </form>
        </div>
      </div>
    </div>

    <div class="col-md-6">
      <div class="card shadow-sm mb-3">
        <div class="card-header">
          Raw Service Status
        </div>
        <div class="card-body">
          <pre class="small mb-0"><?php echo htmlspecialchars($rawStatus); ?></pre>
        </div>
      </div>
    </div>
  </div>
</div>

