<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
auth_require_login();
$pdo = crm_pdo();
$page_title = 'Users';

if (!gp_can_manage_project_access($pdo)) {
    http_response_code(403);
    exit('Access denied.');
}

$ok = '';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    $action = trim((string)($_POST['action'] ?? 'create'));

    if ($action === 'create') {
        $username = trim((string)($_POST['username'] ?? ''));
        $email = trim((string)($_POST['email'] ?? ''));
        $password = (string)($_POST['password'] ?? '');
        $role = trim((string)($_POST['role'] ?? 'secretary'));

        if ($username === '') $errors[] = 'Username is required.';
        if ($password === '') $errors[] = 'Password is required.';
        if (!in_array($role, ['admin','manager','secretary','employee','partner','customer'], true)) $errors[] = 'Invalid role.';

        if (!$errors) {
            $stmt = $pdo->prepare("INSERT INTO users (username, email, password_hash, role, is_active) VALUES (:username, :email, :password_hash, :role, 1)");
            $stmt->execute([
                ':username' => $username,
                ':email' => $email !== '' ? $email : null,
                ':password_hash' => password_hash($password, PASSWORD_DEFAULT),
                ':role' => $role,
            ]);
            $newUserId = (int)$pdo->lastInsertId();
            gp_log_action($pdo, 'USER_CREATE', 'user', $newUserId, "Created new user: $username ($role)");
            $ok = 'User created.';
        }
    }
}

$users = $pdo->query("SELECT id, username, email, role, is_active FROM users ORDER BY id DESC")->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title"><h1>User Management</h1><span>Create admins, managers, and secretaries</span></div>
</div>

<div class="grid-2">
  <div class="card">
    <?php if ($ok !== ''): ?><div class="alert-success"><?php echo h($ok); ?></div><?php endif; ?>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>

    <form method="post">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="action" value="create">
      <div class="form-grid">
        <div class="form-group"><label>Username</label><input type="text" name="username"></div>
        <div class="form-group"><label>Email</label><input type="email" name="email"></div>
        <div class="form-group"><label>Password</label><input type="text" name="password"></div>
        <div class="form-group">
          <label>Role</label>
          <select name="role">
            <option value="secretary">Secretary</option>
            <option value="manager">Manager</option>
            <option value="admin">Admin</option>
            <option value="employee">Employee</option>
            <option value="partner">Partner</option>
            <option value="customer">Customer</option>
          </select>
        </div>
      </div>
      <div class="form-actions"><button class="btn btn-primary" type="submit">Create user</button></div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Users</h1><span>System accounts</span></div>
    <div class="table-responsive">
      <table class="table">
        <thead><tr><th>ID</th><th>Username</th><th>Email</th><th>Role</th><th>Active</th></tr></thead>
        <tbody>
          <?php foreach ($users as $r): ?>
            <tr>
              <td><?php echo (int)$r['id']; ?></td>
              <td><?php echo h($r['username']); ?></td>
              <td><?php echo h($r['email']); ?></td>
              <td><?php echo h($r['role']); ?></td>
              <td><?php echo (int)$r['is_active'] === 1 ? 'Yes' : 'No'; ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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