<?php
class ProjectPnlController extends Controller
{
    public function indexAction()
    {
        $from = (string)($_GET['from'] ?? '');
        $to   = (string)($_GET['to']   ?? '');

        $m = new ProjectPnl();
        $rows = $m->overviewAllProjects($from, $to);

        // Portfolio totals
        $totals = ['revenue' => 0, 'cogs' => 0, 'opex' => 0, 'planned_revenue' => 0, 'planned_cog' => 0];
        foreach ($rows as $r) {
            $totals['revenue']         += (float)$r['revenue'];
            $totals['cogs']            += (float)$r['cogs'];
            $totals['opex']            += (float)$r['opex'];
            $totals['planned_revenue'] += (float)$r['planned_revenue'];
            $totals['planned_cog']     += (float)$r['planned_cog'];
        }
        $totals['gross_margin']         = $totals['revenue'] - $totals['cogs'];
        $totals['net_margin']           = $totals['revenue'] - $totals['cogs'] - $totals['opex'];
        $totals['planned_gross_margin'] = $totals['planned_revenue'] - $totals['planned_cog'];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('ProjectPnl/index', [
            'page_title' => 'Project P&L',
            'rows'       => $rows,
            'totals'     => $totals,
            'from'       => $from,
            'to'         => $to,
        ]);
    }

    public function viewAction($project_id = 0)
    {
        $pid = (int)$project_id;
        if ($pid <= 0) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">project_id required.</div>']);
            return;
        }
        $from = (string)($_GET['from'] ?? '');
        $to   = (string)($_GET['to']   ?? '');
        $m    = new ProjectPnl();
        $data = $m->forProject($pid, $from, $to);
        if (empty($data)) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Project not found.</div>']);
            return;
        }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('ProjectPnl/view', [
            'page_title' => 'P&L · ' . $data['project']['project_no'],
            'p'          => $data['project'],
            'totals'     => $data['totals'],
            'planned'    => $data['planned'],
            'by_account' => $data['by_account'],
            'lines'      => $data['lines'],
            'from'       => $from,
            'to'         => $to,
        ]);
    }
}
