<?php
/**
 * GoodsScrubController — PC scrubs the auto-created client POs on a project.
 *
 *   /GoodsScrub/scrubPo/{project_id}   Landing: list all client POs for the project, pick one
 *   /GoodsScrub/scrubItem/{po_id}      Detail: per-line editor (description/qty/sell/cog/margin)
 *   /GoodsScrub/saveItemAj             POST item_id + fields → recompute + rollup
 *   /GoodsScrub/markScrubbedAj         POST po_id [+ notes] → status DRAFT→CONFIRMED
 *   /GoodsScrub/unscrubAj              POST po_id → revert to DRAFT (if no RFQ started)
 */
class GoodsScrubController extends Controller
{
    public function scrubPoAction($projectId = 0)
    {
        $projectId = (int)$projectId;
        $db = new DB();
        $projectRow = $db->mySelect(
            "SELECT c0d, project_no, project_name, project_type, project_customer, currency, contract_value
               FROM c_projects WHERE c0d = :p AND deleted = 0",
            [':p' => $projectId]
        );
        if (empty($projectRow)) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Project not found.</div>']);
            return;
        }
        $project = $projectRow[0];
        $pos     = (new GoodsScrub())->posForProject($projectId);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('GoodsScrub/scrubPo', [
            'page_title' => 'PC Scrub · ' . ($project['project_no'] ?? '') . ' · ' . ($project['project_name'] ?? ''),
            'project'    => $project,
            'pos'        => $pos,
        ]);
    }

    public function scrubItemAction($poId = 0)
    {
        $poId = (int)$poId;
        $m = new GoodsClientPos();
        $po = $m->byId($poId);
        if (!$po) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Client PO not found.</div>']);
            return;
        }
        $items = $m->itemsFor($poId);

        // Load parent project for the breadcrumb
        $db = new DB();
        $projRow = $db->mySelect("SELECT c0d, project_no, project_name FROM c_projects WHERE c0d = :p", [':p' => (int)$po['project_id']]);
        $project = $projRow[0] ?? [];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('GoodsScrub/scrubItem', [
            'page_title' => 'PC Scrub · ' . $po['client_po_no'],
            'po'         => $po,
            'items'      => $items,
            'project'    => $project,
        ]);
    }

    public function saveItemAjAction()
    {
        try {
            (new GoodsScrub())->saveItem(
                (int)($_POST['item_id'] ?? 0),
                [
                    'description'     => (string)($_POST['description']     ?? ''),
                    'qty'             => (float) ($_POST['qty']             ?? 0),
                    'unit'            => (string)($_POST['unit']            ?? ''),
                    'unit_price_sell' => (float) ($_POST['unit_price_sell'] ?? 0),
                    'unit_price_cog'  => (float) ($_POST['unit_price_cog']  ?? 0),
                    'notes'           => (string)($_POST['notes']           ?? ''),
                ],
                $this->currentUserId()
            );
            $this->jsonResponse(['ok' => true, 'msg' => 'Line saved.']);
        } catch (\Throwable $e) {
            $this->jsonResponse(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }

    public function markScrubbedAjAction()
    {
        try {
            (new GoodsScrub())->markScrubbed(
                (int)($_POST['po_id'] ?? 0),
                $this->currentUserId(),
                (string)($_SESSION['full_name'] ?? ''),
                (string)($_POST['notes'] ?? '')
            );
            $this->jsonResponse(['ok' => true, 'msg' => 'PO scrub complete — ready for sourcing.']);
        } catch (\Throwable $e) {
            $this->jsonResponse(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }

    public function unscrubAjAction()
    {
        try {
            (new GoodsScrub())->unscrub((int)($_POST['po_id'] ?? 0), $this->currentUserId());
            $this->jsonResponse(['ok' => true, 'msg' => 'Scrub reverted.']);
        } catch (\Throwable $e) {
            $this->jsonResponse(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }
}
