<?php
class BdmPlansController extends Controller
{
    public function indexAction()
    {
        $m = new BdmPlans();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('BdmPlans/index', [
            'page_title' => 'BDM Plans',
            'rows'       => $m->listAll(),
        ]);
    }

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

    private function handleForm(?int $id): void
    {
        $m = new BdmPlans();
        $userId = (int)($_SESSION['user_id'] ?? 0);

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

        $this->view->setLayout($this->roleLayout());
        $this->view->render('BdmPlans/form', [
            'page_title' => $id ? 'Edit Plan' : 'Add BDM Plan',
            'plan'       => $id ? $m->find($id) : null,
        ]);
    }

    public function viewAction($id = 0)
    {
        $id = (int)$id;
        $m = new BdmPlans();
        $plan = $m->find($id);
        if (!$plan) { header('HTTP/1.1 404 Not Found'); echo 'Plan not found'; return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('BdmPlans/view', [
            'page_title' => 'BDM Plan · ' . htmlspecialchars($plan['plan_name']),
            'plan'       => $plan,
            'objectives' => $m->objectives($id),
        ]);
    }

    public function addObjectiveAjAction()
    {
        header('Content-Type: application/json');
        try {
            $pid  = (int)($_POST['plan_id'] ?? 0);
            $obj  = trim((string)($_POST['objective'] ?? ''));
            $tval = (float)($_POST['target_value'] ?? 0);
            if ($pid <= 0 || $obj === '') throw new InvalidArgumentException('Plan + objective required.');
            (new BdmPlans())->addObjective($pid, $obj, $tval);
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
