<?php
/**
 * GoodsScrubPackController — 7-pillar scrub authoring surface (Slice 8h).
 *
 *   /GoodsScrubPack/open/{client_po_id}  — get-or-create then redirect to view
 *   /GoodsScrubPack/view/{scrub_id}      — 7-pillar editor
 *   /GoodsScrubPack/addLineAj            — POST scrub_id + pillar + line-shape data
 *   /GoodsScrubPack/removeLineAj         — POST scrub_id + pillar + line_id
 *   /GoodsScrubPack/setMaterialsUnitCostAj — POST scrub_id + line_id + unit_cost
 *   /GoodsScrubPack/markCompleteAj       — POST scrub_id
 */
class GoodsScrubPackController extends Controller
{
    public function openAction($clientPoId = 0)
    {
        $poId = (int)$clientPoId;
        if (!class_exists('GoodsScrubPack')) require_once ROOT . '/app/models/GoodsScrubPack.php';
        $res = (new GoodsScrubPack())->getOrCreateDraft(
            $poId,
            (int)($_SESSION['user_id']    ?? 0),
            (string)($_SESSION['full_name'] ?? '')
        );
        if (!$res['ok']) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-warning">' . htmlspecialchars($res['msg']) . '</div>']);
            return;
        }
        Router::redirect('GoodsScrubPack/view/' . (int)$res['id']);
    }

    public function viewAction($scrubId = 0)
    {
        $scrubId = (int)$scrubId;
        if (!class_exists('GoodsScrubPack')) require_once ROOT . '/app/models/GoodsScrubPack.php';
        $sp = new GoodsScrubPack();
        $scrub = $sp->findById($scrubId);
        if (!$scrub) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Scrub not found.</div>']);
            return;
        }

        $db = new DB();
        $prj = $db->mySelect(
            "SELECT c0d, project_no, project_name, project_customer, currency FROM c_projects WHERE c0d = :p",
            [':p' => (int)$scrub['project_id']]
        );
        $po  = $db->mySelect(
            "SELECT c0d, client_po_no, status, subtotal_sell, subtotal_cog, total FROM goods_client_pos WHERE c0d = :id",
            [':id' => (int)$scrub['client_po_id']]
        );

        $this->view->setLayout($this->roleLayout());
        $this->view->render('GoodsScrubPack/view', [
            'page_title' => 'Scrub · ' . ($scrub['scrub_no'] ?? ''),
            'scrub'      => $scrub,
            'project'    => $prj[0] ?? [],
            'client_po'  => $po[0]  ?? [],
            'lines'      => $sp->allLines($scrubId),
            'pillars'    => GoodsScrubPack::PILLARS,
            'can_edit'   => $scrub['status'] === 'DRAFT',
        ]);
    }

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

    public function addLineAjAction()
    {
        header('Content-Type: application/json');
        try {
            if (!class_exists('GoodsScrubPack')) require_once ROOT . '/app/models/GoodsScrubPack.php';
            $sp    = new GoodsScrubPack();
            $sid   = (int)($_POST['scrub_id'] ?? 0);
            $pillar= (string)($_POST['pillar'] ?? '');
            // Take the whole $_POST as the line-shape (per-pillar model unpacks what it needs).
            $data  = $_POST;
            unset($data['scrub_id'], $data['pillar']);
            echo json_encode($sp->addLine($sid, $pillar, $data));
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function removeLineAjAction()
    {
        header('Content-Type: application/json');
        try {
            if (!class_exists('GoodsScrubPack')) require_once ROOT . '/app/models/GoodsScrubPack.php';
            echo json_encode((new GoodsScrubPack())->removeLine(
                (int)($_POST['scrub_id'] ?? 0),
                (string)($_POST['pillar'] ?? ''),
                (int)($_POST['line_id']  ?? 0)
            ));
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

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

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