<?php

namespace Modules\Vrc\Services\Forecast;

use Illuminate\Support\Facades\DB;

/**
 * Lightweight historical-trend analytics (Phase 5, §10.3): parts-demand forecast
 * (simple moving average over recent monthly consumption) and upcoming service-due
 * load from reminders. Heuristic by design — no external ML — and a natural place
 * to later delegate to AiCore for richer prediction.
 */
class DemandForecastService
{
    /** Forecast next-period qty per part from the last $months of consumption. */
    public function partsDemand(int $businessId, int $months = 6, int $limit = 25): array
    {
        $since = now()->subMonths($months)->startOfMonth()->toDateString();

        $rows = DB::table('vrc_repair_order_parts')
            ->where('business_id', $businessId)
            ->where('created_at', '>=', $since . ' 00:00:00')
            ->selectRaw('description, COALESCE(SUM(qty),0) as total_qty, COUNT(*) as lines')
            ->groupBy('description')
            ->orderByDesc('total_qty')
            ->limit($limit)
            ->get();

        return $rows->map(function ($r) use ($months) {
            $avg = $months > 0 ? $r->total_qty / $months : $r->total_qty;
            return [
                'part'           => $r->description,
                'total_qty'      => (float) $r->total_qty,
                'monthly_avg'    => round($avg, 2),
                'forecast_next'  => (int) ceil($avg),
            ];
        })->toArray();
    }

    /** Count of service reminders coming due in the next $days. */
    public function upcomingServiceLoad(int $businessId, int $days = 30): array
    {
        $until = now()->addDays($days)->toDateString();

        $due = DB::table('vrc_service_reminders')
            ->where('business_id', $businessId)
            ->where('status', 'pending')
            ->whereNotNull('due_date')
            ->where('due_date', '<=', $until)
            ->count();

        return ['window_days' => $days, 'due' => $due];
    }
}
