<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
namespace App\Http\Controllers\API;
use App\Http\Resources\CatgryByProductResources;
use App\Http\Resources\SubCatByPrdctResources;
use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Models\OrderDetails;
use App\Models\ProductVarient;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Product;
use App\Models\Cart;
use App\Models\User;
use App\Models\Order;
use Illuminate\Support\Facades\Log;

class ProductController extends Controller
{

    public function order_place(Request $request)
{
    if (!auth()->guard('sanctum')->check()) {
        return response()->json([
            'status'  => 'error',
            'message' => 'Please login!',
            'data'    => [],
            'code'    => 401,
        ]);
    }

    $user = auth()->guard('sanctum')->user();
    $validator = Validator::make($request->all(), [
        'cart_items'              => 'required|array',
        'cart_items.*.product_id' => 'required|exists:products,id',
        'cart_items.*.quantity'   => 'required|integer|min:1',
        'cart_items.*.variant_id' => 'required|exists:product_varients,id',
        'delivery_address'        => 'nullable|string',
        'instruction'             => 'nullable|string',
    ]);

    if ($validator->fails()) {
        return response()->json([
            'status'  => 'error',
            'message' => 'Validation failed.',
            'errors'  => $validator->errors(),
            'code'    => 422,
        ], 422);
    }

    try {
       
        $order = Order::create([
            'user_id' => $user->id,
            'status' => 'pending',
        ]);

        $orderRandomId = strtoupper(Str::random(2) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT));

        $subtotal        = 0;
        $address         = Address::getCurrentAddress($user->id);
        $deliveryAddress = $request->delivery_address ?? ($address ? implode(', ', array_filter([
            $address->house_no, $address->road_name, $address->landmark,
            $address->district, $address->state, $address->pin,
        ])) : null);

        if (!$deliveryAddress) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Delivery address is required.',
                'code'    => 422,
            ], 422);
        }

        $cartItems = [];
        $orderDetails = [];

        foreach ($request->cart_items as $item) {
            $product = Product::with(['category', 'subcategory'])->find($item['product_id']);
            if (!$product) {
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Product not found.',
                    'code'    => 404,
                ], 404);
            }

            $productVariant = ProductVarient::where('id', $item['variant_id'])
                ->where('product_id', $item['product_id'])
                ->first();

            if (!$productVariant) {
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Product variant not found.',
                    'code'    => 404,
                ], 404);
            }

            $originalPrice = $productVariant->price;
            $itemSubtotal = $originalPrice * $item['quantity'];
            $subtotal += $itemSubtotal;

            $orderDetails[] = [
                'product_details_id'   => $product->id,
                'product_details_name' => $product->title,
                'quantity'             => $item['quantity'],
                'amount'               => $itemSubtotal,
            ];

            $cartItems[] = [
                'product_details_id'   => $product->id,
                'product_details_name' => $product->title,
                'category_name'        => $product->category->category_name ?? 'Not Available',
                'subcategory_name'     => $product->subcategory->subcategory_name ?? 'Not Available',
                'variant_id'           => $item['variant_id'],
                'quantity'             => $item['quantity'],
                'price'                => number_format($originalPrice, 2),
                'subtotal'             => number_format($itemSubtotal, 2),
            ];
        }

        OrderDetails::create([
            'order_date'           => now(),
            'user_id'              => $user->id,
            'user_name'            => $user->name,
            'category_id'          => $product->category->id ?? null,
            'category_name'        => $product->category->category_name ?? 'Not Available',
            'subcategory_name'     => $product->subcategory->subcategory_name ?? 'Not Available',
            'order_random_id'      => $orderRandomId,
            'product_details_id'   => implode('~', array_column($orderDetails, 'product_details_id')),
            'product_details_name' => implode('~', array_column($orderDetails, 'product_details_name')),
            'quantity'             => implode('~', array_column($orderDetails, 'quantity')),
            'amount'               => $subtotal,
            'delivery_address'     => $deliveryAddress,
            'instruction'          => $request->instruction ?? null,
        ]);

        Cart::where('user_id', $user->id)->delete();

        return response()->json([
            'status'   => 'success',
            'message'  => 'Order placed successfully',
            'order_id' => $order->id,
            'Bill_Id'  => $orderRandomId,
            'data'     => [
                'cart_items'       => $cartItems,
                'subtotal'         => number_format($subtotal, 2),
                'delivery_address' => $deliveryAddress,
            ],
        ], 200);

    } catch (\Exception $e) {
        Log::error('Error processing order placement: ' . $e->getMessage());
        return response()->json([
            'status'  => 'error',
            'message' => 'Failed to place order.',
            'code'    => 500,
        ], 500);
    }
}
    public function getProductsBySubcategory($subcategoryId)
    {
        try {
            if (!auth()->guard('sanctum')->check()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Please login!',
                    'data' => [],
                    'code' => 401,
                ]);
            }
    
            $user = auth()->guard('sanctum')->user();
    
            $products = Product::where('subcategory_id', $subcategoryId)
                ->with([
                    'variants',
                    'wishlist' => function ($query) use ($user) {
                        $query->where('user_id', $user->id);
                    }
                ])
                ->get();
    
            if ($products->isEmpty()) {
                return response()->json([
                    'status' => 'success',
                    'data' => [],
                    'message' => 'No products found for this subcategory.',
                    'code' => 200,
                ], 200);
            }
    
            $productsWithWishlistStatus = $products->map(function ($product) {
                $product->is_wishlist = $product->wishlist->isNotEmpty();
                unset($product->wishlist);
                $validVariations = $product->variants->filter(function ($variant) {
                    return is_numeric($variant->mrp) && $variant->mrp > 0; 
                });
    
                if ($product->variants->isNotEmpty()) {
                    $product->variants->each(function ($variant) {
                        if ($variant->discount) {
                            $discountedPrice = $variant->mrp - ($variant->mrp * ($variant->discount / 100));
                            $variant->discounted_price = number_format($discountedPrice, 2);
                        } else {
                            $variant->discounted_price = null;
                        }
                    });
                 
                    $product->variations = $validVariations;
                    return new SubCatByPrdctResources($product); 
                }
                return null;
    
            })->filter(); 
    
            return response()->json([
                'status' => 'success',
                'data' => $productsWithWishlistStatus,
                'message' => 'Products and their variants fetched successfully.',
                'code' => 200,
            ], 200);
    
        } catch (\Exception $e) {
            Log::error('Error fetching products and variants: ' . $e->getMessage());
    
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch products and variants.',
                'code' => 500,
            ], 500);
        }
    }
    

    // public function getProductsBySubcategory($subcategoryId)
    // {
    //     try {
    //         if (!auth()->guard('sanctum')->check()) {
    //             return response()->json([
    //                 'status'  => 'error',
    //                 'message' => 'Please login!',
    //                 'data'    => [],
    //                 'code'    => 401,
    //             ]);
    //         }
    //         $user     = auth()->guard('sanctum')->user();
    //         $products = Product::where('subcategory_id', $subcategoryId)
    //             ->with([
    //                 'variants',
    //                 'wishlist' => function ($query) use ($user) {
    //                     $query->where('user_id', $user->id);
    //                 }
    //             ])
    //             ->get();
    //         if ($products->isEmpty()) {
    //             return response()->json([
    //                 'status'  => 'success',
    //                 'data'    => [],
    //                 'message' => 'No products found for this subcategory.',
    //                 'code'    => 200,
    //             ], 200);
    //         }
    //         $productsWithWishlistStatus = $products->map(function ($product) {
    //             $product->is_wishlist = $product->wishlist && $product->wishlist->isNotEmpty();
    //             unset($product->wishlist);
    //             $validVariations = $product->variants->filter(function ($variant) {
    //                 return is_numeric($variant->mrp) && $variant->mrp > 0;
    //             });
    //             $product->variants = $validVariations->map(function ($variant) {
    //                 if ($variant->discount) {
    //                     $discountedPrice = $variant->mrp - ($variant->mrp * ($variant->discount / 100));
    //                     $variant->discounted_price = number_format($discountedPrice, 2);
    //                 } else {
    //                     $variant->discounted_price = null;
    //                 }
    //                 return $variant;
    //             });
    //             return $product;
    //         });
    //         return response()->json([
    //             'status' => 'success',
    //             'data' => $productsWithWishlistStatus,
    //             'message' => 'Products and their variants fetched successfully.',
    //             'code' => 200,
    //         ], 200);
    //     } catch (\Exception $e) {
    //         Log::error('Error fetching products and variants: ' . $e->getMessage());
    //         return response()->json([
    //             'status' => 'error',
    //             'message' => 'Failed to fetch products and variants.',
    //             'code' => 500,
    //         ], 500);
    //     }
    // }
    

    public function getProductByCategory($categoryId)
{
    try {
        if (!auth()->guard('sanctum')->check()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Please lo`gin!',
                'data' => [],
                'code' => 401,
            ]);
        }

        $user = auth()->guard('sanctum')->user();

        $products = Product::where('category_id', $categoryId)
            ->with([
                'variants',
                'category',
                'subcategory',
                'wishlist' => function ($query) use ($user) {
                    $query->where('user_id', $user->id);
                }
            ])
            ->get();

        if ($products->isEmpty()) {
            return response()->json([
                'status' => 'success',
                'data' => [],
                'message' => 'No products found for this category.',
                'code' => 200,
            ], 200);
        }

        $productsWithWishlistStatus = $products->map(function ($product) use ($user) {
            $product->is_wishlist = $product->wishlist->isNotEmpty();
            unset($product->wishlist);

            $validVariations = $product->variants->filter(function ($variant) {
                return is_numeric($variant->mrp) && $variant->mrp > 0;
            });

            if ($product->variants->isNotEmpty()) {
                $product->variants->each(function ($variant) {
                    if ($variant->discount) {
                        $discountedPrice = $variant->mrp - ($variant->mrp * ($variant->discount / 100));
                        $variant->discounted_price = number_format($discountedPrice, 2);
                    } else {
                        $variant->discounted_price = null;
                    }
                });

                $product->variations = $validVariations;
                return new CatgryByProductResources($product);
            }
            return null;
        })->filter();

        return response()->json([
            'status'  => 'success',
            'data'    => $productsWithWishlistStatus,
            'message' => 'Products and their variants fetched successfully.',
            'code'    => 200,
        ], 200);

    } catch (\Exception $e) {
        Log::error('Error fetching products and variants: ' . $e->getMessage());

        return response()->json([
            'status'  => 'error',
            'message' => 'Failed to fetch products and variants.',
            'code'    => 500,
        ], 500);
    }
}
    public function orderdetails($order_random_id)
    {
        try {
            $user = auth()->guard('sanctum')->user();

            if (!$user) {
                Log::warning('User not authenticated.');
                return response()->json([
                    'status'  => 'error',
                    'message' => 'User not authenticated.',
                    'code'    => 401,
                ], 401);
            }


            $orderDetails = OrderDetails::where('order_random_id', $order_random_id)
                ->where('user_id', $user->id)
                ->first();

            if (!$orderDetails) {
                return response()->json([
                    'status'  => 'success',
                    'data'    => [],
                    'message' => 'No order details found for this order ID for the current user.',
                    'code'    => 200,
                ], 200);
            }

            $subtotal = 0;
            $deliveryFee = 50;


            $productIds   = explode('~', $orderDetails->product_details_id);
            $productNames = explode('~', $orderDetails->product_details_name);
            $quantities   = explode('~', $orderDetails->quantity);

            $orderItem = [
                'Bill Id'          => $orderDetails->order_random_id,
                'user_id'          => $user->id,
                'user_name'        => $user->name,
                'delivery_address' => $orderDetails->delivery_address,
                'instruction'      => $orderDetails->instruction,
                'status'           => $orderDetails->status,
                'order_date'       => $orderDetails->created_at,
                'products'         => [],
            ];


            foreach ($productIds as $index => $productId) {
                $quantity    = isset($quantities[$index]) ? intval($quantities[$index]) : 1;
                $productName = $productNames[$index] ?? 'Unknown Product';
                $amount      = floatval($orderDetails->amount) / count($productIds);

                $subtotal += $amount ;

                $orderItem['products'][] = [
                    'product_details_id'   => $productId,
                    'product_details_name' => $productName,
                    'quantity'             => $quantity,
                    'amount'               => $amount,
                ];
            }

            $totalAmount = $subtotal + $deliveryFee;

            return response()->json([
                'status' => 'success',
                'data' => [
                    'order_items'  => [$orderItem],
                    'subtotal'     => $subtotal,
                    'delivery_fee' => $deliveryFee,
                    'total_amount' => $totalAmount,
                ],
                'message' => 'Order details fetched successfully.',
                'code'    => 200,
            ], 200);
        } catch (\Exception $e) {
            Log::error('Failed to fetch order details: ' . $e->getMessage());
            Log::error('Error details:', [
                'order_random_id' => $order_random_id,
                'user_id'         => $user->id,
            ]);

            return response()->json([
                'status'  => 'error',
                'message' => 'Failed to fetch order details.',
                'code'    => 500,
            ], 500);
        }
    }




}