<?php

namespace Modules\Vrc\Http\Controllers;

use Modules\Vrc\Entities\VrcRepairOrderPart;
use Modules\Vrc\Services\Contracts\StockServiceContract;

/**
 * Repair-parts procurement is the ERP's job (spec §6.7 / §10 Phase 9). VRC
 * only surfaces what needs ordering and the low-stock picture, then hands off
 * to the ERP's existing purchase screens — no parallel PO engine.
 */
class ProcurementController extends VrcBaseController
{
    /** Special-order part lines on open repair orders that need a PO. */
    public function toOrder()
    {
        $this->guard('vrc.repair_order.manage');

        $parts = VrcRepairOrderPart::where('vrc_repair_order_parts.business_id', $this->businessId())
            ->where('source', 'special_order')
            ->join('vrc_repair_orders as ro', 'ro.id', '=', 'vrc_repair_order_parts.repair_order_id')
            ->whereNotIn('ro.status', ['completed', 'cancelled'])
            ->select(['vrc_repair_order_parts.*', 'ro.number as ro_number', 'ro.id as ro_id'])
            ->get();

        // The ERP purchase-create screen (reused; pre-fill via its own UI).
        $erpPurchaseUrl = url('purchases/create');

        return view('vrc::procurement.to_order', compact('parts', 'erpPurchaseUrl'));
    }

    /** Low-stock report from ERP inventory. */
    public function lowStock(StockServiceContract $stock)
    {
        $this->guard('vrc.reports.view');
        $rows = $stock->lowStock($this->businessId(), null, 100);

        return view('vrc::procurement.low_stock', compact('rows'));
    }
}
