<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\InventoryLog;
use App\Models\AuditLog;

class InventoryController extends Controller
{
    public function stockIn(Request $request)
    {
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
            'reason' => 'nullable|string',
        ]);

        $product = Product::findOrFail($validated['product_id']);
        $product->increment('current_stock', $validated['quantity']);

        $log = InventoryLog::create([
            'product_id' => $product->id,
            'type' => 'stock_in',
            'quantity' => $validated['quantity'],
            'reason' => $validated['reason'] ?? 'Manual Stock In',
            'created_by' => $request->user()?->id,
        ]);

        AuditLog::create([
            'user_id' => $request->user()?->id,
            'user_name' => $request->user()?->name,
            'action' => 'STOCK_IN',
            'module' => 'INVENTORY',
            'description' => "Added {$validated['quantity']} units to {$product->name}",
            'ip_address' => $request->ip(),
        ]);

        return response()->json(['success' => true, 'message' => 'Stock In recorded successfully', 'data' => $product]);
    }

    public function stockOut(Request $request)
    {
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
            'reason' => 'nullable|string',
        ]);

        $product = Product::findOrFail($validated['product_id']);
        if ($product->current_stock < $validated['quantity']) {
            return response()->json(['success' => false, 'message' => 'Insufficient current stock available'], 400);
        }

        $product->decrement('current_stock', $validated['quantity']);

        $log = InventoryLog::create([
            'product_id' => $product->id,
            'type' => 'stock_out',
            'quantity' => $validated['quantity'],
            'reason' => $validated['reason'] ?? 'Manual Stock Out / Removal',
            'created_by' => $request->user()?->id,
        ]);

        AuditLog::create([
            'user_id' => $request->user()?->id,
            'user_name' => $request->user()?->name,
            'action' => 'STOCK_OUT',
            'module' => 'INVENTORY',
            'description' => "Removed {$validated['quantity']} units from {$product->name}",
            'ip_address' => $request->ip(),
        ]);

        return response()->json(['success' => true, 'message' => 'Stock Out recorded successfully', 'data' => $product]);
    }

    public function damagedStock(Request $request)
    {
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
            'reason' => 'nullable|string',
        ]);

        $product = Product::findOrFail($validated['product_id']);
        if ($product->current_stock < $validated['quantity']) {
            return response()->json(['success' => false, 'message' => 'Insufficient current stock available'], 400);
        }

        $product->decrement('current_stock', $validated['quantity']);

        $reasonText = 'Damaged Stock: ' . ($validated['reason'] ?? 'Unspecified defect/damage');

        $log = InventoryLog::create([
            'product_id' => $product->id,
            'type' => 'damaged_stock',
            'quantity' => $validated['quantity'],
            'reason' => $reasonText,
            'created_by' => $request->user()?->id,
        ]);

        AuditLog::create([
            'user_id' => $request->user()?->id,
            'user_name' => $request->user()?->name,
            'action' => 'DAMAGED_STOCK',
            'module' => 'INVENTORY',
            'description' => "Marked {$validated['quantity']} units of '{$product->name}' as Damaged Stock. Reason: {$reasonText}",
            'ip_address' => $request->ip(),
        ]);

        return response()->json(['success' => true, 'message' => 'Damaged Stock recorded successfully', 'data' => $product]);
    }

    public function lowStockAlerts()
    {
        $lowStockProducts = Product::with(['category', 'brand'])
            ->whereColumn('current_stock', '<=', 'min_stock_alert')
            ->orderBy('current_stock', 'asc')
            ->get();
        return response()->json(['success' => true, 'data' => $lowStockProducts]);
    }
}
}
