<?php
/**
 * WorksBoqController — read-only viewer for the contract BOQ (auto-snapshotted from tender pricing).
 *
 *   /WorksBoq/view/{project_id}   land on the project's BOQ.
 *   /WorksBoq/import/{project_id} deprecated alias — BOQ is snapshotted automatically on
 *                                  project provisioning. Just redirects to view.
 *
 * Variation items appear inline (origin=VARIATION with a colored badge).
 */
class WorksBoqController extends Controller
{
    /** Cross-project index — all works projects that have a snapshotted BOQ. */
    public function indexAction()
    {
        $db = new DB();
        $rows = $db->mySelect(
            "SELECT p.c0d, p.project_no, p.project_name, p.project_customer, p.currency,
                    b.c0d boq_id, b.contract_value, b.variation_value,
                    (SELECT COUNT(*) FROM works_boq_items i WHERE i.boq_id = b.c0d AND i.deleted = 0) item_count
               FROM works_boqs b
               JOIN c_projects p ON p.c0d = b.project_id AND p.deleted = 0
              WHERE b.deleted = 0
              ORDER BY p.project_no DESC",
            []
        ) ?: [];
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorksBoq/index', [
            'page_title' => 'Contract BOQs · all projects',
            'rows'       => $rows,
        ]);
    }

    public function viewAction($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;
        }
        $wb  = new WorksBoq();
        $boq = $wb->findByProject($projectId);
        $items = $boq ? $wb->itemsFor((int)$boq['c0d']) : [];
        $totals = $boq ? $wb->totals((int)$boq['c0d']) : [];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorksBoq/view', [
            'page_title' => 'Contract BOQ · ' . ($prj[0]['project_no'] ?? ''),
            'project'    => $prj[0],
            'boq'        => $boq,
            'items'      => $items,
            'totals'     => $totals,
        ]);
    }

    /** Legacy alias — kept so old ProjectStarter task URLs (Slice 6) don't 404. */
    public function importAction($projectId = 0)
    {
        Router::redirect('WorksBoq/view/' . (int)$projectId);
    }
}
