<?php

namespace App\Http\Controllers;

use App\Models\DisposedProduct;
use App\Models\Product;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ExpiryController extends Controller
{
    public function index(Request $request)
    {
        $expired = Product::whereNotNull('expiry_date')
            ->whereDate('expiry_date', '<', now())
            ->with('category')
            ->orderBy('expiry_date')
            ->get();

        $expiringSoon = Product::whereNotNull('expiry_date')
            ->whereDate('expiry_date', '>=', now())
            ->whereDate('expiry_date', '<=', now()->addDays(30))
            ->with('category')
            ->orderBy('expiry_date')
            ->get();

        $filter = $request->get('filter', 'all');

        if ($filter === 'expired') {
            $products = $expired;
        } elseif ($filter === 'expiring_7') {
            $products = Product::whereNotNull('expiry_date')
                ->whereDate('expiry_date', '>=', now())
                ->whereDate('expiry_date', '<=', now()->addDays(7))
                ->with('category')
                ->orderBy('expiry_date')
                ->get();
        } elseif ($filter === 'expiring_30') {
            $products = $expiringSoon;
        } else {
            $products = Product::whereNotNull('expiry_date')
                ->with('category')
                ->orderBy('expiry_date')
                ->get();
        }

        return view('expiry.index', compact('expired', 'expiringSoon', 'products', 'filter'));
    }

    public function update(Request $request, Product $product)
    {
        $request->validate([
            'expiry_date' => 'nullable|date',
        ]);

        $product->update([
            'expiry_date' => $request->expiry_date,
        ]);

        return back()->with('success', 'Expiry date updated successfully.');
    }

    public function markAsExpired(Product $product)
    {
        $product->update([
            'expiry_date' => now()->subDay(),
        ]);

        return back()->with('success', 'Product marked as expired.');
    }

    public function extend(Request $request, Product $product)
    {
        $request->validate([
            'days' => 'required|integer|min:1|max:365',
        ]);

        $newDate = Carbon::parse($product->expiry_date)->addDays($request->days);

        $product->update([
            'expiry_date' => $newDate,
        ]);

        return back()->with('success', 'Expiry date extended by '.$request->days.' days.');
    }

    public function dispose(Request $request, Product $product)
    {
        $request->validate([
            'quantity' => 'required|integer|min:1|max:'.$product->stock_quantity,
            'reason' => 'required|string|max:255',
        ]);

        $unitCost = $product->cost_price ?? 0;
        $totalValue = $unitCost * $request->quantity;

        DisposedProduct::create([
            'product_id' => $product->id,
            'user_id' => auth()->id(),
            'quantity' => $request->quantity,
            'unit_cost' => $unitCost,
            'total_value' => $totalValue,
            'reason' => $request->reason,
        ]);

        $product->decrement('stock_quantity', $request->quantity);

        return back()->with('success', $request->quantity.' units disposed.');
    }
}
