<?php

namespace App\Http\Controllers;

use App\Models\StockAdjustment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class StockAdjustmentController extends Controller
{
    public function store(Request $request)
    {
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous ne pouvez pas créer un ajustement de stock.');
        }

        $validated = $request->validate([
            'type' => ['required', 'in:increase,decrease'],
            'reason' => ['nullable', 'string'],
        ]);

        $adjustment = StockAdjustment::create([
            'reference' => StockAdjustment::generateReference(),
            'type' => $validated['type'],
            'reason' => $validated['reason'] ?? null,
            'user_id' => Auth::id(),
            'status' => StockAdjustment::STATUS_DRAFT,
        ]);

        return redirect()->route('stock-adjustments.edit', $adjustment)->with('success', 'Ajustement créé avec succès.');
    }

    public function apply(StockAdjustment $stockAdjustment)
    {
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous ne pouvez pas appliquer un ajustement de stock.');
        }

        if ($stockAdjustment->status === StockAdjustment::STATUS_APPLIED) {
            return back()->with('error', 'Cet ajustement a déjà été appliqué.');
        }

        // Load items with their products to avoid N+1 queries
        $stockAdjustment->load('items.product');

        if ($stockAdjustment->items->isEmpty()) {
            return back()->with('error', 'Vous ne pouvez pas appliquer un ajustement de stock sans articles.');
        }

        DB::transaction(function () use ($stockAdjustment) {
            // Process each item in the adjustment
            foreach ($stockAdjustment->items as $item) {
                if ($stockAdjustment->type === StockAdjustment::TYPE_INCREASE) {
                    $item->product->increment('current_stock', $item->quantity);
                } else {
                    $item->product->decrement('current_stock', $item->quantity);
                }
            }

            $stockAdjustment->update([
                'status' => StockAdjustment::STATUS_APPLIED,
                'applied_at' => now(),
                'applied_by' => Auth::id(),
            ]);
        });

        return redirect()->route('stock-adjustments.show', $stockAdjustment)->with('success', 'Ajustement appliqué avec succès.');
    }

    public function print(StockAdjustment $stockAdjustment)
    {
        $stockAdjustment->load(['items.product', 'user']);

        return view('livewire.stock-adjustments.print', [
            'adjustment' => $stockAdjustment,
        ]);
    }

    public function destroy(StockAdjustment $stockAdjustment)
    {
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous ne pouvez pas supprimer un ajustement.');
        }

        if ($stockAdjustment->status === StockAdjustment::STATUS_APPLIED) {
            return back()->with('error', 'Vous ne pouvez pas supprimer un ajustement déjà appliqué.');
        }

        $stockAdjustment->delete();

        return redirect()->route('stock-adjustments.index')->with('success', 'Ajustement supprimé avec succès.');
    }
}
