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

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

if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

// solo admin può gestire utenti
$current = $_SESSION['user'];
if (($current['role'] ?? '') !== 'admin') {
    echo "<h3 class='m-4 text-danger'>Access denied</h3>";
    exit;
}

$users = get_users();
$available_perms = available_permissions();
$msg = null;
$err = null;

// handle POST: create / update / delete
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save_user') {
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');
        $name     = trim($_POST['name'] ?? '');
        $role     = $_POST['role'] ?? 'viewer';
        $perms    = $_POST['permissions'] ?? [];

        if ($username === '') {
            $err = "Username is required.";
        } else {
            // normalize permissions: keep only known keys
            $perms = array_values(array_intersect(array_keys($available_perms), (array)$perms));

            // find existing user
            $found = false;
            foreach ($users as &$u) {
                if ($u['username'] === $username) {
                    $found = true;
                    if ($password !== '') {
                        $u['password'] = $password; // plain text as per original design
                    }
                    $u['name']   = $name;
                    $u['role']   = $role;
                    $u['active'] = isset($_POST['active']);
                    $u['permissions'] = $perms;
                    break;
                }
            }
            unset($u);

            if (!$found) {
                $users[] = [
                    'username' => $username,
                    'password' => $password,
                    'name'     => $name,
                    'role'     => $role,
                    'active'   => isset($_POST['active']),
                    'permissions' => $perms
                ];
            }

            save_users($users);
            $msg = $found ? "User updated." : "User created.";
        }
    }

    if ($action === 'delete_user') {
        $username = $_POST['username'] ?? '';
        $users = array_values(array_filter($users, function($u) use ($username) {
            return $u['username'] !== $username;
        }));
        save_users($users);
        $msg = "User deleted.";
    }
}

// reload users after any change
$users = get_users();

include '../includes/header.php';
include '../includes/sidebar.php';
?>
<div class="container-fluid">
  <h1 class="mt-4 mb-3">👤 Users management</h1>
  <p class="text-muted mb-4">Create, edit and assign permissions to users.</p>

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

  <div class="row g-4">
    <div class="col-lg-5">
      <div class="card shadow-sm border-0">
        <div class="card-header bg-white">
          <strong>Add / Edit user</strong>
        </div>
        <div class="card-body">
          <form method="post">
            <input type="hidden" name="action" value="save_user">

            <div class="mb-3">
              <label class="form-label">Username</label>
              <input type="text" name="username" class="form-control" required>
              <div class="form-text">If the username already exists, the user will be updated.</div>
            </div>

            <div class="mb-3">
              <label class="form-label">Password</label>
              <input type="text" name="password" class="form-control">
              <div class="form-text">Leave empty to keep the current password.</div>
            </div>

            <div class="mb-3">
              <label class="form-label">Name</label>
              <input type="text" name="name" class="form-control">
            </div>

            <div class="mb-3">
              <label class="form-label">Role</label>
              <select name="role" class="form-select">
                <option value="admin">Admin</option>
                <option value="warehouse">Warehouse</option>
                <option value="viewer">Viewer</option>
              </select>
            </div>

            <div class="mb-3">
              <label class="form-label">Active</label><br>
              <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" name="active" id="activeSwitch" checked>
                <label class="form-check-label" for="activeSwitch">User is active</label>
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label">Permissions</label>
              <div class="row">
                <?php foreach ($available_perms as $key => $label): ?>
                  <div class="col-6">
                    <div class="form-check">
                      <input class="form-check-input" type="checkbox" name="permissions[]" value="<?php echo htmlspecialchars($key); ?>" id="perm_<?php echo htmlspecialchars($key); ?>">
                      <label class="form-check-label" for="perm_<?php echo htmlspecialchars($key); ?>">
                        <?php echo htmlspecialchars($label); ?>
                      </label>
                    </div>
                  </div>
                <?php endforeach; ?>
              </div>
              <div class="form-text">Admins have all permissions regardless of selection.</div>
            </div>

            <button class="btn btn-primary">Save user</button>
          </form>
        </div>
      </div>
    </div>

    <div class="col-lg-7">
      <div class="card shadow-sm border-0">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
          <strong>Existing users</strong>
        </div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-striped table-hover mb-0 align-middle">
              <thead class="table-light">
                <tr>
                  <th>Username</th>
                  <th>Name</th>
                  <th>Role</th>
                  <th>Active</th>
                  <th>Permissions</th>
                  <th style="width:80px;">Delete</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($users as $u): ?>
                  <tr>
                    <td><?php echo htmlspecialchars($u['username']); ?></td>
                    <td><?php echo htmlspecialchars($u['name'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($u['role'] ?? ''); ?></td>
                    <td>
                      <?php echo !isset($u['active']) || $u['active'] ? '✅' : '❌'; ?>
                    </td>
                    <td>
                      <?php
                        $perms = $u['permissions'] ?? [];
                        if (($u['role'] ?? '') === 'admin') {
                            echo '<span class="badge bg-success">ALL</span>';
                        } elseif (empty($perms)) {
                            echo '<span class="text-muted">None</span>';
                        } else {
                            $labels = [];
                            foreach ($perms as $p) {
                                $labels[] = htmlspecialchars($available_perms[$p] ?? $p);
                            }
                            echo implode(', ', $labels);
                        }
                      ?>
                    </td>
                    <td>
                      <?php if (($u['username'] ?? '') !== 'admin'): ?>
                      <form method="post" onsubmit="return confirm('Delete user <?php echo htmlspecialchars($u['username']); ?>?');">
                        <input type="hidden" name="action" value="delete_user">
                        <input type="hidden" name="username" value="<?php echo htmlspecialchars($u['username']); ?>">
                        <button class="btn btn-sm btn-outline-danger">Delete</button>
                      </form>
                      <?php else: ?>
                        <span class="text-muted">—</span>
                      <?php endif; ?>
                    </td>
                  </tr>
                <?php endforeach; ?>
                <?php if (empty($users)): ?>
                  <tr><td colspan="6" class="text-center text-muted py-4">No users defined.</td></tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

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