<?php
class GoodsGrnController extends Controller
{
    public function indexAction()
    {
        $m    = new GoodsGrn();
        $rows = $m->list();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('GoodsGrn/index', [
            'page_title' => 'Goods Received Notes',
            'rows'       => $rows,
        ]);
    }

    /** Receive form pre-filled from an LPO's outstanding lines. */
    public function receiveAction($lpo_id = 0)
    {
        $lpoId = (int)$lpo_id;
        if ($lpoId <= 0) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">lpo_id required.</div>']);
            return;
        }
        $lm  = new Lpos();
        $lpo = $lm->byId($lpoId);
        if (!$lpo) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">LPO not found.</div>']);
            return;
        }
        if ($lpo['lpo_type'] !== 'SUPPLIER') {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-warning">Only SUPPLIER LPOs can have a GRN. This is a ' . htmlspecialchars($lpo['lpo_type']) . '.</div>']);
            return;
        }
        if (!in_array($lpo['cash_out_status'], ['APPROVED','ISSUED','PAID'], true)) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-warning">LPO must be APPROVED before receiving. Current status: <code>' . htmlspecialchars($lpo['cash_out_status']) . '</code>.</div>']);
            return;
        }
        if ($lpo['receipt_status'] === 'FULLY_RECEIVED') {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-info">This LPO is already fully received. <a href="' . PROOT . 'Lpos/view/' . (int)$lpo['c0d'] . '">Back to LPO</a>.</div>']);
            return;
        }
        $items = $lm->itemsFor($lpoId);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('GoodsGrn/receive', [
            'page_title' => 'Receive · ' . $lpo['lpo_no'],
            'lpo'        => $lpo,
            'items'      => $items,
        ]);
    }

    public function saveAction()
    {
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('GoodsGrn'); return; }

        // Rebuild items[] from parallel arrays
        $ids  = $_POST['line_id']    ?? [];
        $qrs  = $_POST['qty_received'] ?? [];
        $qjs  = $_POST['qty_rejected'] ?? [];
        $cns  = $_POST['condition_notes'] ?? [];
        $items = [];
        for ($i = 0; $i < count($ids); $i++) {
            $qr = (float)($qrs[$i] ?? 0);
            $qj = (float)($qjs[$i] ?? 0);
            if ($qr <= 0 && $qj <= 0) continue;
            $items[] = [
                'lpo_item_id'     => (int)$ids[$i],
                'qty_received'    => $qr,
                'qty_rejected'    => $qj,
                'condition_notes' => (string)($cns[$i] ?? ''),
            ];
        }
        $d = [
            'lpo_id'                     => (int)($_POST['lpo_id'] ?? 0),
            'received_on'                => (string)($_POST['received_on'] ?? date('Y-m-d')),
            'supplier_delivery_note_ref' => (string)($_POST['supplier_delivery_note_ref'] ?? ''),
            'notes'                      => (string)($_POST['notes'] ?? ''),
            'items'                      => $items,
        ];

        $m = new GoodsGrn();
        $r = $m->create($d, $this->currentUserId(), $_SESSION['full_name'] ?? '');
        if (!$r['ok']) {
            $lm  = new Lpos();
            $lpo = $lm->byId((int)$d['lpo_id']);
            $items = $lm->itemsFor((int)$d['lpo_id']);
            $this->view->setLayout($this->roleLayout());
            $this->view->render('GoodsGrn/receive', [
                'page_title' => 'Receive',
                'lpo'        => $lpo,
                'items'      => $items,
                'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($r['msg']) . '</div>',
                'form'       => $_POST,
            ]);
            return;
        }
        Router::redirect('GoodsGrn/view/' . (int)$r['id']);
    }

    public function viewAction($id = 0)
    {
        $m   = new GoodsGrn();
        $grn = $m->byId((int)$id);
        if (!$grn) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">GRN not found.</div>']);
            return;
        }
        $items = $m->itemsFor((int)$id);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('GoodsGrn/view', [
            'page_title' => $grn['grn_no'],
            'grn'        => $grn,
            'items'      => $items,
        ]);
    }
}
