<?php
/**
 * WorksProjectReportController — leadership rollup for Works projects.
 *
 *   /WorksProjectReport                  — cross-project index (every project with a BOQ)
 *   /WorksProjectReport/view/{project}   — one project's rollup: summary + per-phase + per-pillar
 *
 * Read-only surface. Model is WorksProjectReport.
 */
class WorksProjectReportController extends Controller
{
    public function indexAction()
    {
        if (!class_exists('WorksProjectReport')) require_once ROOT . '/app/models/WorksProjectReport.php';
        $rows = (new WorksProjectReport())->projectsWithReport();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorksProjectReport/index', [
            'page_title' => 'Works project reports',
            'rows'       => $rows,
        ]);
    }

    public function viewAction($projectId = 0)
    {
        $projectId = (int)$projectId;
        $db = new DB();
        $prj = $db->mySelect(
            "SELECT c0d, project_no, project_name, project_customer, project_type, 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;
        }
        if (($prj[0]['project_type'] ?? '') !== 'works') {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-warning">This report is for <strong>works</strong> projects only.</div>']);
            return;
        }
        if (!class_exists('WorksProjectReport')) require_once ROOT . '/app/models/WorksProjectReport.php';
        if (!class_exists('WorksAlerts'))        require_once ROOT . '/app/models/WorksAlerts.php';
        $wpr = new WorksProjectReport();
        $wa  = new WorksAlerts();

        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorksProjectReport/view', [
            'page_title'   => 'Project report · ' . ($prj[0]['project_no'] ?? ''),
            'project'      => $prj[0],
            'summary'      => $wpr->projectSummary($projectId),
            'revenue'      => $wpr->revenueSummary($projectId),
            'phase_rollup' => $wpr->phaseRollup($projectId),
            'pillar_rollup'=> $wpr->pillarRollup($projectId),
            'alerts'       => $wa->alertsFor($projectId),
        ]);
    }
}
