<?php
// POST /api/roles/save.php  action: create | update
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
requireRole([1, 5]);
$db     = getDB();
$action = post('action', 'create');

if ($action === 'create') {
    $name = trim(post('name', ''));
    $desc = trim(post('description', ''));
    if (!$name) apiError('Role name required.', 422);

    $check = $db->prepare("SELECT COUNT(*) FROM roles WHERE name = ?");
    $check->execute([$name]);
    if ((int)$check->fetchColumn()) apiError('A role with that name already exists.', 409);

    $db->prepare("INSERT INTO roles (name, description, is_system, sort_order) VALUES (?,?,0,(SELECT COALESCE(MAX(sort_order),0)+1 FROM roles r2))")
       ->execute([$name, $desc]);
    $newId = (int)$db->lastInsertId();

    // Copy a base set of view-only permissions for the new role
    $modules = ['dashboard','clients','projects','jobcards','stock','fleet','slips','cashflow','checklists','calendar','employees','payroll','settings','users'];
    foreach ($modules as $mod) {
        $db->prepare("INSERT IGNORE INTO role_permissions (role_id, module, action, allowed) VALUES (?,?,'view',0)")
           ->execute([$newId, $mod]);
        foreach (['view_own','create','edit','delete','reports','view_costing'] as $act) {
            $db->prepare("INSERT IGNORE INTO role_permissions (role_id, module, action, allowed) VALUES (?,?,?,0)")
               ->execute([$newId, $mod, $act]);
        }
    }
    // Give dashboard view by default
    $db->prepare("UPDATE role_permissions SET allowed=1 WHERE role_id=? AND module='dashboard' AND action='view'")->execute([$newId]);

    apiSuccess(['id' => $newId], 'Role created.');
}

if ($action === 'update') {
    $id   = (int)post('id', 0);
    $name = trim(post('name', ''));
    $desc = trim(post('description', ''));
    if (!$id || !$name) apiError('ID and name required.', 422);

    // Can't rename system role
    $role = $db->prepare("SELECT is_system FROM roles WHERE id=? LIMIT 1");
    $role->execute([$id]);
    $r = $role->fetch();
    if (!$r) apiError('Role not found.', 404);
    if ($r['is_system'] && $id == 1) apiError('Admin role cannot be renamed.', 403);

    // Check unique name (excluding self)
    $check = $db->prepare("SELECT COUNT(*) FROM roles WHERE name=? AND id!=?");
    $check->execute([$name, $id]);
    if ((int)$check->fetchColumn()) apiError('Name already in use.', 409);

    $db->prepare("UPDATE roles SET name=?, description=? WHERE id=?")->execute([$name, $desc, $id]);
    apiSuccess([], 'Role updated.');
}

apiError('Unknown action.', 422);