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

session_start();
if (!isset($_SESSION['user']) || ($_SESSION['user']['role'] ?? '') !== 'admin') {
    http_response_code(403);
    die('Not allowed');
}

$permFile = __DIR__ . '/../config/permissions.json';
if (!file_exists($permFile)) {
    file_put_contents($permFile, json_encode([
        "visible_settings_roles" => ["admin"]
    ], JSON_PRETTY_PRINT));
}
$perms = json_decode(file_get_contents($permFile), true);
$current = $perms['visible_settings_roles'] ?? ['admin'];

$all_roles = ['admin', 'supervisor', 'warehouse', 'viewer'];
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selected = $_POST['roles'] ?? [];
    $selected = array_values(array_intersect($all_roles, $selected));
    if (empty($selected)) {
        $selected = ['admin']; // almeno admin ha accesso
    }
    $perms['visible_settings_roles'] = $selected;
    file_put_contents($permFile, json_encode($perms, JSON_PRETTY_PRINT));
    $current = $selected;
    $msg = 'Permissions updated.';
}

include('../includes/header.php');
include('../includes/sidebar.php');
?>
<div class="container-fluid py-4">
  <h3>Users Permissions</h3>
  <p class="text-muted">Seleziona quali ruoli possono vedere il menu <strong>Settings</strong>.</p>

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

  <form method="post" class="card p-4" style="max-width:480px;">
    <h5 class="mb-3">Ruoli che possono vedere Settings</h5>

    <?php foreach ($all_roles as $r): ?>
      <div class="form-check mb-2">
        <input class="form-check-input" type="checkbox" name="roles[]"
               value="<?= htmlspecialchars($r) ?>"
               id="role_<?= htmlspecialchars($r) ?>"
               <?= in_array($r, $current) ? 'checked' : '' ?>>
        <label class="form-check-label" for="role_<?= htmlspecialchars($r) ?>">
          <?= htmlspecialchars(ucfirst($r)) ?>
        </label>
      </div>
    <?php endforeach; ?>

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

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