<?php
/** Approval-matrix configuration — admin/headteacher only. */
require_once __DIR__ . '/_boot.php';

if (!in_array($actor['role'], ['admin', 'headteacher', 'director'], true)) {
    fin_out(['success' => false, 'message' => 'Only administrators can change the approval workflow.']);
}

$action = fin_in('action', '');

switch ($action) {

    case 'get':
        fin_out([
            'success' => true,
            'steps'   => finance_all_steps($conn),
            'roles'   => finance_approver_roles(),
        ]);

    // Replace the whole matrix with the submitted steps (JSON array).
    case 'save': {
        $raw = fin_in('steps', '[]');
        $steps = json_decode((string) $raw, true);
        if (!is_array($steps)) fin_out(['success' => false, 'message' => 'Malformed steps payload.']);

        $validRoles = array_keys(finance_approver_roles());
        $clean = [];
        $order = 1;
        foreach ($steps as $s) {
            $role = (string) ($s['approver_role'] ?? '');
            if (!in_array($role, $validRoles, true)) continue;
            $clean[] = [
                'order'  => $order++,
                'role'   => $role,
                'label'  => trim((string) ($s['label'] ?? '')) ?: (finance_approver_roles()[$role] ?? $role),
                'min'    => max(0, (float) ($s['min_amount'] ?? 0)),
            ];
        }
        if (empty($clean)) fin_out(['success' => false, 'message' => 'Define at least one approval step.']);

        $conn->query("DELETE FROM expense_approval_steps");
        $stmt = $conn->prepare("INSERT INTO expense_approval_steps (step_order, approver_role, label, min_amount, active) VALUES (?,?,?,?,1)");
        foreach ($clean as $c) {
            $stmt->bind_param('issd', $c['order'], $c['role'], $c['label'], $c['min']);
            $stmt->execute();
        }
        $stmt->close();
        fin_out(['success' => true, 'message' => 'Approval workflow saved.', 'steps' => finance_all_steps($conn)]);
    }

    default:
        fin_out(['success' => false, 'message' => 'Unknown action.']);
}
