<?php

namespace App\Http\Controllers;

use App\Models\Inventory;
use App\Models\InventoryTransaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class InventoryTransactionController extends Controller
{
    /**
     * Display a listing of the inventory transactions.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $query = InventoryTransaction::query();
        
        // Aplicar filtros si existen
        if ($request->has('inventory_id') && $request->inventory_id) {
            $query->where('inventory_id', $request->inventory_id);
        }
        
        if ($request->has('transaction_type') && $request->transaction_type) {
            $query->where('transaction_type', $request->transaction_type);
        }
        
        if ($request->has('date_from') && $request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        
        if ($request->has('date_to') && $request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }
        
        // Cargar relaciones
        $query->with(['inventory', 'user']);
        
        // Ordenar por fecha más reciente
        $query->orderBy('created_at', 'desc');
        
        // Paginar resultados
        $transactions = $query->paginate(20);
        
        // Obtener tipos de transacción para filtro
        $transactionTypes = [
            InventoryTransaction::TYPE_ENTRY => 'Entrada',
            InventoryTransaction::TYPE_EXIT => 'Salida',
            InventoryTransaction::TYPE_ADJUSTMENT => 'Ajuste',
            InventoryTransaction::TYPE_TRANSFER => 'Transferencia'
        ];
        
        // Obtener productos para filtro (limitados a 100 para no sobrecargar el dropdown)
        $inventoryItems = Inventory::orderBy('name')->take(100)->get();
        
        return view('admin.inventory.transactions.index', compact('transactions', 'transactionTypes', 'inventoryItems'));
    }

    /**
     * Show the form for creating a new inventory transaction.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $inventoryItems = Inventory::orderBy('name')->get();
        $transactionTypes = [
            InventoryTransaction::TYPE_ENTRY => 'Entrada',
            InventoryTransaction::TYPE_EXIT => 'Salida',
            InventoryTransaction::TYPE_ADJUSTMENT => 'Ajuste',
            InventoryTransaction::TYPE_TRANSFER => 'Transferencia'
        ];
        
        return view('admin.inventory.transactions.create', compact('inventoryItems', 'transactionTypes'));
    }

    /**
     * Store a newly created inventory transaction in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'inventory_id' => 'required|exists:inventory,id',
            'transaction_type' => 'required|in:entry,exit,adjustment,transfer',
            'quantity' => 'required|numeric|min:0.01',
            'reference' => 'nullable|string|max:255',
            'notes' => 'nullable|string',
        ]);
        
        // Obtener el ítem de inventario
        $inventoryItem = Inventory::findOrFail($validatedData['inventory_id']);
        
        // Calcular nueva cantidad basada en el tipo de transacción
        $previousQuantity = $inventoryItem->quantity;
        $quantity = abs($validatedData['quantity']);
        
        switch ($validatedData['transaction_type']) {
            case InventoryTransaction::TYPE_ENTRY:
                $newQuantity = $previousQuantity + $quantity;
                break;
                
            case InventoryTransaction::TYPE_EXIT:
                // Verificar si hay suficiente stock
                if ($quantity > $previousQuantity) {
                    return back()->withErrors(['quantity' => 'No hay suficiente stock disponible.'])
                                ->withInput();
                }
                $newQuantity = $previousQuantity - $quantity;
                break;
                
            case InventoryTransaction::TYPE_ADJUSTMENT:
                $newQuantity = $quantity; // La cantidad proporcionada es el nuevo valor total
                break;
                
            case InventoryTransaction::TYPE_TRANSFER:
                // Para transferencias, necesitaríamos más lógica y quizás otro endpoint
                // Por ahora, tratarlo como una salida
                if ($quantity > $previousQuantity) {
                    return back()->withErrors(['quantity' => 'No hay suficiente stock disponible para transferir.'])
                                ->withInput();
                }
                $newQuantity = $previousQuantity - $quantity;
                break;
                
            default:
                return back()->withErrors(['transaction_type' => 'Tipo de transacción no válido.'])
                            ->withInput();
        }
        
        // Crear la transacción
        $transaction = InventoryTransaction::create([
            'inventory_id' => $validatedData['inventory_id'],
            'user_id' => Auth::id(),
            'transaction_type' => $validatedData['transaction_type'],
            'quantity' => $quantity,
            'previous_quantity' => $previousQuantity,
            'new_quantity' => $newQuantity,
            'reference' => $validatedData['reference'] ?? null,
            'notes' => $validatedData['notes'] ?? null,
        ]);
        
        // Actualizar la cantidad en el inventario
        $inventoryItem->quantity = $newQuantity;
        $inventoryItem->save();
        
        return redirect()->route('inventory.transactions.index')
            ->with('success', 'Transacción registrada exitosamente.');
    }

    /**
     * Display the specified inventory transaction.
     *
     * @param  \App\Models\InventoryTransaction  $transaction
     * @return \Illuminate\Http\Response
     */
    public function show(InventoryTransaction $transaction)
    {
        $transaction->load(['inventory', 'user']);
        
        return view('admin.inventory.transactions.show', compact('transaction'));
    }

    /**
     * Show transactions for a specific inventory item.
     *
     * @param  \App\Models\Inventory  $inventory
     * @return \Illuminate\Http\Response
     */
    public function forInventory(Inventory $inventory)
    {
        $transactions = $inventory->transactions()
            ->with('user')
            ->orderBy('created_at', 'desc')
            ->paginate(20);
            
        return view('admin.inventory.transactions.for_inventory', compact('inventory', 'transactions'));
    }
} 