<?php
/**
 * CompanyProfileController — Slice 8V.
 *
 *   /CompanyProfile        edit form (rendered read-only for fields the current role can't edit)
 *   /CompanyProfile/saveAj POST full form; model filters by role
 */
class CompanyProfileController extends Controller
{
    public function indexAction()
    {
        if (!class_exists('CompanyProfile')) require_once ROOT . '/app/models/CompanyProfile.php';
        $m = new CompanyProfile();
        $group = (string)($_SESSION['user_group_name'] ?? '');
        $this->view->setLayout($this->roleLayout());
        $this->view->render('CompanyProfile/index', [
            'page_title'      => 'Company Profile',
            'profile'         => $m->get(),
            'writable_fields' => CompanyProfile::writableFieldsFor($group),
            'user_group'      => $group,
        ]);
    }

    public function saveAjAction()
    {
        header('Content-Type: application/json');
        try {
            if (!class_exists('CompanyProfile')) require_once ROOT . '/app/models/CompanyProfile.php';
            $group = (string)($_SESSION['user_group_name'] ?? '');
            $res = (new CompanyProfile())->save($_POST, $group,
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_SESSION['full_name'] ?? ''));
            echo json_encode($res);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
