<?php

namespace App\Http\Controllers;

use App\Models\StockIn;
use App\Models\StockOut;
use App\Models\Product;
use App\Models\OrderDetail;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class InventoryController extends Controller
{
    public function inventory(){
        $products = Product::select('id', 'name')->orderBy('id', 'desc')->get();

        $inventories = $products->map(function ($product) {
            $totalStockIn =StockIn::where('product_id', $product->id)->sum('quantity');
            $totalStockOut =StockOut::where('product_id', $product->id)->sum('quantity');
            $totalSold = OrderDetail::where('product_id', $product->id)->sum('qty');
            $availbleStockIn = $totalStockIn - $totalStockOut;
            $currentStock = $totalStockOut - $totalSold;

            $product->total_stock_in = $totalStockIn;
            $product->total_stock_out = $totalStockOut;
            $product->total_sold = $totalSold;
            $product->availble_stock_in = $availbleStockIn;
            $product->current_stock = $currentStock;

            return $product;
        });

        return view('inventory.inventory', compact('inventories'));
    }


    public function stockInView() {
        $inventories = StockIn::with([
        'product:id,name', 'creator:id,name'])->whereHas('product')->orderBy('id', 'desc')->get();

        return view('inventory.stock-in-view', compact('inventories'));
    }


    public function stockOutView(){
        $inventories = StockOut::with('product:id,name', 'creator:id,name')->whereHas('product')->orderBy('id', 'desc')->get();

        return view('inventory.stock-Out-view', compact('inventories'));
    }


    public function create(){
        return view('inventory.create');
    }

    public function edit($id){
        $inventory = Inventory::findOrFail($id);
        $products = Product::where('status', static::active)->get();
        return view('Inventory.edit', compact('inventory', 'products'));
    }

    public function update(Request $request, $id){
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'total_quantity' => 'required|numeric|min:0',
        ]);

        $inventory = Inventory::findOrFail($id);
        $product = Product::findOrFail($request->product_id);
        $inventory_price = $product->purchase_price * $request->total_quantity;

        $inventory->update([
            'product_id' => $request->product_id,
            'total_quantity' => $request->total_quantity,
            'inventory_price' => $inventory_price,
        ]);

        return redirect('inventory')->with('success', 'Inventory updated successfully!');
    }

    public function destroy($id)
    {
        Inventory::findOrFail($id)->delete();
        return redirect('inventory')->with('success', 'Inventory deleted successfully!');
    }

    public function sales(){
        $orders = Order::orderBy('sale_date', 'desc')->orderBy('id', 'desc')->get();
        return view('inventory.sales', compact('orders'));
    }

    public function orderDetails($orderId){
        $order = Order::findOrFail($orderId);

        $orderItems = $order->order_snap;

        return view('inventory.order-detail', compact('order', 'orderItems'));
    }

    

    public function stockIn(Request $request){
            $validated = $request->validate([
                'product_id' => 'required|exists:products,id',
                'quantity' => 'required|numeric|min:1',
                'total_price' => 'required|numeric|min:1', 
            ]);

            $unitPrice = $request->total_price / $request->quantity;

            StockIn::create([
                'product_id' => $request->product_id,
                'quantity' => $request->quantity,
                'total_price' => $request->total_price,
                'unit_price' => $unitPrice,
                'created_by' => auth()->user()->id, 
            ]);

            return redirect('stock-in-view')->with('success', 'Stock In successfully!');
        }


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

            $stockOutDate = \Carbon\Carbon::createFromFormat('d/m/Y', $request->sale_date)->format('Y-m-d');

            StockOut::create([
                'product_id'      => $request->product_id,
                'quantity'        => $request->quantity,
                'stock_out_date'  => $stockOutDate,
                'created_by' => auth()->user()->id, 
            ]);

            return redirect('stock-out-view')->with('success', 'Stock Out successfully!');
        }

    public function updateStockIn(Request $request, $id){
        $validated = $request->validate([
            'quantity' => 'required|numeric|min:1',
            'total_price' => 'required|numeric|min:1',
        ]);

        $inventory = StockIn::findOrFail($id);
        $inventory->quantity = $request->quantity;
        $inventory->total_price = $request->total_price;
        $inventory->unit_price = $request->total_price / $request->quantity;
        $inventory->save();

        return redirect('stock-in-view')->with('success', 'Stock In updated successfully!');
    }

    public function deleteStockIn($id){
        $inventory = StockIn::findOrFail($id);
        $inventory->delete();

        return redirect('stock-in-view')->with('success', 'Stock In deleted successfully!');
    }

    public function updateStockOut(Request $request, $id){
    $validated = $request->validate([
        'quantity'   => 'required|numeric|min:1',
        'sale_date'  => 'required',
    ]);

    $stockOutDate = \Carbon\Carbon::createFromFormat('d/m/Y', $request->sale_date)->format('Y-m-d');

    $stockOut = StockOut::findOrFail($id);
    $stockOut->quantity = $request->quantity;
    $stockOut->stock_out_date = $stockOutDate;
    $stockOut->save();

    return redirect('stock-out-view')->with('success', 'Stock Out updated successfully!');
}

public function deleteStockOut($id){
    $stockOut = StockOut::findOrFail($id);
    $stockOut->delete();

    return redirect('stock-out-view')->with('success', 'Stock Out deleted successfully!');
}




}
