<?php

namespace App\Http\Controllers;

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

class InventoryController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:products.inventory.view')->only(['index', 'log']);
        $this->middleware('permission:products.inventory.update')->only(['addStock']);
    }

    public function index()
    {
        $products = Product::with(['inventoryLogs', 'images', 'colors', 'sizes', 'measurements'])
            ->latest()
            ->paginate(10);

        // Calculate stock for each product
        $products->getCollection()->transform(function ($product) {
            $totalStock = 0;

            // Calculate stock from variants if they exist
            if ($product->has_color) {
                $totalStock += $product->colors->sum('pivot.stock');
            } elseif ($product->has_size) {
                $totalStock += $product->sizes->sum('pivot.stock');
            } elseif ($product->has_measurement) {
                $totalStock += $product->measurements->sum('pivot.stock');
            } else {
                // Fallback to logs sum for simple products
                $totalStock = $product->inventoryLogs->sum('quantity');
            }

            $product->current_stock = $totalStock;

            return $product;
        });

        return view('products.inventory.index', compact('products'));
    }

    public function addStock(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
            'color_id' => 'nullable|exists:product_colors,id',
            'size_id' => 'nullable|exists:product_sizes,id',
            'measurement_id' => 'nullable|exists:product_measurements,id',
        ]);

        $product = Product::findOrFail($request->product_id);

        // Validation: Ensure variant is selected if product has variants
        if ($product->has_color && ! $request->color_id) {
            return redirect()->back()->withErrors(['color_id' => __('products.inventory.validation.color_required')]);
        }
        if ($product->has_size && ! $request->size_id) {
            return redirect()->back()->withErrors(['size_id' => __('products.inventory.validation.size_required')]);
        }
        if ($product->has_measurement && ! $request->measurement_id) {
            return redirect()->back()->withErrors(['measurement_id' => __('products.inventory.validation.measurement_required')]);
        }

        DB::transaction(function () use ($request, $product) {
            // Create Log
            ProductInventoryLog::create([
                'product_id' => $request->product_id,
                'user_id' => Auth::id(),
                'quantity' => $request->quantity,
                'color_id' => $request->color_id,
                'size_id' => $request->size_id,
                'measurement_id' => $request->measurement_id,
            ]);

            // Update Pivot Stock
            if ($request->color_id) {
                $product->colors()->updateExistingPivot($request->color_id, ['stock' => DB::raw('stock + '.$request->quantity)]);
            }
            if ($request->size_id) {
                $product->sizes()->updateExistingPivot($request->size_id, ['stock' => DB::raw('stock + '.$request->quantity)]);
            }
            if ($request->measurement_id) {
                $product->measurements()->updateExistingPivot($request->measurement_id, ['stock' => DB::raw('stock + '.$request->quantity)]);
            }
        });

        return redirect()->back()->with('success', __('products.inventory.messages.stock_added'));
    }

    public function log(Product $product)
    {
        $logs = $product->inventoryLogs()
            ->with(['user', 'color', 'size', 'measurement'])
            ->latest()
            ->get();

        return view('products.inventory.partials.log_content', compact('product', 'logs'));
    }
}
