<?php
class GoodsRfqController extends Controller
{
    public function indexAction()
    {
        $m           = new GoodsRfq();
        $projectId   = (int)($_GET['project_id'] ?? 0);
        $assignedMe  = strtolower((string)($_GET['assigned'] ?? '')) === 'me';
        $assignedUid = $assignedMe ? $this->currentUserId() : 0;
        $rows = $m->list((string)($_GET['status'] ?? ''), $projectId, $assignedUid);

        $projName = '';
        if ($projectId > 0) {
            $db = new DB();
            $r = $db->mySelect("SELECT project_no, project_name FROM c_projects WHERE c0d = :id", [':id' => $projectId]);
            if (!empty($r)) $projName = $r[0]['project_no'] . ' · ' . $r[0]['project_name'];
        }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('GoodsRfq/index', [
            'page_title'           => 'Sourcing · RFQs',
            'rows'                 => $rows,
            'status'               => (string)($_GET['status'] ?? ''),
            'filter_project'       => $projectId,
            'filter_project_label' => $projName,
            'filter_assigned_me'   => $assignedMe,
        ]);
    }

    /**
     * Project-scoped alias — from the ProjectStarter checklist we have project_id, not RFQ id.
     * Find (or ensure) an RFQ for the project's client PO and redirect to view.
     */
    public function fromProjectAction($projectId = 0)
    {
        $projectId = (int)$projectId;
        $db = new DB();
        $poRow = $db->mySelect(
            "SELECT c0d FROM goods_client_pos WHERE project_id = :p AND deleted = 0 ORDER BY c0d DESC LIMIT 1",
            [':p' => $projectId]
        );
        if (empty($poRow)) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-warning">No client PO on this project yet — PC must scrub the PO first.</div>']);
            return;
        }
        // Reuse the existing ensure-and-redirect helper
        $this->fromClientPoAction((int)$poRow[0]['c0d']);
    }

    /** Alias — the ProjectStarter Goods checklist calls this "assessQuotes". Same target as fromProject. */
    public function assessQuotesAction($projectId = 0)
    {
        $this->fromProjectAction($projectId);
    }

    /** Auto-ensure an RFQ exists for the given Client PO, then redirect to view. */
    public function fromClientPoAction($cpo_id = 0)
    {
        $cpoId = (int)$cpo_id;
        if ($cpoId <= 0) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Client PO id missing.</div>']);
            return;
        }
        $m = new GoodsRfq();
        $r = $m->ensureForClientPo($cpoId, $this->currentUserId(), $_SESSION['full_name'] ?? '');
        if (!$r['ok']) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">' . htmlspecialchars($r['msg'] ?? 'Failed to create RFQ.') . '</div>']);
            return;
        }
        Router::redirect('GoodsRfq/view/' . (int)$r['id']);
    }

    public function viewAction($id = 0)
    {
        $m   = new GoodsRfq();
        $rfq = $m->byId((int)$id);
        if (!$rfq) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">RFQ not found.</div>']);
            return;
        }
        $db = new DB();
        // Load client PO line items (rows of the matrix)
        $cpoItems = $db->mySelect(
            "SELECT c0d, item_no, description, qty, unit, unit_price_sell, unit_price_cog
               FROM goods_client_po_items WHERE client_po_id = :id ORDER BY item_no ASC",
            [':id' => (int)$rfq['client_po_id']]
        ) ?: [];
        // Load supplier quotes (columns of the matrix) + quote items
        $quotes     = $m->quotesForRfq((int)$id);
        $quoteItems = $m->quoteItemsForRfq((int)$id);
        // Index quote items for easy view lookup: [cpo_item_id][rfq_quote_id] = row
        $qi = [];
        foreach ($quoteItems as $it) {
            $qi[(int)$it['client_po_item_id']][(int)$it['rfq_quote_id']] = $it;
        }
        // Vendors available for invitation (exclude already-invited)
        $invitedIds = array_map(fn($q) => (int)$q['vendor_id'], $quotes);
        $vendors    = $db->mySelect(
            "SELECT c0d, vendor_no, vendor_name, vendor_tin, vendor_category
               FROM vendors
              WHERE deleted = 0 AND status = 'ACTIVE'
              ORDER BY vendor_name ASC", []
        ) ?: [];
        $availVendors = array_filter($vendors, fn($v) => !in_array((int)$v['c0d'], $invitedIds, true));

        // Load any approval + LPOs
        $ac       = new ApprovalChain();
        $approval = ((int)$rfq['approval_id'] > 0) ? $ac->approvalById((int)$rfq['approval_id']) : [];
        $steps    = !empty($approval) ? $ac->stepsForChain((int)$approval['chain_id']) : [];
        $lpos     = $db->mySelect(
            "SELECT c0d, lpo_no, payee_name, amount, currency, cash_out_status
               FROM lpos WHERE sourced_from_rfq_id = :id AND deleted = 0 ORDER BY c0d ASC",
            [':id' => (int)$id]
        ) ?: [];

        $group      = strtolower($this->currentUserGroup());
        $canEdit    = in_array($group, ['procurement','projects coordinator','administrator'], true)
                      && in_array($rfq['status'], ['DRAFT','OPEN'], true);
        $canFinalize= in_array($group, ['procurement','administrator'], true)
                      && $rfq['status'] === 'OPEN';
        $awardedCount = 0; foreach ($quoteItems as $it) if ((int)$it['awarded_flag'] === 1) $awardedCount++;
        $needAwards   = count($cpoItems) - $awardedCount;

        $this->view->setLayout($this->roleLayout());
        $this->view->render('GoodsRfq/view', [
            'page_title'    => $rfq['rfq_no'] . ' · sourcing',
            'rfq'           => $rfq,
            'cpo_items'     => $cpoItems,
            'quotes'        => $quotes,
            'qi_index'      => $qi,
            'avail_vendors' => array_values($availVendors),
            'approval'      => $approval,
            'steps'         => $steps,
            'lpos'          => $lpos,
            'can_edit'      => $canEdit,
            'can_finalize'  => $canFinalize && $awardedCount > 0,
            'award_gap'     => $needAwards,
            'awarded_count' => $awardedCount,
        ]);
    }

    public function inviteSupplierAjAction()
    {
        $rid = (int)($_POST['rfq_id']    ?? 0);
        $vid = (int)($_POST['vendor_id'] ?? 0);
        if ($rid <= 0 || $vid <= 0) { $this->jsonResponse(['ok' => false, 'msg' => 'rfq_id and vendor_id required']); return; }
        $m = new GoodsRfq();
        $this->jsonResponse($m->inviteSupplier($rid, $vid, $this->currentUserId()));
    }

    public function saveQuoteItemAjAction()
    {
        $qid = (int)($_POST['rfq_quote_id']      ?? 0);
        $cid = (int)($_POST['client_po_item_id'] ?? 0);
        $up  = (float)($_POST['unit_price']    ?? 0);
        $qa  = (float)($_POST['qty_available'] ?? 0);
        $lt  = (int)($_POST['lead_time_days'] ?? 0);
        if ($qid <= 0 || $cid <= 0) { $this->jsonResponse(['ok' => false, 'msg' => 'quote + item required']); return; }
        $m = new GoodsRfq();
        $this->jsonResponse($m->saveQuoteItem($qid, $cid, $up, $qa, $lt));
    }

    public function awardAjAction()
    {
        $qiId = (int)($_POST['quote_item_id'] ?? 0);
        if ($qiId <= 0) { $this->jsonResponse(['ok' => false, 'msg' => 'quote_item_id required']); return; }
        $m = new GoodsRfq();
        $this->jsonResponse($m->awardItem($qiId, $this->currentUserId()));
    }

    public function awardAllFromSupplierAjAction()
    {
        $qid = (int)($_POST['rfq_quote_id'] ?? 0);
        if ($qid <= 0) { $this->jsonResponse(['ok' => false, 'msg' => 'rfq_quote_id required']); return; }
        $m = new GoodsRfq();
        $this->jsonResponse($m->awardAllFromSupplier($qid, $this->currentUserId()));
    }

    public function finalizeAjAction()
    {
        $rid = (int)($_POST['rfq_id'] ?? 0);
        if ($rid <= 0) { $this->jsonResponse(['ok' => false, 'msg' => 'rfq_id required']); return; }
        $m = new GoodsRfq();
        $r = $m->finalize($rid, $this->currentUserId(), $_SESSION['full_name'] ?? '', $_SESSION['user_group_name'] ?? '');
        $this->jsonResponse($r);
    }
}
