<?php
// POST /api/roles/permissions.php  action: get | set | get_my
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user   = requireAuth();
$db     = getDB();
$action = post('action', 'get');

// ── GET MY permissions (called after login) ───────────────────
if ($action === 'get_my') {
    $roleId = (int)$user['role_id'];

    // Admin always gets everything
    if ($roleId === 1) {
        $modules = ['dashboard','clients','projects','jobcards','stock','fleet','slips',
                    'cashflow','checklists','calendar','employees','payroll','settings','users'];
        $perms = [];
        foreach ($modules as $mod) {
            foreach (['view','create','edit','delete'] as $act) {
                $perms[] = ['module' => $mod, 'action' => $act, 'allowed' => 1];
            }
        }
        apiSuccess(['permissions' => $perms, 'is_admin' => true]);
    }

    $stmt = $db->prepare("SELECT module, action, allowed FROM role_permissions WHERE role_id = ?");
    $stmt->execute([$roleId]);
    apiSuccess(['permissions' => $stmt->fetchAll(), 'is_admin' => false]);
}

// ── GET permissions for a specific role (admin only) ──────────
if ($action === 'get') {
    requireRole([1, 5]);
    $roleId = (int)post('role_id', 0);
    if (!$roleId) apiError('role_id required.', 422);

    $stmt = $db->prepare("SELECT module, action, allowed FROM role_permissions WHERE role_id = ? ORDER BY module, action");
    $stmt->execute([$roleId]);
    apiSuccess(['permissions' => $stmt->fetchAll()]);
}

// ── SET permissions for a role (admin only) ───────────────────
if ($action === 'set') {
    requireRole([1, 5]);
    $roleId = (int)post('role_id', 0);
    if (!$roleId) apiError('role_id required.', 422);

    // Can't edit Admin (role 1)
    if ($roleId === 1) apiError('Admin permissions cannot be changed.', 403);

    // Expect JSON: { "fleet.view": true, "fleet.create": false, ... }
    $raw    = post('matrix', '{}');
    $matrix = is_array($raw) ? $raw : json_decode($raw, true);
    if (!is_array($matrix)) apiError('Invalid matrix.', 422);

    $stmt = $db->prepare("INSERT INTO role_permissions (role_id, module, action, allowed)
        VALUES (?,?,?,?)
        ON DUPLICATE KEY UPDATE allowed = VALUES(allowed)");

    foreach ($matrix as $key => $allowed) {
        [$module, $act] = explode('.', $key, 2);
        if (!in_array($act, ['view','view_own','create','edit','delete','reports','view_costing'])) continue;
        $stmt->execute([$roleId, $module, $act, $allowed ? 1 : 0]);
    }

    apiSuccess([], 'Permissions saved.');
}

apiError('Unknown action.', 422);