<?php
/**
 * DocNumbersController — admin surface for the central document-numbering config.
 *
 *   /DocNumbers            list every doc_key + preview of next allocated number
 *   /DocNumbers/edit/{id}  edit form (loaded via modal in the index page)
 *   /DocNumbers/saveAj     POST id + config fields (Admin only)
 */
class DocNumbersController extends Controller
{
    public function indexAction()
    {
        if (!class_exists('DocNumberSettings')) require_once ROOT . '/app/models/DocNumberSettings.php';
        $m = new DocNumberSettings();
        $rows = $m->list();
        // Enrich each row with a peek-formatted next number for the UI preview.
        foreach ($rows as &$r) $r['next_preview'] = $m->peek((string)$r['doc_key']);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('DocNumbers/index', [
            'page_title' => 'Document Numbering',
            'rows'       => $rows,
        ]);
    }

    /** POST id + config fields → update. Only Admin may write. */
    public function saveAjAction()
    {
        header('Content-Type: application/json');
        try {
            $group = strtoupper((string)($_SESSION['user_group_name'] ?? ''));
            if ($group !== 'ADMINISTRATOR') {
                echo json_encode(['ok' => false, 'msg' => 'Only Administrator can edit doc-numbering config.']); return;
            }
            if (!class_exists('DocNumberSettings')) require_once ROOT . '/app/models/DocNumberSettings.php';
            $res = (new DocNumberSettings())->configure(
                (int)($_POST['id'] ?? 0),
                [
                    'label'         => (string)($_POST['label']         ?? ''),
                    'prefix'        => (string)($_POST['prefix']        ?? ''),
                    'separator'     => (string)($_POST['separator']     ?? '-'),
                    'seq_width'     => (int)   ($_POST['seq_width']     ?? 4),
                    'start_no'      => (int)   ($_POST['start_no']      ?? 1),
                    'next_no'       => (int)   ($_POST['next_no']       ?? 1),
                    'include_year'  => (int)   ($_POST['include_year']  ?? 1),
                    'year_position' => (string)($_POST['year_position'] ?? 'AFTER_PREFIX'),
                    'reset_scope'   => (string)($_POST['reset_scope']   ?? 'YEARLY'),
                    'notes'         => (string)($_POST['notes']         ?? ''),
                ],
                (int)($_SESSION['user_id'] ?? 0)
            );
            echo json_encode($res);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
