<?php
class CompanyDocumentsController extends Controller
{
    private function ug(): string { return (string)($_SESSION['user_group_name'] ?? ''); }

    public function indexAction()
    {
        $filter = [
            'status'   => (string)($_GET['status'] ?? ''),
            'expiring' => !empty($_GET['expiring']),
            'expired'  => !empty($_GET['expired']),
            'q'        => trim((string)($_GET['q'] ?? '')),
        ];
        $m = new CompanyDocuments();
        $ug = $this->ug();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('CompanyDocuments/index', [
            'page_title'    => 'Company Documents Library',
            'rows'          => $m->listVisible($ug, $filter),
            'counts'        => $m->counts($ug),
            'action_needed' => $m->actionNeeded($ug),
            'filter'        => $filter,
            'is_admin_role' => in_array($ug, CompanyDocuments::DEFAULT_ACCESS_ROLES, true),
        ]);
    }

    public function addAction()    { $this->handleForm(null); }
    public function editAction($id = 0) { $this->handleForm((int)$id); }

    private function handleForm(?int $id): void
    {
        $m = new CompanyDocuments();
        $ug = $this->ug();
        $userId   = (int)($_SESSION['user_id'] ?? 0);
        $userName = (string)($_SESSION['full_name'] ?? '');

        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
            if ($id === null) { $id = $m->create($_POST, $userId, $userName, $ug); }
            else              { $m->update($id, $_POST, $userId); }
            header('Location: ' . PROOT . 'CompanyDocuments/view/' . $id);
            return;
        }

        $doc = $id ? $m->find($id, $ug) : null;
        $this->view->setLayout($this->roleLayout());
        $this->view->render('CompanyDocuments/form', [
            'page_title' => $id ? 'Edit Document' : 'Add Company Document',
            'doc'        => $doc,
            'catalog'    => $m->docTypeCatalog(),
        ]);
    }

    public function viewAction($id = 0)
    {
        $id = (int)$id;
        $m = new CompanyDocuments();
        $ug = $this->ug();
        $doc = $m->find($id, $ug);
        if (!$doc) { header('HTTP/1.1 403 Forbidden'); echo 'Not found or you do not have access.'; return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('CompanyDocuments/view', [
            'page_title'    => 'Document · ' . htmlspecialchars($doc['doc_name']),
            'doc'           => $doc,
            'grants'        => $m->accessGrants($id),
            'ungranted'     => $m->ungrantedGroups($id),
            'is_admin_role' => in_array($ug, CompanyDocuments::DEFAULT_ACCESS_ROLES, true),
            'default_roles' => CompanyDocuments::DEFAULT_ACCESS_ROLES,
        ]);
    }

    public function shareAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id  = (int)($_POST['doc_id'] ?? 0);
            $gid = (int)($_POST['user_group_id'] ?? 0);
            (new CompanyDocuments())->share($id, $gid,
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_SESSION['full_name'] ?? ''),
                $this->ug()
            );
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function revokeAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id  = (int)($_POST['doc_id'] ?? 0);
            $gid = (int)($_POST['user_group_id'] ?? 0);
            (new CompanyDocuments())->revoke($id, $gid, $this->ug());
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
