<?php
/**
 * CalloutPlaybooksController — admin authoring of the callout playbook library.
 *
 *   /CalloutPlaybooks                list all playbooks
 *   /CalloutPlaybooks/edit/{id}      author SLAs + escalations for one playbook
 *   /CalloutPlaybooks/createAj       POST code, name, description → new playbook
 *   /CalloutPlaybooks/updateHeaderAj POST id, name, description
 *   /CalloutPlaybooks/setActiveAj    POST id, active (0/1)
 *   /CalloutPlaybooks/upsertSlaAj    POST playbook_id, severity, response_hours, resolution_hours, notes
 *   /CalloutPlaybooks/deleteSlaAj    POST id
 *   /CalloutPlaybooks/addEscalationAj POST playbook_id, severity, step_no, role, notify_after_hours, notes
 *   /CalloutPlaybooks/deleteEscalationAj POST id
 */
class CalloutPlaybooksController extends Controller
{
    public function indexAction()
    {
        $rows = (new CalloutPlaybooks())->listAll(false);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('CalloutPlaybooks/index', [
            'page_title' => 'Callout Playbooks',
            'rows'       => $rows,
            'severities' => CalloutPlaybooks::SEVERITIES,
        ]);
    }

    public function editAction($id = 0)
    {
        $m = new CalloutPlaybooks();
        $pb = $m->findById((int)$id);
        if (!$pb) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Playbook not found.</div>']);
            return;
        }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('CalloutPlaybooks/edit', [
            'page_title'  => 'Playbook · ' . $pb['name'],
            'pb'          => $pb,
            'slas'        => $m->slasFor((int)$id),
            'escalations' => $m->escalationsFor((int)$id),
            'severities'  => CalloutPlaybooks::SEVERITIES,
        ]);
    }

    public function createAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (new CalloutPlaybooks())->create(
                [
                    'code'        => (string)($_POST['code'] ?? ''),
                    'name'        => (string)($_POST['name'] ?? ''),
                    'description' => (string)($_POST['description'] ?? ''),
                ],
                (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 updateHeaderAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new CalloutPlaybooks())->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 setActiveAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new CalloutPlaybooks())->setActive(
                (int)($_POST['id'] ?? 0),
                !empty($_POST['active']),
                (int)($_SESSION['user_id'] ?? 0)
            );
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function upsertSlaAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (new CalloutPlaybooks())->upsertSla(
                (int)($_POST['playbook_id'] ?? 0),
                (string)($_POST['severity'] ?? ''),
                (float)($_POST['response_hours'] ?? 0),
                (float)($_POST['resolution_hours'] ?? 0),
                (string)($_POST['notes'] ?? '')
            );
            echo json_encode(['ok' => true, 'id' => $id]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

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

    public function addEscalationAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (new CalloutPlaybooks())->addEscalation(
                (int)($_POST['playbook_id'] ?? 0),
                (string)($_POST['severity'] ?? ''),
                (int)($_POST['step_no'] ?? 1),
                (string)($_POST['role'] ?? ''),
                (float)($_POST['notify_after_hours'] ?? 0),
                (string)($_POST['notes'] ?? '')
            );
            echo json_encode(['ok' => true, 'id' => $id]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

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