<?php
/**
 * ServicePmPlansController — plan authoring for Services projects.
 *
 *   /ServicePmPlans/create/{project_id}    landing to create a plan (or view existing)
 *   /ServicePmPlans/view/{plan_id}         plan detail: items + assets picker + generate
 *   /ServicePmPlans/createAj               POST project_id + title → plan_id
 *   /ServicePmPlans/addItemAj              POST plan_id + asset_id + template_id + cadence + start_date
 *   /ServicePmPlans/generateAj             POST plan_id + horizon_days → creates WorkInstances
 *   /ServicePmPlans/activateAj             POST plan_id
 *   /ServicePmPlans/closeAj                POST plan_id
 */
class ServicePmPlansController extends Controller
{
    public function createAction($projectId = 0)
    {
        $projectId = (int)$projectId;
        $db = new DB();
        $prj = $db->mySelect(
            "SELECT c0d, project_no, project_name, project_type, project_customer, currency
               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;
        }
        $existing = (new ServicePmPlans())->listForProject($projectId);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('ServicePmPlans/create', [
            'page_title' => 'PM Plan · ' . ($prj[0]['project_no'] ?? ''),
            'project'    => $prj[0],
            'existing'   => $existing,
        ]);
    }

    public function viewAction($planId = 0)
    {
        $planId = (int)$planId;
        $m = new ServicePmPlans();
        $plan = $m->findById($planId);
        if (!$plan) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Plan not found.</div>']);
            return;
        }
        $items = $m->itemsFor($planId);
        $db = new DB();
        $prj = $db->mySelect(
            "SELECT c0d, project_no, project_name FROM c_projects WHERE c0d = :p",
            [':p' => (int)$plan['project_id']]
        );
        // Assets on this project
        $assets = $db->mySelect(
            "SELECT c0d, asset_no, name, status FROM assets
              WHERE project_id = :p AND deleted = 0 AND status = 'IN_SERVICE'
              ORDER BY asset_no",
            [':p' => (int)$plan['project_id']]
        ) ?: [];
        // PM-scope active templates targeting assets
        $templates = $db->mySelect(
            "SELECT c0d, code, title, cadence FROM work_templates
              WHERE scope = 'PM' AND target_entity_type = 'assets' AND is_active = 1 AND deleted = 0
              ORDER BY title",
            []
        ) ?: [];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('ServicePmPlans/view', [
            'page_title' => 'PM Plan · ' . ($plan['title'] ?? ''),
            'plan'       => $plan,
            'project'    => $prj[0] ?? [],
            'items'      => $items,
            'assets'     => $assets,
            'templates'  => $templates,
        ]);
    }

    public function createAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (new ServicePmPlans())->create(
                (int)($_POST['project_id'] ?? 0),
                [
                    'title' => (string)($_POST['title'] ?? ''),
                    'description' => (string)($_POST['description'] ?? ''),
                    'planned_start' => (string)($_POST['planned_start'] ?? ''),
                    'planned_end' => (string)($_POST['planned_end'] ?? ''),
                ],
                (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 addItemAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (new ServicePmPlans())->addItem(
                (int)($_POST['plan_id'] ?? 0),
                (int)($_POST['asset_id'] ?? 0),
                (int)($_POST['template_id'] ?? 0),
                (string)($_POST['cadence'] ?? 'MONTHLY'),
                [
                    'start_date' => (string)($_POST['start_date'] ?? ''),
                    'default_assignee_id' => (int)($_POST['default_assignee_id'] ?? 0),
                    'default_assignee_name' => (string)($_POST['default_assignee_name'] ?? ''),
                    'notes' => (string)($_POST['notes'] ?? ''),
                ]
            );
            echo json_encode(['ok' => true, 'id' => $id]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function generateAjAction()
    {
        header('Content-Type: application/json');
        try {
            $ids = (new ServicePmPlans())->generateNextInstances(
                (int)($_POST['plan_id'] ?? 0),
                (int)($_POST['horizon_days'] ?? 30),
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_SESSION['full_name'] ?? '')
            );
            echo json_encode(['ok' => true, 'created' => count($ids), 'instance_ids' => $ids]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function activateAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new ServicePmPlans())->activate((int)($_POST['plan_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 closeAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new ServicePmPlans())->close((int)($_POST['plan_id'] ?? 0), (int)($_SESSION['user_id'] ?? 0));
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
