<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Product;
use App\Models\ProductStock;
use App\Models\AttributeValue;
use App\Models\Upload;
use App\Models\Color;
use Illuminate\Support\Facades\Storage;
use Illuminate\Pagination\LengthAwarePaginator;
use Combinations;
use DB;
use Artisan;
use Cache;
use Str;



class ProductController extends Controller
{
    public function newproduct(){

     $categories=Category::get();

       return View('admin.partials.products.addnewproduct', compact('categories'));
    }

    public function productlist(Request $request)
   {
      $query = Product::with('stocks')->latest();

      if ($request->search) {
          $query->where('name', 'like', '%' . $request->search . '%');
      }

      if ($request->category) {
          $query->where('category_id', $request->category);
      }

      if ($request->status !== null) {
          $query->where('published', $request->status);
      }

      $allproducts = $query->paginate(10)->appends($request->all());
      $categories = Category::get();
      

      return view(
          'admin.partials.products.productlist',
          compact('allproducts', 'categories')
      );
    }
    public function sku_combination(Request $request)
    {
        $options = [];

        // COLORS
        if ($request->has('colors')) {
            $options['Color'] = (array) $request->colors;
            $colors_active = 1;
        } else {
            $colors_active = 0;
        }

        // ATTRIBUTES
        if ($request->has('choice_no')) {
            foreach ((array) $request->choice_no as $choice) {

                $key = 'choice_options_' . $choice;

                if ($request->has($key)) {
                    $options['attr_' . $choice] = (array) $request->$key;
                }
            }
        }

        if (empty($options)) {
            return '';
        }

        $combinations = $this->combinations($options);
        $unit_price = 0;
        $product_name = 'Product';

        return view(
            'admin.partials.products.sku_combinations',
            compact('combinations', 'unit_price', 'colors_active', 'product_name')
        );
    }

    public function sku_combination_edit(Request $request)
    {
      $product = Product::findOrFail($request->id);
  
      $options = [];
      // COLORS
      $colors_active = 0;

       $colors = $product->colors;
       
       // Decode only if needed
       if (is_string($colors)) {
           $colors = json_decode($colors, true);
       }
       
       // If colors exist → activate
       if (is_array($colors) && count($colors) > 0) {
           $options['Color'] = array_values($colors);
           $colors_active = 1;
       }
      

      // ATTRIBUTES
      if (!empty($product->choice_options)) {
          foreach (json_decode($product->choice_options) as $choice_option) {
              $values = $choice_option->values ?? [];
              if (!empty($values)) {
                  $options['attr_'.$choice_option->attribute_id] = $values;
              }
          }
      }
  
      if (empty($options)) {
          return '';
      }
  
      $product_name = $product->name;
      $unit_price   = $product->unit_price;
  
      // Generate all combinations (attributes + colors)
      $combinations = $this->combinations($options);
  
      return view(
          'admin.partials.products.sku_combinationedit',
          compact('combinations', 'unit_price', 'colors_active', 'product_name', 'product')
      );
   }


    private function combinations($arrays)
    {
        $result = [[]];

        foreach ($arrays as $values) {
            $tmp = [];
            foreach ($result as $res) {
                foreach ($values as $val) {
                    $tmp[] = array_merge($res, [$val]);
                }
            }
            $result = $tmp;
        }

        return $result;
    }

    public function add_more_choice_option(Request $request)
    {
        $values = AttributeValue::where('attribute_id', $request->attribute_id)->get();

        $html = '';
        foreach ($values as $row) {
            $html .= '<option value="'.$row->value.'">'.$row->value.'</option>';
        }

        return response()->json($html);
    }
  
    private function relativePath($url)
    {
    // Converts full URL to relative path
    return str_replace(url('/storage') . '/', '', $url);
    }

    public function upload_product(Request $request)
    {
      //dd($request->all());
       // 1️⃣ Handle thumbnail
               $thumbnail = null;
               if ($request->filled('thumbnail_img')) {
                   $thumbnail = $this->relativePath($request->thumbnail_img);
               }

                $photosArray = [];

               if ($request->has('photos') && is_array($request->photos)) {
                   foreach ($request->photos as $photoString) {
                       // Split comma-separated URLs
                       $items = explode(',', $photoString);

                       foreach ($items as $url) {
                           $photosArray[] = $this->relativePath($url);
                       }
                   }
               }

            $photos = implode(',', $photosArray);


      
        $product = new Product;
        $product->name = $request->name;
        $product->user_id = 1;
        $product->category_id = $request->category_id;
        $product->brand_id = $request->brand_id;
        $product->unit = $request->unit;
        $product->min_qty = $request->min_qty;
        $product->unit_price = $request->unit_price;
        $product->discount = $request->discount;
        $product->discount_type = $request->discount_type;
        $product->external_link = $request->external_link;
        $product->description = $request->description;
        $product->shipping_type = $request->shipping_type;
        $product->shipping_cost  = $request->est_shipping_days;
        $product->low_stock_quantity = 5;
        $product->thumbnail_img = $thumbnail;
        $product->photos = $photos;; 
        if($request->has('video_provider')){
          $product->video_provider = $request->video_provider;
        }
        $product->video_link = $request->video_link;
        if ($request->has('shipping_type')) {
            if ($request->shipping_type == 'free') {
                $product->shipping_cost = 0;
            } elseif ($request->shipping_type == 'flat_rate') {
                $product->shipping_cost = $request->flat_shipping_cost;
            } elseif ($request->shipping_type == 'product_wise') {
                $product->shipping_cost = json_encode($request->shipping_cost);
            }
        }
        if ($request->has('is_quantity_multiplied')) {
            $product->is_quantity_multiplied = 1;
        }
        if ($request->has('meta_title')){
        $product->meta_title = $request->meta_title;
        }
        if ($request->has('meta_description')){
         $product->meta_description = $request->meta_description;
        }
        if ($request->has('meta_img')) {
            $product->meta_img = $request->meta_img;
        } else {
            $product->meta_img = $product->thumbnail_img;
        }
        if ($product->meta_title == null) {
            $product->meta_title = $product->name;
        }
        
        if ($product->meta_img == null) {
            $product->meta_img = $product->thumbnail_img;
        }
        if ($request->hasFile('pdf')) {
            $product->pdf = $request->pdf->store('uploads/products/pdf');
        }
        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
            $product->colors = json_encode($request->colors);
        } else {
            $colors = array();
            $product->colors = json_encode($colors);
        }
        $choice_options = array();
        if ($request->has('choice_no')) {
            foreach ($request->choice_no as $key => $no) {
                $str = 'choice_options_' . $no;
                $item['attribute_id'] = $no;
                $data = array();
                foreach ($request[$str] as $key => $eachValue) {
                    array_push($data, $eachValue);
                }
                $item['values'] = $data;
                array_push($choice_options, $item);
            }
        }

        if (!empty($request->choice_no)) {
            $product->attributes = json_encode($request->choice_no);
        } else {
            $product->attributes = json_encode(array());
        }

        $product->choice_options = json_encode($choice_options, JSON_UNESCAPED_UNICODE);
        $product->published = 1;
        //$variations = array();
        $product->save();


       $variationKey="";
          
          foreach ($request->choice_no as $choiceNo) {
            $optionKey = "choice_options_$choiceNo";
            $options = $request->$optionKey; // e.g., ["Cotton"]

            foreach ($options as $option) {
                $key = $request->colors_active && $request->colors ? $request->colors : ['']; 

                foreach ($key as $color) {
                   
                    $variationKey = $color ? "{$color}-{$option}" : $option;
                    
                }
            }
        }




        $productstock=0;
        $options = array();
        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
            $colors_active = 1;
            array_push($options, $request->colors);
        }

        if ($request->has('choice_no')) {
            foreach ($request->choice_no as $key => $no) {
                $name = 'choice_options_' . $no;
                $data = array();
                foreach ($request[$name] as $key => $eachValue) {
                    array_push($data, $eachValue);
                }
                array_push($options, $data);
            }
        }
        
        $combinations = $this->makeCombinations($options);
        if (count($combinations[0]) > 0) {
            $product->variant_product = 1;
            foreach ($combinations as $key => $combination) {
                $str = '';
                foreach ($combination as $key => $item) {
                    if ($key > 0) {
                        $str .= '-' . str_replace(' ', '', $item);
                    } else {
                        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
                            $color_name = Color::where('code', $item)->first()->name;
                            $str .= $color_name;
                        } else {
                            $str .= str_replace(' ', '', $item);
                        }
                    }
                }
                $product_stock = ProductStock::where('product_id', $product->id)->where('variant', $str)->first();
                if ($product_stock == null) {
                    $product_stock = new ProductStock;
                    $product_stock->product_id = $product->id;
                }


                $imgField = 'img_' . str_replace('.', '_', $str);

                  if ($request->has($imgField)) {
                  //  dd("enter");
                      // Get the full URL from the request
                      $imgUrl = $request->input($imgField);
                  
                      // Extract the relative path from the URL
                      $relativePath = str_replace(url('/storage/'), '', $imgUrl);
                  
                      // Save in DB
                      $product_stock->image = $relativePath; // e.g., 'products/1769591490_6979d2c25a521_RedMain.jpeg'
                  } else {
                   // dd("Not enter");
                      $product_stock->image = null; // no image for this variant
                  }

                $product_stock->variant = $str;
                $product_stock->price = $request['price_' . str_replace('.', '_', $str)];
                $product_stock->sku = $request['sku_' . str_replace('.', '_', $str)];
                $product_stock->qty = $request['qty_' . str_replace('.', '_', $str)];
                $product_stock->save();
                $productstock=$productstock+$request['qty_' . str_replace('.', '_', $str)];
            }
           } else {
            $product_stock              = new ProductStock;
            $product_stock->product_id  = $product->id;
            $product_stock->variant     = '';
            $product_stock->price       = $request->unit_price;
            $product_stock->sku         = $request->sku;
            $product_stock->qty         = $request->current_stock;
            $product_stock->save();
            $productstock=$productstock+$request->current_stock;
        }
        $product->current_stock=$productstock;
        $product->save();

        Artisan::call('view:clear');
        Artisan::call('cache:clear');

         return redirect()->back()->with('success', 'Upload successfully!');

       
    }

    public static function makeCombinations($arrays) { 
        $result = array(array());
        foreach ($arrays as $property => $property_values) {
            $tmp = array();
            foreach ($result as $result_item) {
                foreach ($property_values as $property_value) {
                    $tmp[] = array_merge($result_item, array($property => $property_value));
                }
            }
            $result = $tmp;
        }
        return $result;
    }

    public function test(){
             $options = array();
       if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
           $colors_active = 1;
           array_push($options, $request->colors);
       }
  
       if ($request->has('choice_no')) {
           foreach ($request->choice_no as $key => $no) {
               $name = 'choice_options_' . $no;
               $data = array();
               foreach ($request[$name] as $key => $eachValue) {
                   array_push($data, $eachValue);
               }
               array_push($options, $data);
           }
       }
       //Generates the combinations of customer choice options
      $combinations = $this->makeCombinations($options);
        if (count($combinations[0]) > 0) {
           $product->variant_product = 1;
           foreach ($combinations as $key => $combination) {
               $str = '';
               foreach ($combination as $key => $item) {
                   if ($key > 0) {
                       $str .= '-' . str_replace(' ', '', $item);
                   } else {
                       if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
                           $color_name =  Color::where('code', $item)->first()->name;;
                           $str .= $color_name;
                       } else {
                           $str .= str_replace(' ', '', $item);
                       }
                   }
               }
               $product_stock = ProductStock::where('product_id', $product->id)->where('variant', $str)->first();
               if ($product_stock == null) {
                   $product_stock = new ProductStock;
                   $product_stock->product_id = $product->id;
               }
  
               $product_stock->variant = $str;
               $product_stock->price = $request['price_' . str_replace('.', '_', $str)];
               $product_stock->sku = $request['sku_' . str_replace('.', '_', $str)];
               $product_stock->qty = $request['qty_' . str_replace('.', '_', $str)];
               $product_stock->image = $request['img_' . str_replace('.', '_', $str)];
               $product_stock->save();

               $productstock=$productstock+$request['qty_' . str_replace('.', '_', $str)];
           }
       } else {
           $product_stock              = new ProductStock;
           $product_stock->product_id  = $product->id;
           $product_stock->variant     = '';
           $product_stock->price       = $request->unit_price;
           $product_stock->sku         = $request->sku;
           $product_stock->qty         = $request->current_stock;
           $product_stock->save();

           $productstock=$productstock+$request->current_stock;
       }
      
        //combinations end

        $product->current_stock =$productstock;

        $product->save();
    }


    public function updateproduct($id){

         $product = Product::with('stocks')->findOrFail($id);

        return view('admin.partials.products.updateproduct', [
            'product' => $product,
            'categories' => Category::all(),
        ]);

      

    }

      

    

    
}
