<?php

namespace App\Http\Controllers\AdminControllers;

use Illuminate\Http\Request;
use App\Models\AdminModels\Product;
use App\Models\AdminModels\Category;
use App\Models\AdminModels\Brand;
use App\Models\AdminModels\SubCategory;
use App\Models\AdminModels\ChildCategory;
use App\Models\AdminModels\ProductVariantType;
use App\Models\AdminModels\ProductVariantValue;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use App\Http\Requests\ProductRequest;
use Illuminate\Support\Facades\File;

class ProductController
{


    public function productVariantAdd($id){

       $product = Product::select('id','stock','discount','mrp','selling_price','color','size','sub_sku')->where('id', $id)->first();
       
       $product_variant = Product::select('id','stock','discount','mrp','selling_price','color','size')->where('sub_sku', $product->sub_sku)->paginate(5);

       return view('admin.products.product-variant-add', ['product' => $product, 'product_variant' => $product_variant]);   
    }

    public function productVariantSave(Request $request)
    {
        $product = Product::find($request->id);
      
        $validator = Validator::make($request->all(), [
            'addons.*.size' => 'required|string',
            'addons.*.color' => 'required|string',
    
            'addons.*.featured_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ], [
            'addons.*.size.required' => 'The size field is required.',
            'addons.*.size.unique' => 'The size has already been taken.',
            'addons.*.color.required' => 'The color field is required.',
            'addons.*.color.unique' => 'The color has already been taken.',
            'addons.*.featured_image.required' => 'The featured image field is required.',
            'addons.*.featured_image.image' => 'The featured image must be an image.',
            'addons.*.featured_image.mimes' => 'The featured image must be a jpeg, png, jpg, gif, or svg file.',
            'addons.*.featured_image.max' => 'The featured image must not be greater than 2MB.',
        ]);
    
        // Step 2: Custom validation for duplicate size-color combinations
        $combinations = [];
        foreach ($request->addons as $index => $addon) {
    
            $size = strtolower(trim($addon['size']));
            $color = strtolower(trim($addon['color']));
            $combo = $size . '|' . $color;
    
            if (in_array($combo, $combinations)) {
                $validator->after(function ($validator) use ($index) {
                    $validator->errors()->add("addons.$index.size", "Duplicate size-color combination found.");
                    $validator->errors()->add("addons.$index.color", "Duplicate size-color combination found.");
                });
            }
    
    
             // Check duplicate in database for this sub_sku
            $exists = Product::where('sub_sku', $product->sub_sku)
                ->where('size', $addon['size'])
                ->where('color', $addon['color'])
                ->exists();
    
            if ($exists) {
                $validator->after(function ($validator) use ($index) {
                    $validator->errors()->add("addons.$index.size", "This size-color combination already exists in the database.");
                    $validator->errors()->add("addons.$index.color", "This size-color combination already exists in the database.");
                });
            }
    
            $combinations[] = $combo;
        }
    
        // Check if validation fails
       
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }
    
        // Step 3: Save variants
        
        foreach ($request->addons as $addon) {
            if (isset($addon['featured_image'])) {
                $featured_image = $addon['featured_image'];
                $featuredimageName = time() . '_' . $featured_image->getClientOriginalName();
                $featured_image->move(public_path('uploads/products'), $featuredimageName);
            }
    
            $collection = collect([

                'sku' => $product->sku ?? '',
                'hsn_code' => $product->hsn_code ?? '',
                'stock' => $product->stock ?? '',
                'category_id' => $product->category_id ?? NULL,
                'sub_category_id' => $product->sub_category_id ?? NULL,
                'child_category_id' => $product->child_category_id ?? NULL,
                'brand_id' => $product->brand_id ?? NULL,
                'product_highlights' => $product->product_highlights  ?? '',
                'product_description' => $product->product_description  ?? '',

                'length' => $product->length  ?? NULL,
                'breadth' => $product->breadth  ?? NULL,
                'height' => $product->height  ?? NULL,
                'weight' => $product->weight  ?? NULL,

                'country_of_origin' => $product->country_of_origin  ?? '',
                'manufacturer_details' => $product->manufacturer_details  ?? '',
                'importer_details' => $product->importer_details  ?? '',
                'packer_details' => $product->packer_details  ?? '',

                'meta_title' => $product->meta_title  ?? '',
                'meta_description' => $product->meta_description  ?? '',

                'meta_keywords' => $product->meta_keywords  ?? '',
                'tags' => $product->tags  ?? '',
                'note' => $product->note  ?? '',
                'status' => $product->status  ?? '',

                'name' => $product->name ?? '',
                'slug' => $product->slug ?? '',
                'sub_sku' => $product->sub_sku ?? '',
                'product_id' => rand(100000, 999999),
                'size' => $addon['size'],
                'color' => $addon['color'],
                'mrp' => $addon['mrp'],
                'selling_price' => $addon['selling_price'],
                'discount' => $addon['discount'],
                'stock' => $addon['stock'],
                'featured_image' => $featuredimageName ?? '',
                'bulk_images' => $product->bulk_images ?? '',
            ]);
            Product::create($collection->toArray());
        }
    
        return redirect()->back()->with('success', 'Product variants added successfully!');
    }

    public function getSubcategories($category_id)
    {
        $subcategories = SubCategory::where('category_id', $category_id)->pluck('name', 'id');
        return response()->json($subcategories);
    }

    public function getChildcategories($subcategory_id)
    {
        $childcategories = ChildCategory::where('sub_category_id', $subcategory_id)->pluck('name', 'id');
        return response()->json($childcategories);
    }

    public function productList(){
        $product = Product::select('*')->orderBy('id', 'DESC')->with(['brand','childCategory','subCategory','category'])->get();
        return view('admin.products.product-list', ['product'=>$product]);
    }
    
    public function productAdd(){
        $categories = Category::select('*')->get();
        $brands = Brand::select('*')->get();
        $variantTypes = ProductVariantType::select('*')->get();
        return view('admin.products.product-add', ['categories'=>$categories, 'brands' => $brands, 'variantTypes' => $variantTypes]);
    }

    public function variantValueStore(Request $request){

        $variantValue = new ProductVariantValue;
        $variantValue->product_variant_type_id = $request->product_variant_type_id;
        $variantValue->name = $request->name;
        
        if($variantValue->save()){
            return response()->json([
                'status' => 'true',
                'message' => 'success'
         ]);
        }
        else{
            return response()->json([
                'status' => 'false',
                'message' => 'fail'
         ]); 
        }
        
    }

    public function productSave(Request $request)
    {
        $validated = $request->validate([
            'category_id' => 'required|exists:categories,id',
            'sub_category_id' => 'nullable|exists:sub_categories,id',
            'child_category_id' => 'nullable|exists:child_categories,id',
            'brand_id' => 'required|integer',
            'name' => 'required|string|max:255',
            'mrp' => 'required|numeric|min:0',
            'selling_price' => 'nullable|numeric|min:0|lte:mrp',
            'discount' => 'nullable|numeric|min:0|max:100',
            'size' => 'required|string|max:100',
            'color' => 'required|string|max:100',
            'sku' => 'nullable|string|max:100|unique:products,sku',
            'hsn_code' => 'nullable|string|max:50',
            'stock' => 'nullable|numeric|max:50',
            'product_highlights' => 'nullable|string',
            'product_description' => 'nullable|string',
            'length' => 'nullable|numeric|min:0',
            'breadth' => 'nullable|numeric|min:0',
            'height' => 'nullable|numeric|min:0',
            'weight' => 'nullable|numeric|min:0',
            'country_of_origin' => 'required|string|max:100',
            'manufacturer_details' => 'nullable|string',
            'importer_details' => 'nullable|string',
            'packer_details' => 'nullable|string',
            'meta_title' => 'required|string|max:255',
            'meta_description' => 'nullable|string',
            'meta_keywords' => 'nullable|string',
            'tags' => 'nullable|string',
            'note' => 'nullable|string',
            'status' => 'required|in:active,inactive',
            'featured_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'bulk_images' => 'nullable|array',
            'bulk_images.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $product = new Product($request->all());

        $product->product_id = rand(100000, 999999);
        $product->sub_sku = rand(100000, 999999);
        $product->slug = Str::slug($request->name);
        $product->selling_price = round($request->selling_price, 2);
        $product->discount = round($request->discount, 2);
        $product->ip = $request->ip();

        // Handle featured image
        if ($request->hasFile('featured_image')) {
            $image = $request->file('featured_image');
            $imageName = time() . '_' . $image->getClientOriginalName();
            $image->move(public_path('uploads/products'), $imageName);
            $product->featured_image = $imageName;
        }

        // Handle bulk images
        if ($request->hasFile('bulk_images')) {
            $bulkImages = [];
            foreach ($request->file('bulk_images') as $file) {
                $fileName = time() . '_' . $file->getClientOriginalName();
                $file->move(public_path('uploads/products'), $fileName);
                $bulkImages[] = $fileName;
            }
            $product->bulk_images = json_encode($bulkImages);
        }

        if ($product->save()) {
            return redirect()->route('product.list')->with('success', 'Product added successfully!');
        }

        return redirect()->back()->with('error', 'Product not added successfully!');
    }

    public function productEdit($id){
        $categories = Category::select('*')->get();
        $brands = Brand::select('*')->get();
        $product = Product::where('id', $id)->first();

        $variantTypes = ProductVariantType::select('*')->get(); 
        $subcategories = SubCategory::where('category_id', $product->category_id)->get();
        $childcategories = ChildCategory::where('sub_category_id', $product->sub_category_id)->get();

        return view('admin.products.product-edit', ['product'=>$product, 'categories'=>$categories, 'brands' => $brands, 'subcategories'=>$subcategories, 'childcategories'=>$childcategories, 'variantTypes' => $variantTypes]);
    }

    public function productUpdate(Request $request, $id){

        $validated = $request->validate([

            'category_id' => 'required|exists:categories,id',
            'brand_id' => 'required|integer',
            'name' => 'required|string|max:255',
            'mrp' => 'required|numeric|min:0',

            'size' => 'required|string|max:100',
            'color' => 'required|string|max:100',

            'country_of_origin' => 'required|string|max:100',
            'meta_title' => 'required|string|max:255',

            'status' => 'required|in:active,inactive',
            'featured_image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $products = Product::findOrFail($id);
        $products->fill($request->all());
        
        $products->slug = Str::slug($request->name);
        $products->selling_price = round($request->selling_price, 2);
        $products->discount = round($request->discount, 2);
        $products->ip = $request->ip();
        

        if ($request->hasFile('featured_image')) {

            $oldImage = public_path('uploads/products/' . $products->featured_image);
            if (File::exists($oldImage)) {
                File::delete($oldImage);
            }
            $featured_image = $request->file('featured_image');
            $featuredimageName = time() . '_' . $featured_image->getClientOriginalName();
            $featured_image->move(public_path('uploads/products'), $featuredimageName);
            $products->featured_image = $featuredimageName;
        }


        if ($request->hasFile('bulk_images')) {

        // Delete old images
        // if (!empty($products->bulk_images)) {
        //     $oldImages = json_decode($products->bulk_images, true);
        //     if (is_array($oldImages)) {
        //         foreach ($oldImages as $oldImage) {
        //             $oldImagePath = public_path('uploads/products/' . $oldImage);
        //             if (File::exists($oldImagePath)) {
        //                 File::delete($oldImagePath);
        //             }
        //         }
        //     }
        // }

        // Upload new images
        $bulk_images = [];
        foreach ($request->file('bulk_images') as $file) {
            $bulkImageName = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/products'), $bulkImageName);
            $bulk_images[] = $bulkImageName;
        }

        $products->bulk_images = json_encode($bulk_images);
       }


        if($products->save()){
            return redirect()->route('product.list')->with('success', 'Product added successfully!');
        }
        else{
            return redirect()->back()->with('error', 'Product not added successfully!'); 
        }
    }

    public function productDelete($id){
        $product = Product::where('id', $id)->first();
        $product->delete();
        
        return redirect()->route('product.list')->with('success', 'Category successfully deleted');
    }

    

}
