<?php

namespace App\Repositories\Shop;

use App\Mail\AlerteStock;
use App\Models\Shop\Offer;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class OfferStocks
{
    public static function decreaseStock($item)
    {
        $offer = Offers::get($item['offer_id']);
        $previousStock = $offer->stock_current;
        $offer->stock_current = $offer->stock_current - $item['quantity'];
        if ($offer->stock_current <= 0) {
            $offer->stock_current = 0;
        }

        $saved = $offer->save();

        if ($saved) {
            self::checkStockAlert($offer, $previousStock);
        }

        return $saved;
    }

    public static function checkStockAlert($offer, $previousStock)
    {
        $threshold = (float) $offer->minimum_ondemand;
        if ($threshold <= 0) {
            return;
        }

        $crossedThreshold = $previousStock > $threshold
            && $offer->stock_current <= $threshold;

        if (! $crossedThreshold) {
            return;
        }

        try {
            $offer->load('article');
            Mail::to('commande@jardinenvie.com')
                ->send(new AlerteStock($offer));
            Log::info('Stock alert email sent', [
                'offer_id' => $offer->id,
                'article' => $offer->article->name ?? $offer->article_id,
                'stock_current' => $offer->stock_current,
                'threshold' => $threshold,
            ]);
        } catch (\Throwable $e) {
            Log::error('Failed to send stock alert email', [
                'offer_id' => $offer->id,
                'stock_current' => $offer->stock_current,
                'exception' => $e->getMessage(),
            ]);
        }
    }

    public static function restoreStock($orderId)
    {
        $details = \App\Models\Shop\OrderDetail::where('order_id', $orderId)->get();

        foreach ($details as $detail) {
            $offer = Offers::get($detail->offer_id);
            if ($offer) {
                $offer->stock_current = $offer->stock_current + $detail->quantity;
                $offer->save();
            }
        }
    }

    public static function checkStockForOrder($orderId)
    {
        $details = \App\Models\Shop\OrderDetail::where('order_id', $orderId)->get();
        $insufficients = [];

        foreach ($details as $detail) {
            $offer = Offers::get($detail->offer_id);
            if ($offer && $offer->stock_current < $detail->quantity) {
                $offer->load('article');
                $insufficients[] = [
                    'name' => $offer->article->name ?? 'Offre #'.$offer->id,
                    'stock' => $offer->stock_current,
                    'quantity' => $detail->quantity,
                ];
            }
        }

        return $insufficients;
    }

    public static function decreaseStockForOrder($orderId)
    {
        $details = \App\Models\Shop\OrderDetail::where('order_id', $orderId)->get();

        foreach ($details as $detail) {
            $offer = Offers::get($detail->offer_id);
            if ($offer) {
                $offer->stock_current = max(0, $offer->stock_current - $detail->quantity);
                $offer->save();
            }
        }
    }

    public static function getStockCurrent($id)
    {
        return Offers::getField($id, 'stock_current');
    }

    public static function getAlerts()
    {
        return Offer::active()->where('stock_current', '<', 15)->get();
    }

    public static function countAlerts()
    {
        return Offer::active()->where('stock_current', '<', 15)->count();
    }
}
