<?php

namespace Modules\Vrc\Http\Controllers;

use App\Transaction;
use Modules\Vrc\Entities\VrcRepairOrder;
use Modules\Vrc\Services\Contracts\StockServiceContract;

/**
 * VRC dashboard / module landing page. Owner tiles read from VRC repair orders
 * and the linked ERP invoices/inventory (spec §6.14). Advisor/Technician
 * dashboards are expanded in Phase 8/11.
 */
class VrcController extends VrcBaseController
{
    public function index(StockServiceContract $stock)
    {
        $this->guard('vrc.access');
        $bid = $this->businessId();

        // Open orders by status.
        $byStatus = VrcRepairOrder::where('business_id', $bid)
            ->whereNotIn('status', ['completed', 'cancelled'])
            ->selectRaw('status, COUNT(*) as c')->groupBy('status')->pluck('c', 'status')->toArray();

        // Revenue from VRC-linked ERP invoices (today / month-to-date).
        $invoiceIds = VrcRepairOrder::where('business_id', $bid)->whereNotNull('erp_invoice_id')->pluck('erp_invoice_id');
        $revenueToday = (float) Transaction::whereIn('id', $invoiceIds)->whereDate('transaction_date', today())->sum('final_total');
        $revenueMtd = (float) Transaction::whereIn('id', $invoiceIds)->whereMonth('transaction_date', now()->month)->whereYear('transaction_date', now()->year)->sum('final_total');

        $tiles = [
            'open_orders'      => array_sum($byStatus),
            'ready_for_pickup' => $byStatus['ready_for_pickup'] ?? 0,
            'in_progress'      => $byStatus['in_progress'] ?? 0,
            'revenue_today'    => $revenueToday,
            'revenue_mtd'      => $revenueMtd,
        ];

        $lowStock = [];
        try {
            $lowStock = $stock->lowStock($bid, null, 8);
        } catch (\Throwable $e) {
            // Inventory widget is best-effort.
        }

        return view('vrc::dashboard.index', compact('tiles', 'byStatus', 'lowStock'));
    }
}
