<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tenant\ProductVariant;
use App\Models\Tenant\StockMovement;
use Illuminate\Support\Facades\DB;

class StockAdjustmentController extends Controller
{
    public function index()
    {
        $variants = ProductVariant::with('product')
            ->select('product_variants.*', 'products.name as product_name')
            ->join('products', 'product_variants.product_id', '=', 'products.id')
            ->get()
            ->map(function($variant) {
                $variant->full_name = $variant->product_name . ' - ' . $variant->name;
                return $variant;
            });

        return view('tenant.stock-adjustments.index', compact('variants'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'variant_id' => 'required|exists:tenant.product_variants,id',
            'adjustment_type' => 'required|in:add,subtract,set',
            'quantity' => 'required|numeric|min:0',
            'reason' => 'required|string|max:255',
        ]);

        try {
            DB::transaction(function () use ($validated) {
                $variant = ProductVariant::find($validated['variant_id']);
                $oldStock = $variant->stock;
                $newStock = $oldStock;
                $movementQuantity = $validated['quantity'];

                switch ($validated['adjustment_type']) {
                    case 'add':
                        $newStock = $oldStock + $movementQuantity;
                        break;
                    case 'subtract':
                        $newStock = max(0, $oldStock - $movementQuantity);
                        $movementQuantity = $oldStock - $newStock; // Actual quantity subtracted
                        break;
                    case 'set':
                        $newStock = $movementQuantity;
                        $movementQuantity = $newStock - $oldStock;
                        break;
                }

                // Update variant stock
                $variant->update(['stock' => $newStock]);

                // Record stock movement
                StockMovement::record(
                    $validated['variant_id'],
                    abs($movementQuantity),
                    'adjustment',
                    'manual',
                    null,
                    $validated['reason'] . " (Stock: {$oldStock} → {$newStock})"
                );
            });

            return response()->json([
                'success' => true, 
                'message' => 'Stock adjusted successfully!'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false, 
                'message' => 'Stock adjustment failed: ' . $e->getMessage()
            ], 500);
        }
    }

    public function history(Request $request)
    {
        $variantId = $request->input('variant_id');
        
        $movements = StockMovement::with(['variant.product', 'user'])
            ->where('movement_type', 'adjustment')
            ->when($variantId, function($query) use ($variantId) {
                return $query->where('variant_id', $variantId);
            })
            ->latest()
            ->paginate(20);

        return view('tenant.stock-adjustments.history', compact('movements', 'variantId'));
    }
}
