<?php
/**
 * WorksIpcsController — customer-side Interim Payment Certificates.
 *
 *   /WorksIpcs                     — cross-project index of every IPC
 *   /WorksIpcs/list/{project_id}   — IPCs on one project
 *   /WorksIpcs/create/{project_id} — draft a new IPC (auto-seeds BOQ lines)
 *   /WorksIpcs/view/{ipc_id}       — line editor + totals + approve button
 *   /WorksIpcs/createAj            POST project_id + ipc_date + period_from/to + notes
 *   /WorksIpcs/setLineQtyAj        POST ipc_id + line_id + this_period_qty
 *   /WorksIpcs/setAdvanceAj        POST ipc_id + amount
 *   /WorksIpcs/approveAj           POST ipc_id → generates sales invoice
 */
class WorksIpcsController extends Controller
{
    public function indexAction()
    {
        $db = new DB();
        $rows = $db->mySelect(
            "SELECT i.c0d, i.ipc_no, i.ipc_seq, i.status, i.ipc_date, i.certified_gross, i.net_amount, i.invoice_total, i.sale_id,
                    p.c0d project_id, p.project_no, p.project_name
               FROM works_ipcs i
               JOIN c_projects p ON p.c0d = i.project_id AND p.deleted = 0
              WHERE i.deleted = 0
              ORDER BY i.status='DRAFT' DESC, i.status='SUBMITTED' DESC, i.c0d DESC",
            []
        ) ?: [];
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorksIpcs/index', [
            'page_title' => 'Interim Payment Certificates',
            'rows'       => $rows,
        ]);
    }

    public function listAction($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 (!class_exists('WorksIpcs')) require_once ROOT . '/app/models/WorksIpcs.php';
        $wi = new WorksIpcs();
        $this->view->setLayout($this->roleLayout());
        $ipcs = $wi->listForProject($projectId);
        // Enrich each list row with AR summary (invoiced/received/outstanding).
        $ar = [];
        foreach ($ipcs as $r) $ar[(int)$r['c0d']] = $wi->arSummaryFor((int)$r['c0d']);
        $this->view->render('WorksIpcs/list', [
            'page_title' => 'IPCs · ' . ($prj[0]['project_no'] ?? ''),
            'project'    => $prj[0],
            'ipcs'       => $ipcs,
            'totals'     => $wi->totalCertifiedFor($projectId),
            'received'   => $wi->totalReceivedFor($projectId),
            'ar_by_ipc'  => $ar,
        ]);
    }

    public function createAction($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;
        }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorksIpcs/create', [
            'page_title' => 'New IPC · ' . ($prj[0]['project_no'] ?? ''),
            'project'    => $prj[0],
        ]);
    }

    public function viewAction($ipcId = 0)
    {
        $ipcId = (int)$ipcId;
        if (!class_exists('WorksIpcs')) require_once ROOT . '/app/models/WorksIpcs.php';
        $wi  = new WorksIpcs();
        $ipc = $wi->findById($ipcId);
        if (!$ipc) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">IPC not found.</div>']);
            return;
        }
        $db  = new DB();
        $prj = $db->mySelect("SELECT c0d, project_no, project_name, currency FROM c_projects WHERE c0d = :p", [':p' => (int)$ipc['project_id']]);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorksIpcs/view', [
            'page_title' => $ipc['ipc_no'],
            'ipc'        => $ipc,
            'project'    => $prj[0] ?? [],
            'lines'      => $wi->linesFor($ipcId),
            'can_edit'   => $ipc['status'] === 'DRAFT',
            'receipts'   => $wi->receiptsFor($ipcId),
            'ar'         => $wi->arSummaryFor($ipcId),
        ]);
    }

    /* ── AJAX ──────────────────────────────────────────────────────── */

    public function createAjAction()
    {
        header('Content-Type: application/json');
        try {
            if (!class_exists('WorksIpcs')) require_once ROOT . '/app/models/WorksIpcs.php';
            $res = (new WorksIpcs())->draft(
                (int)($_POST['project_id'] ?? 0),
                [
                    'ipc_date'    => (string)($_POST['ipc_date']    ?? date('Y-m-d')),
                    'period_from' => (string)($_POST['period_from'] ?? date('Y-m-01')),
                    'period_to'   => (string)($_POST['period_to']   ?? date('Y-m-d')),
                    'vat_pct'     => (float)($_POST['vat_pct']      ?? 18),
                    'notes'       => (string)($_POST['notes'] ?? ''),
                ],
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_SESSION['full_name'] ?? '')
            );
            echo json_encode($res);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function setLineQtyAjAction()
    {
        header('Content-Type: application/json');
        try {
            if (!class_exists('WorksIpcs')) require_once ROOT . '/app/models/WorksIpcs.php';
            $res = (new WorksIpcs())->setLineQty(
                (int)($_POST['ipc_id']  ?? 0),
                (int)($_POST['line_id'] ?? 0),
                (float)($_POST['this_period_qty'] ?? 0)
            );
            echo json_encode($res);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function setAdvanceAjAction()
    {
        header('Content-Type: application/json');
        try {
            if (!class_exists('WorksIpcs')) require_once ROOT . '/app/models/WorksIpcs.php';
            $res = (new WorksIpcs())->setAdvanceRecovery(
                (int)($_POST['ipc_id'] ?? 0),
                (float)($_POST['amount'] ?? 0)
            );
            echo json_encode($res);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function approveAjAction()
    {
        header('Content-Type: application/json');
        try {
            if (!class_exists('WorksIpcs')) require_once ROOT . '/app/models/WorksIpcs.php';
            $res = (new WorksIpcs())->approve(
                (int)($_POST['ipc_id'] ?? 0),
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_SESSION['full_name'] ?? ''),
                (string)($_SESSION['user_group_name'] ?? '')
            );
            echo json_encode($res);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
