<?php

namespace App\Http\Controllers\Admin\Warehouse;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Brand;
use App\Models\Color;
use App\Models\ModelTable;
use App\Models\origin;
use App\Models\Product;
use App\Models\ProductType;
use App\Models\Size;
use App\Models\Supplier;
use App\Models\SupplierOpeningStock;
use App\Models\Units;
use App\Models\Warehouse;
use App\Models\WarehouseStock;
use App\Service\Warehouse\WarehouseService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Inertia\Inertia;

class WarehouseStoreContorller extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {

        return Inertia::render('Warehouse/WarehouseStore');
    }

    // public function view()
    // {
    //     $warehouse =  WarehouseStock::orderByDesc('id')
    //         ->with(['product', 'warehouse', 'getAttr', 'openingStock'])
    //         ->groupBy('product_id', 'warehouse_id')
    //         ->select('product_id', 'warehouse_id', DB::raw('SUM(unit_price_total) as unit_price_total'), DB::raw('SUM(quantity) as quantity'))
    //         ->get();
    //     return response()->json(['warehouse' => $warehouse, 'warehouseList' => Warehouse::get(),  'categoryList' =>  Category::pluck('name'), 'supplier' => Supplier::where('status', 1)->with('openingStockQty')->get()]);
    // }

    public function view(Request $request)
    {
        // Base query: one row per stock record (no grouping)
        $query = WarehouseStock::with([
            'warehouse',
            'attribute.product.category',
            'openingStock',
        ]);

        // Product-based search (by product name or SKU / barcode on attributes)
        if ($request->filled('search')) {
            $search = trim($request->get('search'));
            $lower = strtolower($search);

            $query->where(function ($q) use ($lower) {
                $q->whereHas('attribute.product', function ($q2) use ($lower) {
                    $q2->whereRaw('LOWER(products.name) LIKE ?', ["%{$lower}%"]);
                })->orWhereHas('attribute', function ($q3) use ($lower) {
                    $q3->whereRaw('LOWER(product_attributes.sku) LIKE ?', ["%{$lower}%"])
                        ->orWhereRaw('LOWER(product_attributes.barcode) LIKE ?', ["%{$lower}%"]);
                });
            });
        }

        if ($request->filled('brand_id')) {
            $query->whereHas('attribute', function ($q) use ($request) {
                $q->where('brand_id', $request->get('brand_id'));
            });
        }

        if ($request->filled('model_id')) {
            $query->whereHas('attribute', function ($q) use ($request) {
                $q->where('model_id', $request->get('model_id'));
            });
        }

        if ($request->filled('unit_id')) {
            $query->whereHas('attribute', function ($q) use ($request) {
                $q->where('unit_id', $request->get('unit_id'));
            });
        }

        if ($request->filled('color_id')) {
            $query->whereHas('attribute', function ($q) use ($request) {
                $q->where('color_id', $request->get('color_id'));
            });
        }

        if ($request->filled('size_id')) {
            $query->whereHas('attribute', function ($q) use ($request) {
                $q->where('size_id', $request->get('size_id'));
            });
        }

        if ($request->filled('product_type_id')) {
            $query->whereHas('attribute', function ($q) use ($request) {
                $q->where('product_type_id', $request->get('product_type_id'));
            });
        }

        if ($request->filled('origin_id')) {
            $query->whereHas('attribute.product', function ($q) use ($request) {
                $q->where('origin_id', $request->get('origin_id'));
            });
        }

        $isPaginationRequest = $request->filled('page') || $request->filled('perPage') || $request->filled('search');

        // Always calculate grand totals based on the full (filtered) dataset
        $totalQtyAll = (clone $query)->sum('quantity');
        $totalValueAll = (clone $query)->sum('unit_price_total');
        $totalMrpValueAll = (clone $query)->sum(DB::raw('COALESCE(mrp_price_total, 0)'));
        $totalTpValueAll = (clone $query)->sum(DB::raw('COALESCE(tp_price_total, 0)'));

        $brands = Brand::orderBy('name', 'ASC')->get();
        $colors = Color::orderBy('name', 'ASC')->get();
        $models = ModelTable::orderBy('name', 'ASC')->get();
        $sizes = Size::orderBy('name', 'ASC')->get();
        $units = Units::orderBy('name', 'ASC')->get();
        $origins = origin::orderBy('name', 'ASC')->get();
        $productTypes = ProductType::orderBy('name', 'ASC')->get();

        if ($isPaginationRequest) {
            $page = (int) $request->get('page', 1);
            $perPage = (int) $request->get('perPage', 10);
            $stocks = $query->orderByDesc('id')->paginate($perPage, ['*'], 'page', $page);

            return response()->json([
                'data' => $stocks->items(),
                'total' => $stocks->total(),
                'total_qty_all' => $totalQtyAll,
                'total_value_all' => $totalValueAll,
                'total_mrp_value_all' => $totalMrpValueAll,
                'total_tp_value_all' => $totalTpValueAll,
                'warehouseList' => Warehouse::get(),
                'categoryList' => Category::pluck('name'),
                'supplier' => Supplier::where('status', 1)->with('openingStockQty')->get(),
                'brands' => $brands,
                'colors' => $colors,
                'models' => $models,
                'sizes' => $sizes,
                'units' => $units,
                'origins' => $origins,
                'productTypes' => $productTypes,
            ]);
        }

        $warehouse = $query->orderByDesc('id')->get();

        return response()->json([
            'warehouse' => $warehouse,
            'total_qty_all' => $totalQtyAll,
            'total_value_all' => $totalValueAll,
            'total_mrp_value_all' => $totalMrpValueAll,
            'total_tp_value_all' => $totalTpValueAll,
            'warehouseList' => Warehouse::get(),
            'categoryList' => Category::pluck('name'),
            'supplier' => Supplier::where('status', 1)->with('openingStockQty')->get(),
            'brands' => $brands,
            'colors' => $colors,
            'models' => $models,
            'sizes' => $sizes,
            'units' => $units,
            'origins' => $origins,
            'productTypes' => $productTypes,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        WarehouseService::DataStore(request()->all());
        WarehouseService::CompanyOpeningStockStore(request()->all());


        // 1. Fetch all records with necessary relations in one query
        $allStocks = SupplierOpeningStock::with(['attribute', 'warehouse'])
            ->selectRaw('*, DATE(opening_stock_date) as grouped_date')
            ->orderBy('warehouse_id')
            ->orderBy('opening_stock_date')
            ->get();

        // 2. Group by date and warehouse_id
        $groupedData = $allStocks->groupBy(function ($item) {
            return $item->grouped_date . '_' . $item->warehouse_id;
        });

        // 3. Transform into your desired structure
        $warehouse = $groupedData->map(function ($groupItems, $key) {
            $first = $groupItems->first();

            return (object) [
                'date' => $first->grouped_date,
                'warehouse_id' => $first->warehouse_id,
                'warehouse' => $first->warehouse,
                'details' => $groupItems,
            ];
        })->values();

        // Step 4: Fetch other required data
        $warehouseList = Warehouse::get(); // Fetch all warehouses
        $categoryList = Category::pluck('name'); // Fetch category names
        $supplier = Supplier::where('status', 1)->with('openingStockQty')->get(); // Fetch active suppliers with opening stock quantity

        // Step 5: Return response with all data
        return response()->json([
            'success' => 'Data insert Successfully',
            'warehouse' => $warehouse,
            'warehouseList' => $warehouseList,
            'categoryList' => $categoryList,
            'supplier' => $supplier,
        ], 200);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Request $request, $id) {}

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {

        try {
            // Step 1: Update the data store
            WarehouseService::UpdateDataStore(request()->all(), $id);

            // Step 2: Run the company opening stock program
            WarehouseService::CompanyOpeningStock(request()->all(), $id);

            // 1. Fetch all records with necessary relations in one query
            $allStocks = SupplierOpeningStock::with(['attribute', 'warehouse'])
                ->selectRaw('*, DATE(opening_stock_date) as grouped_date')
                ->orderBy('warehouse_id')
                ->orderBy('opening_stock_date')
                ->get();

            // 2. Group by date and warehouse_id
            $groupedData = $allStocks->groupBy(function ($item) {
                return $item->grouped_date . '_' . $item->warehouse_id;
            });

            // 3. Transform into your desired structure
            $warehouse = $groupedData->map(function ($groupItems, $key) {
                $first = $groupItems->first();

                return (object) [
                    'date' => $first->grouped_date,
                    'warehouse_id' => $first->warehouse_id,
                    'warehouse' => $first->warehouse,
                    'details' => $groupItems,
                ];
            })->values();


            // Step 4: Fetch other required data
            $warehouseList = Warehouse::get(); // Fetch all warehouses
            $categoryList = Category::pluck('name'); // Fetch category names
            $supplier = Supplier::where('status', 1)->with('openingStockQty')->get(); // Fetch active suppliers with opening stock quantity

            // Step 5: Return response with all data
            return response()->json([
                'success' => 'Data Update Successfully',
                'warehouse' => $warehouse,
                'warehouseList' => $warehouseList,
                'categoryList' => $categoryList,
                'supplier' => $supplier,
            ], 200);
        } catch (\Exception $e) {
            // Handle exceptions, log error, and return an error response
            Log::error('Error in updating warehouse or fetching data: ' . $e->getMessage());

            return response()->json(['message' => 'An error occurred while processing your request.'], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
   
        WarehouseService::CompanyOpeningStockDelete($id);

        // 1. Fetch all records with necessary relations in one query
        $allStocks = SupplierOpeningStock::with(['attribute', 'warehouse'])
            ->selectRaw('*, DATE(opening_stock_date) as grouped_date')
            ->orderBy('warehouse_id')
            ->orderBy('opening_stock_date')
            ->get();

        // 2. Group by date and warehouse_id
        $groupedData = $allStocks->groupBy(function ($item) {
            return $item->grouped_date . '_' . $item->warehouse_id;
        });

        // 3. Transform into your desired structure
        $warehouse = $groupedData->map(function ($groupItems, $key) {
            $first = $groupItems->first();

            return (object) [
                'date' => $first->grouped_date,
                'warehouse_id' => $first->warehouse_id,
                'warehouse' => $first->warehouse,
                'details' => $groupItems,
            ];
        })->values();



        // Step 4: Fetch other required data
        $warehouseList = Warehouse::get(); // Fetch all warehouses
        $categoryList = Category::pluck('name'); // Fetch category names
        $supplier = Supplier::where('status', 1)->with('openingStockQty')->get(); // Fetch active suppliers with opening stock quantity

        // Step 5: Return response with all data
        return response()->json([
            'success' => 'Data Delete Successfully',
            'warehouse' => $warehouse,
            'warehouseList' => $warehouseList,
            'categoryList' => $categoryList,
            'supplier' => $supplier,
        ], 200);
    }

    public function wareHouseOpening()
    {



        return Inertia::render('Warehouse/WarehousesOpening');
    }

    public function wareHouseOpeningView()
    {


        // 1. Fetch all records with necessary relations in one query
        $allStocks = SupplierOpeningStock::with(['attribute', 'warehouse'])
            ->selectRaw('*, DATE(opening_stock_date) as grouped_date')
            ->orderBy('warehouse_id')
            ->orderBy('opening_stock_date')
            ->get();

        // 2. Group by date and warehouse_id
        $groupedData = $allStocks->groupBy(function ($item) {
            return $item->grouped_date . '_' . $item->warehouse_id;
        });

        // 3. Transform into your desired structure
        $data = $groupedData->map(function ($groupItems, $key) {
            $first = $groupItems->first();

            return (object) [
                'date' => $first->grouped_date,
                'warehouse_id' => $first->warehouse_id,
                'warehouse' => $first->warehouse,
                'details' => $groupItems,
            ];
        })->values();

        return response()->json(['warehouse' => $data, 'warehouseList' => Warehouse::get(),  'categoryList' => Category::pluck('name'), 'supplier' => Supplier::where('status', 1)->with('openingStockQty')->get()]);
    }

    public function attr_delete($id, $warehouse_id)
    {
        $supplier = SupplierOpeningStock::withoutGlobalScope('typeScope')->where('attribute_id', $id)
            ->where('warehouse_id', $warehouse_id)
            ->first();



        $warehouseStock = WarehouseStock::where('attribute_id', $id)
            ->where('warehouse_id', $warehouse_id)
            ->first();

        if (!$supplier) {
            return response()->json(['error' => 'Supplier record not found.'], 404);
        }

        // Optional: wrap in transaction
        DB::beginTransaction();
        try {
            if ($warehouseStock) {
                $warehouseStock->update([
                    'quantity' => $warehouseStock->quantity - $supplier->quantity
                ]);
            }

            $supplier->delete();

            DB::commit();
            return response()->json(['success' => 'Deleted successfully!']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['error' => 'Delete failed.'], 500);
        }
    }
}
