<?php
/**
 * SpCalloutsController — Services callouts (unplanned response).
 *
 * This slice (8b-5) only wires the PLAYBOOK ATTACHMENT surface:
 *   /SpCallouts/playbook/{project_id}   attach a playbook to a Services project.
 *
 * Actual callout events + response tracking are a later slice.
 */
class SpCalloutsController extends Controller
{
    public function playbookAction($projectId = 0)
    {
        $projectId = (int)$projectId;
        $db = new DB();
        $prj = $db->mySelect(
            "SELECT c0d, project_no, project_name, project_type, project_customer
               FROM c_projects WHERE c0d = :p AND deleted = 0",
            [':p' => $projectId]
        );
        if (empty($prj)) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Project not found.</div>']);
            return;
        }
        $m = new CalloutPlaybooks();
        $current = $m->activeForProject($projectId);
        $history = $m->attachmentHistory($projectId);
        $catalogue = $m->listAll(true); // active only for the picker

        $currentSlas = $current ? $m->slasFor((int)$current['playbook_id']) : [];
        $currentEsc  = $current ? $m->escalationsFor((int)$current['playbook_id']) : [];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('SpCallouts/playbook', [
            'page_title'    => 'Callout Playbook · ' . ($prj[0]['project_no'] ?? ''),
            'project'       => $prj[0],
            'current'       => $current,
            'current_slas'  => $currentSlas,
            'current_esc'   => $currentEsc,
            'history'       => $history,
            'catalogue'     => $catalogue,
        ]);
    }

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