<?php
// POST /api/roles/delete.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
requireRole([1]);
$db = getDB();
$id = (int)post('id', 0);
if (!$id) apiError('Role ID required.', 422);

$role = $db->prepare("SELECT * FROM roles WHERE id=? LIMIT 1");
$role->execute([$id]);
$r = $role->fetch();
if (!$r) apiError('Role not found.', 404);
if ($r['is_system']) apiError('System roles cannot be deleted.', 403);

// Check no users assigned
$users = $db->prepare("SELECT COUNT(*) FROM users WHERE role_id=?");
$users->execute([$id]);
if ((int)$users->fetchColumn() > 0) apiError('Cannot delete — users are assigned to this role. Reassign them first.', 409);

$db->prepare("DELETE FROM roles WHERE id=?")->execute([$id]);
apiSuccess([], 'Role deleted.');