<?php
/**
 * WorkTemplatesController — admin authoring of reusable checklist templates.
 *
 *   /WorkTemplates                  list all templates
 *   /WorkTemplates/edit/{id}        author items on a specific template
 *   /WorkTemplates/createAj         POST code, title, scope, target_entity_type → new template
 *   /WorkTemplates/newVersionAj     POST id → fork
 *   /WorkTemplates/deactivateAj     POST id
 *   /WorkTemplates/updateHeaderAj   POST id, title, description, ...
 *   /WorkTemplates/addItemAj        POST template_id, prompt, input_type, ...
 *   /WorkTemplates/updateItemAj     POST id, ...
 *   /WorkTemplates/deleteItemAj     POST id
 */
class WorkTemplatesController extends Controller
{
    public function indexAction()
    {
        $m = new WorkTemplates();
        $rows = $m->listAll();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorkTemplates/index', [
            'page_title' => 'Work Templates',
            'rows'       => $rows,
            'scopes'     => WorkTemplates::SCOPES,
        ]);
    }

    public function editAction($id = 0)
    {
        $m = new WorkTemplates();
        $tpl = $m->findById((int)$id);
        if (!$tpl) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Template not found.</div>']);
            return;
        }
        $items    = $m->itemsForTemplate((int)$id);
        $editable = !$m->hasLiveInstances((int)$id);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorkTemplates/edit', [
            'page_title'   => $tpl['code'] . ' v' . $tpl['version'],
            'tpl'          => $tpl,
            'items'        => $items,
            'editable'     => $editable,
            'input_types'  => WorkTemplates::INPUT_TYPES,
            'cadences'     => WorkTemplates::CADENCES,
        ]);
    }

    public function createAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (new WorkTemplates())->create(
                [
                    'code'  => (string)($_POST['code'] ?? ''),
                    'title' => (string)($_POST['title'] ?? ''),
                    'description' => (string)($_POST['description'] ?? ''),
                    'scope' => (string)($_POST['scope'] ?? 'CHECKLIST'),
                    'target_entity_type' => (string)($_POST['target_entity_type'] ?? 'c_projects'),
                    'cadence' => (string)($_POST['cadence'] ?? 'ON_DEMAND'),
                    'expected_minutes' => (int)($_POST['expected_minutes'] ?? 0),
                    'reviewer_role' => (string)($_POST['reviewer_role'] ?? ''),
                ],
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_SESSION['full_name'] ?? '')
            );
            echo json_encode(['ok' => true, 'id' => $id]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function newVersionAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (new WorkTemplates())->forkNewVersion(
                (int)($_POST['id'] ?? 0),
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_SESSION['full_name'] ?? '')
            );
            echo json_encode(['ok' => true, 'id' => $id]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function deactivateAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new WorkTemplates())->deactivate((int)($_POST['id'] ?? 0), (int)($_SESSION['user_id'] ?? 0));
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function updateHeaderAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new WorkTemplates())->updateHeader((int)($_POST['id'] ?? 0), $_POST, (int)($_SESSION['user_id'] ?? 0));
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function addItemAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (new WorkTemplates())->addItem((int)($_POST['template_id'] ?? 0), $_POST);
            echo json_encode(['ok' => true, 'id' => $id]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function updateItemAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new WorkTemplates())->updateItem((int)($_POST['id'] ?? 0), $_POST);
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function deleteItemAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new WorkTemplates())->deleteItem((int)($_POST['id'] ?? 0));
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
