<?php
declare(strict_types=1);
require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role('Admin');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') redirect('list.php');

try {
  csrf_verify((string)($_POST['csrf'] ?? ''));
  $id = (int)($_POST['id'] ?? 0);
  if ($id <= 0) redirect('list.php');

  $companyId = current_user()['company_id'] ?? null;
  if (!$companyId) redirect('../../public/index.php');

  // prevent self-delete
  if ($id === (int)current_user()['id']) {
    redirect('list.php');
  }

  // Only delete within same company
  $del = db()->prepare("DELETE FROM users WHERE id = :id AND company_id = :cid");
  $del->execute([':id'=>$id, ':cid'=>$companyId]);

  audit_log('user.delete', 'user', $id, null);
} catch (Throwable $e) {
  // swallow errors for UX; could flash message if you add flash system
}
redirect('list.php');
