<?php

namespace App\Http\Controllers\API;
use App\Http\Resources\BannerResource;
use App\Http\Resources\NotificationResource;
use App\Models\Wishlist;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\CategoryResource;
use App\Http\Resources\DeliveryFeeResource;
use App\Http\Resources\UserDetailsResource;
use App\Http\Resources\ProductResource;
use App\Models\BannerImage;
use App\Models\Category;
use App\Models\DeliveryFeeMaster;
use App\Models\User;
use App\Models\Notification;
use App\Models\Product;


class UserController extends Controller
{
    public function banner()
    {
        try {
            $banners = BannerImage::all();

            return response()->json([
                'status' => 'success',
                'data' => BannerResource::collection($banners),
                'message' => 'Banners fetched successfully.',
                'code' => 200,
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch banners.',
                'code' => 500,
            ], 500);
        }
    }
    public function notification()
    {
        try {
            $notifications = Notification::all();
            return response()->json([
                'status' => 'success',
                'data' => NotificationResource::collection($notifications),
                'message' => 'Notifications fetched successfully.',
                'code' => 200,
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch notifications.',
                'code' => 500,
            ], 500);
        }
    }
    public function delivery_fee()
    {
        try {
            $deliveryFees = DeliveryFeeMaster::all();
            return response()->json([
                'status' => 'success',
                'data' => DeliveryFeeResource::collection($deliveryFees),
                'message' => 'Delivery fees fetched successfully.',
                'code' => 200,
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch delivery fees.',
                'code' => 500,
            ], 500);
        }
    }
    public function category()
    {
        try {

            $categories = Category::where('category_type', 1)->distinct()->get();

            return response()->json([
                'status' => 'success',
                'data' => CategoryResource::collection($categories),
                'message' => 'Categories fetched successfully.',
                'code' => 200,
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch categories.',
                'code' => 500,
            ], 500);
        }
    }
    public function category_id($id)
    {
        $validator = Validator::make(['id' => $id], [
            'id' => 'required|integer|exists:categories,id',
        ]);
        
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'data' => null,
                'message' => 'Validation failed',
                'code' => 422,
                'errors' => $validator->errors()
            ], 422);
        }
        
        $category = Category::with('subcategories')->find($id);
        if (!$category) {
            return response()->json([
                'status' => 'error',
                'data' => null,
                'message' => 'Category not found',
                'code' => 404
            ], 404);
        }
    
      
        return response()->json([
            'status' => 'success',
            'data' => $category->subcategories->map(function($subcategory) {
                return [
                    'id' => $subcategory->id,
                    'subcategory_name' => $subcategory->subcategory_name,
                    'subcategory_img' => url($subcategory->category_img), // Subcategory image URL
                ];
            }),
            'message' => 'Subcategories retrieved successfully',
            'code' => 200
        ], 200);
    }
    
     public function user_details()
    {
        try {
            if (!auth('sanctum')->check()) {
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Please login!',
                    'data'    => [],
                    'code'    => 401,
                ], 401);
            }


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

            return response()->json([
                'status'  => 'success',
                'data'    => new UserDetailsResource($user),
                'message' => 'User details retrieved successfully',
                'code'    => 200
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to retrieve user details',
                'code' => 500,
                'error' => $e->getMessage()
            ], 500);
        }
    }
    public function products()
    {
        try {
            if (!auth()->guard('sanctum')->check()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Please login!',
                    'data' => [],
                    'code' => 401,
                ]);
            }
    
            $user = auth()->guard('sanctum')->user();
    
            $products = Product::with([
                'wishlist' => function ($query) use ($user) {
                    $query->where('user_id', $user->id);
                },
                'variants'
            ])->get();
    
            Log::info('Fetched Products', ['products' => $products]);
    
            $productsWithWishlistStatus = $products->map(function ($product) use ($user) {
                Log::info('Processing Product', ['product' => $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 ProductResource($product); 
                }
                return null;
    
            })->filter(); 
    
            return response()->json([
                'status'  => 'success',
                'data'    => $productsWithWishlistStatus,
                'message' => 'Products fetched successfully.',
                'code'    => 200,
            ], 200);
    
        } catch (\Exception $e) {
            Log::error('Error fetching products', ['exception' => $e]);
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch products.',
                'code' => 500,
            ], 500);
        }
    }
    

    public function products_id($id)
{
    try {
       
        $validator = Validator::make(['id' => $id], [
            'id' => 'required|integer|exists:products,id',
        ]);
        
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'data' => null,
                'message' => 'Validation failed',
                'code' => 422,
                'errors' => $validator->errors()
            ], 422);
        }

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

        
        $product = Product::with([
            'wishlist' => function ($query) use ($user) {
                $query->where('user_id', $user->id);
            },
            'variants'
        ])->find($id);

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

        
        $product->is_wishlist = $product->wishlist->isNotEmpty();
        unset($product->wishlist); 

        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; 
                }
            });
        }


        return response()->json([
            'status' => 'success',
            'data' => new ProductResource($product),
            'message' => 'Product retrieved successfully',
            'code' => 200
        ], 200);
        
    } catch (\Exception $e) {
        Log::error('Error retrieving product', ['exception' => $e]);
        return response()->json([
            'status' => 'error',
            'message' => 'Failed to retrieve product.',
            'code' => 500,
        ], 500);
    }
}

}
