<?php

namespace App\Http\Controllers\Admin;

use App\AttributeValue;
use App\Product;
use App\Category;
use App\Brand;
use App\Position;
use App\ProductMetatag;
use App\ProductDescription;
use App\ProductVideo;
use App\ProductImage;
use App\ProductDocument;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage; //Laravel Filesystem
use DB;
use App\Route;
use App\Log;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\Rule;

class ProductController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:admin');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Product $product)
    {
        $this->authorize('view', $product);

        $data = [];
        $data['product']  = $product;
        $data['products'] = $product->with(['category', 'brand'])->get();

        return view('admin.products.index',$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Product $product)
    {
        $this->authorize('create', $product);

        $data = [];
        $data['product']     = $product;
        $data['catergories'] = Category::getALlCategoriesCT();
        $data['brands']      = Brand::pluck('brand_name','brand_id');
        $data['positions']   = Position::getALlPositionsCT();
        $data['prodimages']  = [];
        $data['documents']   = [];
        $data['catatrids']   = [];
        $data['prodatrdata'] = [];
        $data['create']      = 1;
        return view('admin.products.form', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, Product $product)
    {
        //


        $this->authorize('create', $product);


        $this->validate(
            $request,
            [
                'prod_name'   => 'required|string|min:3',
                'brand_id'    => 'required|integer|exists:brands,brand_id',
                'cat_id'      => 'required|integer|exists:categories,cat_id',
                'prod_sku'    => 'nullable|string|min:3',
                'prod_price'  => 'required|regex:/^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)*$/|min:0.1',
                'prod_weight' => 'required|regex:/^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)*$/|min:0.1',
                'pos_id'      => 'nullable|integer|exists:positions,pos_id',
                'prod_status' => 'required|integer|in:1,0',

                'prod_title'    => 'nullable|string|min:10',
                'prod_metadesc' => 'nullable|string|min:10',
                'prod_keyw'     => 'nullable|string|min:10',

                'prod_mdesc'    => 'nullable|string|min:10',
                'prod_desc'     => 'nullable|string|min:10',

                'prod_video'    => 'nullable|string|min:10',

                'atr_val_id.*'      => 'nullable|integer|exists:attribute_values,atr_val_id',
                'm_atr_val_id.*'    => 'nullable|array',
                'm_atr_val_id.*.*'  => 'nullable|integer|exists:attribute_values,atr_val_id',

                'images.*' => 'required|image|mimes:jpeg,png,jpg,gif|max:5120',
                "pdfdoc.*" => 'nullable|mimes:pdf|max:10000',
            ]
        );


        // get Brand name
        $brand_name = Brand::find($request->brand_id)->brand_name;

        // Clear name from dq
        $prod_name = repalceQt($request->prod_name);


        // Check if slug exist in routes

        $slug = str_slug($brand_name.' '.$prod_name);

        if (Route::where('slug', '=', $slug)->exists()) {
            return redirect()->back()->withInput()->with('error', __('adminforms.products.slug_exists_err'));
            exit;
        }

        try{

            DB::beginTransaction();
            // Product


            // Setting prod_sdesc

            $mdescription = removeExtraSpaceAndBreaks($request->prod_mdesc);
            $sdescription = removeExtraSpaceAndBreaks($request->prod_desc);

            $sdesc = (trim($request->prod_mdesc) != '') ? stripTagsAndSubstr($mdescription) : stripTagsAndSubstr($sdescription);






            $product = new Product();

            $product->prod_name         = $prod_name;
            $product->brand_id          = $request->brand_id;
            $product->cat_id            = $request->cat_id;
            $product->prod_sku          = $request->prod_sku;
            $product->prod_price        = $request->prod_price;
            $product->prod_weight       = $request->prod_weight;
            $product->pos_id            = $request->pos_id;
            $product->prod_status       = $request->prod_status;

            $product->prod_timg         = config('images.no_image_paths.t');
            $product->prod_simg         = config('images.no_image_paths.s');
            $product->prod_mimg         = config('images.no_image_paths.m');
            $product->prod_bimg         = config('images.no_image_paths.b');

            $product->prod_sdesc        = $sdesc;
            //$product->prod_slug         = $slug;

            $product->prod_created_by   = auth('admin')->user()->full_name;

            //no image za sve putanje definisati u config.images

            $product->save();


            // reinstantiating product object due to active transaction
            $id = DB::getPdo()->lastInsertId();
            $product = Product::find($id);


            // Product Meta tags
            if(trim($request->prod_title) != '' || trim($request->prod_metadesc) != '' ||  trim($request->prod_keyw) != '' ) {

                $mt = new ProductMetatag();

                $mt->prod_title     = repalceQt(removeExtraSpaceAndBreaks($request->prod_title));
                $mt->prod_metadesc  = repalceQt(removeExtraSpaceAndBreaks($request->prod_metadesc));
                $mt->prod_keyw      = repalceQt(removeExtraSpaceAndBreaks($request->prod_keyw));

                $product->metatags()->save($mt);
            }


            // Product descriptions
            // -------------------------------------
            if($mdescription != '' || $sdescription != '' ) {

                $pd = new ProductDescription();

                $pd->prod_mdesc  = $mdescription;
                $pd->prod_desc   = $sdescription;

                $product->description()->save($pd);

            }

            // Product video
            // -------------------------------------
            if(trim($request->prod_video) != '' ) {

                $pv = new ProductVideo();

                $pv->prod_video  = removeWidthHeightAttribute($request->prod_video);

                $product->video()->save($pv);
            }


            // Product AttributeValues
            // -----------------------
            $corectAttributeValues = [];

            // If submited attributes get ids of existing atr_val_id-s for validation
            if(($request->has('atr_val_id') && is_array($request->atr_val_id)) || ($request->has('m_atr_val_id') && is_array($request->m_atr_val_id))){
                $existingAttrValIds = AttributeValue::pluck('atr_val_id')->toArray();
            }

            // Attributes with single value
            if($request->has('atr_val_id') && is_array($request->atr_val_id)){
                foreach($request->atr_val_id as $aid => $valid){
                    if(is_numeric($valid) && $valid > 0 && in_array($valid, $existingAttrValIds)){
                        $corectAttributeValues[$valid] = ['atr_id' => $aid];
                    }
                }
            }

            // Attributes with multiple values
            if($request->has('m_atr_val_id') && is_array($request->m_atr_val_id)){
                foreach($request->m_atr_val_id as $aid => $vals){
                    foreach($vals as $i => $valid){
                        if(is_numeric($valid) && $valid > 0 && in_array($valid, $existingAttrValIds)){
                            $corectAttributeValues[$valid] = ['atr_id' => $aid];
                        }
                    }
                }
            }

            $product->attributevalues()->sync($corectAttributeValues);

            $prodAtrCount = $product->attributevalues->count();

            // Update prod atrDesc if product have atr vals
            if($prodAtrCount){
                Product::updateProductAttributeDescription($product->prod_id);
            }



            // Product Images
            // --------------------------------------
            if ($request->hasFile('images')) {

                foreach($request->file('images') as $file){


                    $result = $this->uploadImage($file, $slug);

                    if(is_array($result) && !empty($result)) {

                        $image = new ProductImage();

                        $image->prod_timg = trim($result['t']);
                        $image->prod_simg = trim($result['s']);
                        $image->prod_mimg = trim($result['m']);
                        $image->prod_bimg = trim($result['b']);

                        $product->images()->save($image);

                    }


                }

                // updejt putanja slika za product

                // Dobijanje id-ja prve unete slike
                $defImgID = DB::table('product_images')->where('prod_id', $product->prod_id)->min('prod_img_id');

                // Oznacavanje date slike kao osnovne
                ProductImage::where('prod_id', $product->prod_id)->where('prod_img_id', $defImgID)->update(['prod_def_img' => 1]);

                // Update Slika u products
                Product::updateImagesForListing($product->prod_id);
            }




            // Product Documents
            // --------------------------------------
            if ($request->hasFile('pdfdoc')) {

                foreach($request->file('pdfdoc') as $doc){

                    $result = $this->uploadDocument($doc);

                    if( is_array($result) && !empty($result) && file_exists(public_path($result['path']))){

                        $doc = new ProductDocument();

                        $doc->pd_name = trim($result['name']);
                        $doc->pd_path = trim($result['path']);
                        $doc->pd_type = trim($result['type']);

                        $product->documents()->save($doc);
                    }

                }

            }



            // Update nuber of active products in categrories
            //---------------------------------------------------

            $rowCount = DB::update('UPDATE `categories` c
                                          INNER JOIN (
                                          SELECT c.`cat_id` , /*c.`cat_name` ,*/ COUNT( p.`prod_id` ) AS ap, p.`prod_status` 
                                          FROM `categories` c
                                          INNER JOIN `products` p ON c.`cat_id` = p.`cat_id` 
                                          AND p.`prod_status` = 1
                                          GROUP BY p.`cat_id`
                                          ) t ON c.`cat_id` = t.`cat_id`
                                          SET c.`cat_ap` = t.ap; ');



            // Update insert active brands in categories
            //-------------------------------------------

            DB::statement( 'TRUNCATE categoriesBrandsActive;' );

            $rowCount = DB::insert('INSERT INTO `categoriesBrandsActive` ( `cat_id` , `brand_id` ) 
                                          SELECT DISTINCT c.`cat_id` , b.`brand_id` 
                                          FROM `categories` c
                                          INNER JOIN `products` p ON c.`cat_id` = p.`cat_id` 
                                          AND p.`prod_status` = 1
                                          INNER JOIN `brands` b ON p.`brand_id` = b.`brand_id` 
                                          ORDER BY c.`cat_id` , b.`brand_id`');


            // Insert slug in routes
            // ---------------------------


            foreach(config('app.languages') as $lang) {

                $newroute = new Route();

                $newroute->object    = 'Product';
                $newroute->object_id = $product->prod_id;
                $newroute->lang      = $lang;
                $newroute->slug      = $request->{$lang.'_slug'};

                $newroute->save();

            }



            // Create log record
            //--------------------------------------------

            $log = new Log();

            $log->object    = 'Product';
            $log->object_id = $product->prod_id;
            $log->action    = 'create';
            $log->admin     = auth('admin')->user()->full_name;
            $log->note      = NULL;

            $log->save();

            DB::commit();

            return redirect()->route('admin.product.index')->with('result', __('adminforms.products.insert_controller_msg', ['name' => $product->prod_name]));

        } catch (\Illuminate\Database\QueryException $e) {
            DB::rollBack();
            echo handle_error($e);
        } catch (\Exception $e) {
            DB::rollBack();
            echo handle_error($e);
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Product $product)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit(Product $product)
    {
        $this->authorize('update', $product);

        $data = [];
        $data['product']         = $product;
        $data['catergories']     = Category::getALlCategoriesCT();
        $data['brands']          = Brand::pluck('brand_name','brand_id');
        $data['positions']       = Position::getALlPositionsCT();
        $data['catatrids']       = Category::find($product->cat_id)->attributes->pluck('atr_id')->toArray();
        $data['prodimages']      = $product->images;
        $data['documents']       = $product->documents->sortBy('pd_id');
        $data['prodatrdata']     = $product->getProductAttributeValues();
        $data['create']          = 0;

        return view('admin.products.form', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Product $product)
    {
        $this->authorize('create', $product);


        //dd($request->all());


        $rules = [
                    'prod_name'   => 'required|string|min:3',
                    'brand_id'    => 'required|integer|exists:brands,brand_id',
                    'cat_id'      => 'required|integer|exists:categories,cat_id',
                    'prod_sku'    => 'nullable|string|min:3',
                    'prod_price'  => 'required|regex:/^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)*$/|min:0.1',
                    'prod_weight' => 'required|regex:/^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)*$/|min:0.1',
                    'pos_id'      => 'nullable|integer|exists:positions,pos_id',
                    'prod_status' => 'required|integer|in:1,0',

                    'prod_title'    => 'nullable|string|min:10',
                    'prod_metadesc' => 'nullable|string|min:10',
                    'prod_keyw'     => 'nullable|string|min:10',

                    'prod_mdesc'    => 'nullable|string|min:10',
                    'prod_desc'     => 'nullable|string|min:10',

                    'prod_video'    => 'nullable|string|min:10',

                    'atr_val_id.*'      => 'nullable|integer|exists:attribute_values,atr_val_id',
                    'm_atr_val_id.*'    => 'nullable|array',
                    'm_atr_val_id.*.*'  => 'nullable|integer|exists:attribute_values,atr_val_id',

                    'images.*' => 'required|image|mimes:jpeg,png,jpg,gif|max:5120',
                ];

        foreach(config('app.languages') as $lang){

            $rules[$lang.'_slug']          = ['required', 'string', 'min:3',
                Rule::unique('routes','slug')
                    ->where(function ($query) use ($lang, $product) {
                        return $query
                            ->where('lang', $lang)
                            ->whereRaw('CONCAT(object,"",object_id) <> ? ', ['Product'.$product->prod_id]);
                    })
            ];
        }

        $this->validate( $request,$rules );

        // get Brand name
        $brand_name = Brand::find($request->brand_id)->brand_name;

        // Clear name from dq
        $prod_name = repalceQt($request->prod_name);


        // Check if slug exist in routes

        $slug = str_slug($brand_name.' '.$prod_name);



        if (Route::where('slug', '=', $slug)->whereRaw('CONCAT(object,"",object_id) != ?', ['Product'.$product->prod_id])->exists()) {
            return redirect()->back()->withInput()->with('error', __('adminforms.products.slug_exists_err'));
            exit;
        }



        try{

            DB::beginTransaction();


            // Setting prod_sdesc

            $mdescription = removeExtraSpaceAndBreaks($request->prod_mdesc);
            $sdescription = removeExtraSpaceAndBreaks($request->prod_desc);

            $sdesc = (trim($request->prod_mdesc) != '') ? stripTagsAndSubstr($mdescription) : stripTagsAndSubstr($sdescription);


            $product->prod_name         = $prod_name;
            $product->brand_id          = $request->brand_id;
            $product->cat_id            = $request->cat_id;
            $product->prod_sku          = $request->prod_sku;
            $product->prod_price        = $request->prod_price;
            $product->prod_weight       = $request->prod_weight;
            $product->pos_id            = $request->pos_id;
            $product->prod_status       = $request->prod_status;
            $product->prod_sdesc        = $sdesc;
            //$product->prod_slug         = $slug;

            $product->save();


            // Product Meta tags
            //---------------------------------------

            if(trim($request->prod_title) != '' || trim($request->prod_metadesc) != '' ||  trim($request->prod_keyw) != '' ) {

                $mt = (isset($product->metatags)) ? $product->metatags : new ProductMetatag();

                $mt->prod_title    = repalceQt(removeExtraSpaceAndBreaks($request->prod_title));
                $mt->prod_metadesc = repalceQt(removeExtraSpaceAndBreaks($request->prod_metadesc));
                $mt->prod_keyw     = repalceQt(removeExtraSpaceAndBreaks($request->prod_keyw));

                $product->metatags()->save($mt);
            } else {
                $product->metatags()->delete();
            }



            // Product descriptions
            // -------------------------------------
            if($mdescription != '' || $sdescription != '' ) {

                $pd =  (isset($product->description)) ? $product->description : new ProductDescription();

                $pd->prod_mdesc  = $mdescription;
                $pd->prod_desc   = $sdescription;

                $product->description()->save($pd);

                // Updejt malog opisa za product

            } else {
                $product->description()->delete();
            }

            // Product video
            // -------------------------------------

            if(trim($request->prod_video) != '' ) {

                $pv = (isset($product->video)) ? $product->video : new ProductVideo();

                $pv->prod_video  = removeWidthHeightAttribute($request->prod_video);

                $product->video()->save($pv);
            } else {
                $product->video()->delete();
            }


            // Product AttributeValues
            // -----------------------
            $corectAttributeValues = [];

            if(($request->has('atr_val_id') && is_array($request->atr_val_id)) || ($request->has('m_atr_val_id') && is_array($request->m_atr_val_id))){
                $existingAttrValIds = AttributeValue::pluck('atr_val_id')->toArray();
            }

            // Attributes with single value
            if($request->has('atr_val_id') && is_array($request->atr_val_id)){
                foreach($request->atr_val_id as $aid => $valid){
                    if(is_numeric($valid) && $valid > 0 && in_array($valid, $existingAttrValIds)){
                        $corectAttributeValues[$valid] = ['atr_id' => $aid];
                    }
                }
            }

            // Attributes with multiple values
            if($request->has('m_atr_val_id') && is_array($request->m_atr_val_id)){
                foreach($request->m_atr_val_id as $aid => $vals){
                    foreach($vals as $i => $valid){
                        if(is_numeric($valid) && $valid > 0 && in_array($valid, $existingAttrValIds)){
                            $corectAttributeValues[$valid] = ['atr_id' => $aid];
                        }
                    }
                }
            }

            $product->attributevalues()->sync($corectAttributeValues);

            $prodAtrCount = $product->attributevalues->count();

            // Update prod atrDesc if product have atr vals
            if($prodAtrCount){
                Product::updateProductAttributeDescription($product->prod_id);
            }


            // Product Images
            // --------------------------------------
            if ($request->hasFile('images')) {

                $numOfExistingImages = $product->images->count();


                foreach($request->file('images') as $file){

                    $result = $this->uploadImage($file, $slug);

                    //echo '<pre>'.print_r($result,true).'</pre>';

                    if(is_array($result) && !empty($result)) {

                        $image = new ProductImage();

                        $image->prod_timg = trim($result['t']);
                        $image->prod_simg = trim($result['s']);
                        $image->prod_mimg = trim($result['m']);
                        $image->prod_bimg = trim($result['b']);

                        $product->images()->save($image);

                    }

                }

                if($numOfExistingImages == 0){

                    // updejt putanja slika za product

                    // Dobijanje id-ja prve unete slike
                    $defImgID = DB::table('product_images')->where('prod_id', $product->prod_id)->min('prod_img_id');

                    // Oznacavanje date slike kao osnovne
                    ProductImage::where('prod_id', $product->prod_id)->where('prod_img_id', $defImgID)->update(['prod_def_img' => 1]);

                    // Update Slika u products
                    Product::updateImagesForListing($product->prod_id);

                }
            }


            // Product Documents
            // --------------------------------------
            if ($request->hasFile('pdfdoc')) {

                foreach($request->file('pdfdoc') as $doc){

                    $result = $this->uploadDocument($doc);

                    if( is_array($result) && !empty($result) && file_exists(public_path($result['path']))){

                        $doc = new ProductDocument();

                        $doc->pd_name = trim($result['name']);
                        $doc->pd_path = trim($result['path']);
                        $doc->pd_type = trim($result['type']);

                        $product->documents()->save($doc);
                    }

                }

            }


            // Update nuber of active products in categrories
            //---------------------------------------------------

            $rowCount = DB::update('UPDATE `categories` c
                                          INNER JOIN (
                                          SELECT c.`cat_id` , /*c.`cat_name` ,*/ COUNT( p.`prod_id` ) AS ap, p.`prod_status` 
                                          FROM `categories` c
                                          INNER JOIN `products` p ON c.`cat_id` = p.`cat_id` 
                                          AND p.`prod_status` = 1
                                          GROUP BY p.`cat_id`
                                          ) t ON c.`cat_id` = t.`cat_id`
                                          SET c.`cat_ap` = t.ap; ');


            // Update insert active brands in categories
            //-------------------------------------------

            DB::statement( 'TRUNCATE categoriesBrandsActive;' );

            $rowCount = DB::insert('INSERT INTO `categoriesBrandsActive` ( `cat_id` , `brand_id` ) 
                                          SELECT DISTINCT c.`cat_id` , b.`brand_id` 
                                          FROM `categories` c
                                          INNER JOIN `products` p ON c.`cat_id` = p.`cat_id` 
                                          AND p.`prod_status` = 1
                                          INNER JOIN `brands` b ON p.`brand_id` = b.`brand_id` 
                                          ORDER BY c.`cat_id` , b.`brand_id`');



            // Update slug in routes
            // ---------------------------

            foreach(config('app.languages') as $lang) {

                $route = Route::where('object', '=', 'Product')->where('lang', '=', $lang)->where('object_id', '=', $product->prod_id)->first();

                if ($route) {
                    $route->slug = $request->{$lang.'_slug'};
                    $route->save();
                } else {

                    $newroute = new Route();

                    $newroute->object    = 'Product';
                    $newroute->object_id = $product->prod_id;
                    $newroute->lang      = $lang;
                    $newroute->slug      = $request->{$lang.'_slug'};

                    $newroute->save();

                }

            }


            // Create log record
            //--------------------------------------------

            $log = new Log();

            $log->object    = 'Product';
            $log->object_id = $product->prod_id;
            $log->action    = 'update';
            $log->admin     = auth('admin')->user()->full_name;
            $log->note      = NULL;
            
            $log->save();


            DB::commit();

            return redirect()->route('admin.product.index')->with('result', __('adminforms.products.update_controller_msg', ['name' => $product->prod_name]));

        } catch (\Illuminate\Database\QueryException $e) {
            DB::rollBack();
            echo handle_error($e);
        } catch (\Exception $e) {
            DB::rollBack();
            echo handle_error($e);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {

        $this->authorize('delete', $product);

        $name = $product->prod_name;
        $id   = $product->prod_id;

        // Delete images

        $this->deleteProductImages($product);

        // Delete documents

        $documents = $product->documents;

        if(!empty($documents)) {
            foreach ($documents as $document){

                $path  = public_path($document->pd_path);
                if(file_exists($path) && is_readable($path)){ unlink($path);}

            }
        }




        try{
            DB::beginTransaction();

            // Remove slug from routes
            // ------------------------------

            $routes = Route::where('object', '=', 'Product')->where('object_id', '=', $id)->get();
            if(!empty($routes)){
                foreach($routes as $route){
                    $route->destroy($route->id);
                }
            }



            // Create log record
            //--------------------------------------------

            $log = new Log();

            $log->object    = 'Product';
            $log->object_id = $id;
            $log->action    = 'delete';
            $log->admin     = auth('admin')->user()->full_name;
            $log->note      = 'Name: '.$name;

            $log->save();



            // Delete Product
            // ----------------------------------------------
            $product->destroy($product->prod_id);

            DB::commit();

            return redirect()->route('admin.product.index')->with('result', __('adminforms.products.delete_controller_msg', ['name' => $name]));

        } catch (\Illuminate\Database\QueryException $e) {
            DB::rollBack();
            echo handle_error($e);
        } catch (\Exception $e) {
            DB::rollBack();
            echo handle_error($e);
        }
    }


    private function deleteProductImages($product){

        try{
            $prodimages = $product->images;

            if(!empty($prodimages)) {
                foreach ($prodimages as $img){

                    // Delete from disk
                    $timg = public_path($img->prod_timg);
                    $simg = public_path($img->prod_simg);
                    $mimg = public_path($img->prod_mimg);
                    $bimg = public_path($img->prod_bimg);

                    if(file_exists($timg) && is_readable($timg)){ unlink($timg);}
                    if(file_exists($simg) && is_readable($simg)){ unlink($simg);}
                    if(file_exists($mimg) && is_readable($mimg)){ unlink($mimg);}
                    if(file_exists($bimg) && is_readable($bimg)){ unlink($bimg);}

                    // Delete from db
                    DB::delete('DELETE FROM `product_images` WHERE `prod_img_id` = :id ', [':id' => $img->prod_img_id]);

                }
            }

            return true;

        } catch (\Illuminate\Database\QueryException $e) {
            // something went wrong with the transaction, rollback
            echo handle_error($e);
        } catch (\Exception $e) {
            // something went wrong elsewhere
            echo handle_error($e);
        }

    }

    private function uploadImage($file,$slug){



            $result = [];

            $img_quality = config('images.quality');
            $img_paths = config('images.path');


            //get filename with extension
            $filenamewithextension = $file->getClientOriginalName();
            //get filename without extension
            $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);
            //get file extension
            $extension = $file->getClientOriginalExtension();




            foreach ($img_paths as $s => $path) {


                //filename to store
                $filenametostore = $slug. '.' . $extension;

                $path_to_check = $img_paths[$s] . $filenametostore;

                if (file_exists(public_path($path_to_check))) {
                    $tmp = '';
                    for ($i = 2; $i <= 1000; $i++) {
                        $tmp = $slug . '-' . $i . '.' . $extension;
                        if (!file_exists(public_path($img_paths[$s] . $tmp))) {
                            $filenametostore = $tmp;
                            break;
                        }
                        $tmp = '';
                    }
                }


                $cpath = $path . $filenametostore;


                Storage::disk('public_uploads')->put($cpath, fopen($file, 'r+'));


                $padding = config('images.size.' . $s . '.padding');
                $width = config('images.size.' . $s . '.width');
                $height = config('images.size.' . $s . '.height');
                $resize_width = $width - (2 * $padding);
                $resize_height = $height - (2 * $padding);


                $storage_path = public_path($cpath);

                $img = Image::make($storage_path)->resize(300, 300)->encode('jpg');

                // create new image with transparent background color
                $background = Image::canvas($width, $height);

                // read image file and resize it to 90x90
                // but keep aspect-ratio and do not size up,
                // so smaller sizes don't stretch
                $image = Image::make($storage_path)->resize($resize_width, $resize_height, function ($c) {
                    $c->aspectRatio();
                    $c->upsize();
                });



                // insert resized image centered into background
                $background->insert($image, 'center', $padding, $padding);

                $res = $background->save($storage_path, $img_quality);



                // save image
                if ($res) {
                    $result[$s] = $cpath;
                }


            } // end foreach

            return $result;



    } // end method uploadImage


    private function uploadDocument($file){

        $result = [];


        $doc_path   = config('docs.documents_path');


        //get filename with extension
        $filenamewithextension = $file->getClientOriginalName();
        //get filename without extension
        $filename = str_replace('_', ' ', pathinfo($filenamewithextension, PATHINFO_FILENAME));
        //get file extension
        $extension = $file->getClientOriginalExtension();
        // filenameslug
        $filenameslug = str_slug($filename);

        //filename to store
        $filenametostore = $filenameslug.'.'.$extension;

        $path_to_check = $doc_path.$filenametostore;

        if( file_exists(public_path($path_to_check))){
            $tmp = '';
            for ($i = 2; $i <= 1000; $i++) {
                $tmp = $filenameslug.'-'.$i.'.'.$extension;
                if(!file_exists(public_path($doc_path.$tmp)) ){
                    $filenametostore = $tmp;
                    break;
                }
                $tmp = '';
            }
        }






        if($file->move($doc_path, $filenametostore)){

            $result['path'] =  $doc_path.$filenametostore;
            $result['name'] =  $filename;
            $result['type'] =  strtolower($extension);

        }



        return $result;

    } // end method uploadDocument


}
