<?php
/**
 * FinanceSettingsController — Slice 8Z-j · Batch 4
 *
 * Finance-owned tunables surface. Currently exposes the two Product Discovery percentages
 * (cap + Exec threshold) that gate the Discovery request modal. FM + Exec + Admin can edit.
 *
 * Endpoints:
 *   /FinanceSettings           GET  — settings index (form)
 *   /FinanceSettings/updateAj  POST — save one or more settings
 */
class FinanceSettingsController extends Controller
{
    public function indexAction()
    {
        $m = new FinanceSettings();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('FinanceSettings/index', [
            'page_title' => 'Finance Settings',
            'settings'   => $m->all(),
        ]);
    }

    public function updateAjAction()
    {
        header('Content-Type: application/json');
        try {
            // Whitelist of editable keys — extend as new settings land.
            $keys = ['discovery_cap_pct','discovery_exec_threshold_pct'];
            $updates = [];
            foreach ($keys as $k) {
                if (array_key_exists($k, $_POST)) $updates[$k] = $_POST[$k];
            }
            if (empty($updates)) throw new InvalidArgumentException('No editable settings supplied.');
            $r = (new FinanceSettings())->updateMany($updates, $this->currentUserId(), $_SESSION['full_name'] ?? '');
            echo json_encode($r);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
