<?php

namespace App\Http\Controllers\Merchant;

use Picqer;
use Exception;
use Throwable;
use App\Models\Product;
use App\Models\Variant;
use Illuminate\Support\Str;
use App\Models\ProductImage;
use Illuminate\Http\Request;
use App\Models\ProductBarcode;
use App\Models\ProductVariant;
use Illuminate\Validation\Rule;
use App\Models\ProductAttribute;
use Barryvdh\DomPDF\Facade as PDF;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Intervention\Image\Facades\Image;
use App\Services\FileUpload;

class ProductController extends Controller
{
      
    public function index(Request $request)
    {

      //  return $request->all();
        $paginate = $request->item ?? 20;

        if($request->status=="all"){
            $products = Product::where('merchant_id',session()->get('merchant')['id'])
            ->orderBy('id', 'DESC')->with(['productImage', 'productBarcode'])
            ->paginate($paginate);

        }else{
            $products = Product::where('merchant_id',session()->get('merchant')['id'])
            ->orderBy('id', 'DESC')->with(['productImage', 'productBarcode'])
            ->where('status',$request->status)
            ->paginate($paginate);
 
        }
        return response()->json([
            'status' => 'SUCCESS',
            'products' => $products
        ]);
    }


    public function slugCreator($string, $delimiter = '-') {
        // Remove special characters
          $string = preg_replace("/[~`{}.'\"\!\@\#\$\%\^\&\*\(\)\_\=\+\/\?\>\<\,\[\]\:\;\|\\\]/", "", $string);
        // Replace blank space with delimiter
        $string = preg_replace("/[\/_|+ -]+/", $delimiter, $string);
        return $string;
    }





    public function storeProduct(Request $request)
    {
        // return $request->all();
        $data = $request->validate([
            'name' => 'required ',
            'merchant_id' => 'nullable|integer',
            'category_id' => 'required|integer',
            'sub_category_id' => 'required|integer',
            'sub_sub_category_id' => 'nullable|integer',
            'discount' => 'nullable|integer',
            'sale_price' => 'required|integer',
            'is_manual_stock' => 'required|integer',
            'stock' => 'nullable|integer',
            'price' => 'required',
            'details' => 'nullable',
            'images' => 'required',
            'is_featured' => 'nullable|integer',
            'video_url' => 'nullable',
            'size_chart' => 'nullable',
            'size_id' => 'nullable',
            'color_id' => 'nullable',
            'sizes' => 'nullable',
            'colors' => 'nullable',
            'brand_id' => 'nullable',
            'reselling_price' => 'required',

        ]);

        $data['discount'] = $data['reselling_price'] - $data['price'];
        $data['status'] = 2;
        DB::beginTransaction();
        try {
                //get products tables max id
                $id = Product::max('id') ?? 0;
                $product_code = 1000 + $id;
                $data['product_code']  = $product_code;
                $data['slug'] = Str::slug($data['name']) . '-' . $product_code;
                $data['merchant_id'] = session()->get('merchant')['id'];
                $product = Product::query()->create($data);

                //if product save then generate product barcode
                $generator = new Picqer\Barcode\BarcodeGeneratorHTML();
                $barcode = $generator->getBarcode($product->product_code, $generator::TYPE_CODE_128);
                $product_barcode = new ProductBarcode();
                $product_barcode->product_id = $product->id;
                $product_barcode->barcode = $barcode;
                $product_barcode->barcode_number = $product->product_code;
                $product_barcode->save();

                //save product multiple image in store directory
                if ($request->hasFile('images')) {
                    $files = $request->file('images');

                    //make thumbnail image
                    $filename = time() . $files[0]->getClientOriginalName();
                    $image_resize = Image::make($files[0]->getRealPath());
                    $image_resize->resize(400, 400, function ($constraint) {
                        $constraint->aspectRatio();
                    });
                    
                    $image_resize->save(public_path('storage/images/product_thumbnail_img/' . $filename));
                    $product->thumbnail_img = 'images/product_thumbnail_img/' . $filename;
                    $product->save();
                  
                    foreach ($files as $file) {
                        $product_image = new ProductImage();
                        $product_image->product_id = $product->id;
                        $path = 'product_'.time().'_'.rand(1111,9999).'.jpg';
                        Image::make(file_get_contents($file))->save(public_path('storage/images/products/').$path);
                        $product_image->image = 'images/products/'.$path;
                        $product_image->save();
                    }
                }

            //save the product properties
            if (isset($request->attribute) && !empty($request->attribute)) {
                $product_attribute = new ProductAttribute();
                $product_attribute->product_id = $product->id;
                $product_attribute->attribute_id = $request->attribute;
                $product_attribute->save();
            }
           //save the product variants
           if (isset($request->variants) && !empty($request->variants)) {
             foreach ($request->variants as $item) {
                $variant = Variant::findOrFail($item);
                $product_variant = new ProductVariant();
                $product_variant->product_id = $product->id;
                $product_variant->variant_id = $item;
                $product_variant->attribute_id = $variant->attribute_id;
                $product_variant->save();
             }
            }

            DB::commit();
            //return success message
            return response()->json([
                'status' => true,
                'message' => 'product added successfully'
            ]);

        } catch (Throwable $th) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => $th->getMessage()
            ]);
        }
        
        

    }


    
    public function getProduct($id){

        $product = Product::with('productVariant:product_id,variant_id')->findOrFail($id);
        
        $images = ProductImage::where('product_id', $product->id)->orderBy('id','asc')->get();
        return response()->json([
            'success' => true,
            'product' => $product,
           
            'images' => $images,
        ]);

    }



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

        // return $request->all();
        
        $request->validate([
            'name' => 'required ',
            'category_id' => 'required|integer',
            'sub_category_id' => 'nullable|integer',
            'sub_sub_category_id' => 'nullable|integer',
            'sale_price' => 'required',
            'price' => 'required',
            'details' => 'required',
            'reselling_price' => 'required',
            'brand_id' => 'nullable',

        ]);

        DB::beginTransaction();
        try{

            //save product data
            $product=Product::where('merchant_id',session()->get('merchant')['id'])->where('id',$id)->first() ;
            $product->name = $request->name;
            $product->category_id = $request->category_id;
            $product->sub_category_id = $request->sub_category_id ?? null;
            $product->sub_sub_category_id = $request->sub_sub_category_id ?? null;
            $product->brand_id = $request->brand_id ?? null;
            $product->sale_price = $request->sale_price;
            $product->price = $request->price;
            $product->reselling_price = $request->reselling_price;
            $product->discount = $request->discount ?? null;
            $product->details = $request->details;
            $product->stock = $request->stock;
            $product->save();


            if ($request->hasFile('images')) {
                $files = $request->file('images');
                //make thumbnail image
                $filename = time() .$files[0]->getClientOriginalName();
                $image_resize = Image::make($files[0]->getRealPath());
                $image_resize->resize(400, 400, function ($constraint) {
                    $constraint->aspectRatio();
                });
                $image_resize->save(public_path('storage/images/product_thumbnail_img/'.$filename));
                $product->thumbnail_img = 'images/product_thumbnail_img/'.$filename;
                $product->save();
                
                if($files > 0) {
                    foreach ($files as $key => $file) {
                        $p_c_image = new ProductImage() ;
                        $path = $file->store('images/products','public');
                        $p_c_image->product_id = $product->id ;
                        $p_c_image->image = $path ;
                        $p_c_image->save();
                   }

                }
            }
            


            //save the product properties
            if (isset($request->attribute) && !empty($request->attribute)) {
                    ProductAttribute::whereIn('product_id',[$id])->delete();
                    $product_attribute=new ProductAttribute () ;
                    $product_attribute->product_id = $product->id;
                    $product_attribute->attribute_id = $request->attribute;
                    $product_attribute->save();
                

            }
            if (isset($request->variants) && !empty($request->variants)) {
                ProductVariant::whereIn('product_id',[$id])->delete();
                foreach ($request->variants as $item) {
                    $variant = Variant::findOrFail($item);
                    $product_variant= new ProductVariant() ;
                    $product_variant->product_id = $product->id;
                    $product_variant->variant_id = $item;
                    $product_variant->attribute_id = $variant->attribute_id;
                    $product_variant->save();
                }

            }
            DB::commit();
            //return success message
            return response()->json([
                'status' => true,
                'message' => 'product updated successfully'
            ]);
          
        }catch(Exception $e){
            DB::rollBack();
            return $e->getMessage();
       }
    }



    public function searchProducts($search)
    {
          $merchant_product = Product::where('merchant_id',session()->get('merchant')['id'])
                                        ->where('product_code',$search)
                                         ->orWhere('name','like','%'.$search.'%')
                                        ->with(['productImage', 'productBarcode'])->paginate(20);
      
    

                return response()->json([
                    'status' => 'SUCCESS',
                    'products' => $merchant_product
                ]);

        
    }


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

        $product_image=ProductImage::where('product_id',$id)->get();
        if ($product_image[$request->index]->delete()){
            return response()->json([
                'status'=>'SUCCESS',
                'message'=>'product image was deleted'
            ]);
        }    
   }


   public function deleteImage($id)
   {
       ProductImage::findOrFail($id)->delete();
       return response()->json([
           'success'=>true,
           'message'=>' image  deleted'
       ]);

   }















}