<?php

namespace App\Imports;


use App\Model\Store\Store;
use App\Model\Inventory\Category;
use App\Model\Inventory\Product;
use App\Model\Inventory\Product_meta;
use App\Model\Gallery;
use App\Models\Data\EventResult;
use Maatwebsite\Excel\Validators\Failure;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Validators\ValidationException;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use DB;


use Auth;
class ImportProduct implements ToModel, WithValidation, WithHeadingRow, WithMultipleSheets, WithEvents
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    use Importable, RegistersEventListeners;

    public static function beforeImport(BeforeImport $event)
    {
        $worksheet = $event->reader->getActiveSheet();
        $highestRow = $worksheet->getHighestRow(); // e.g. 10

        if ($highestRow < 2) {
            $error = \Illuminate\Validation\ValidationException::withMessages([]);
            $failure = new Failure(1, 'rows', [0 => 'Please upload a Excel valid  file or Excel file is blank!']);
            $failures = [0 => $failure];
            throw new ValidationException($error, $failures);
        }
    }

    public function model(array $row)
    {

       
        HeadingRowFormatter::default('none');
      //  $company_id = Auth::user()->company_id;  
      //  $dimensions = explode("x",$row['dimensions']);
       // echo "<pre>";print_r($row);
    //   foreach($row as $get){
    //      echo "<pre>";print_r($get);
    //      //die;
    // }
       $company_id = Auth::user()->company_id;
    //   $Category = Category::create([
    //             'company_id' => $company_id,
    //             'name' => $row['name'],
    //             'images' => $row['imageurl'],
    //             'description' => $row['description'],
    //             'sku' => 'null'
     //         ]);
     //echo $row['category'];
    // die;
        $exploded = explode (",", $row['category']); 
      // echo '<pre>';print_r($exploded);
      // die;
//print_r($get);




        $values = implode(',', array_map(function($value)
{
    return trim($value, ',');
},$exploded));

       // $get = 'testing,Open Polki Tops';
       // die;
        $enquiry_1 = [];
        $enquiry_1 = DB::table('category')
                ->where('company_id', $company_id)
                ->whereIn('name',explode(',',$values))
                ->select('id')
                ->get();
              
         
                
                
                $array = $enquiry_1->map(function($i) {
                                 return (array)$i;
                                 })->toArray();

        $useArrayOutSideLoop = array();
                foreach($array as $getValueNew){      
                    $useArrayOutSideLoop[] = $getValueNew['id'];
                   
                }
                //echo '<pre>';print_r($useArrayOutSideLoop);
                $getStringValue= implode(',',$useArrayOutSideLoop);
               // echo $getStringValue;
              //  die;
                        
  
  
  
     // die;
  //   die;
        $Product = Product::create([
            'company_id'=>$company_id,
              'title' => $row['product_name'],
              'slug' => $row['sku'],
              'product_type' => 'simple',
              'status' => $row['stock_quantity'] ? 1 : 0,
              'sku' => $row['sku'],
              'price'=>$row['price'],
             // 'length' =>  $dimensions[0],
             // 'width' =>   $dimensions[1],
             // 'height' =>  $dimensions[2],
              'weight' => $row['weight'],
              'description'=> $row['description']
          ]);

          $Gallery =  Gallery::create([
                     'path' => $row['product_image1'] ? $row['product_image1'] : '',
              ]); 
               
          $Product_meta = Product_meta::create([
            'Product_id' => $Product->id,
            'tax' =>  0,
            'manage_stock' => 1,
            'categories'=>  $getStringValue,
            'stock_quantity' =>  $row['stock_quantity'],
            'images' => $Gallery->id,
            'image2' => $row['product_image2'] ? $row['product_image2'] : '',
            'image3' => $row['product_image3'] ? $row['product_image3'] : '',
            'video'=>$row['video'] ? $row['video'] : ''
          // 'upc_code' => $row['upc_code'],
          //  'product_location'=> $row['product_location'],
          //  'bin_no'=> $row['bin_no'],
          // 'tax'=> $row['tax']
         ]); 
                  //  }
              
                    
                    
         
    }
    
    // public function model(array $row)
    // {

       
    //     HeadingRowFormatter::default('none');
    //     $company_id = Auth::user()->company_id;  
    //     $dimensions = explode("x",$row['dimensions'])   ;
    //     $Product = Product::create([
    //         'company_id'=>$company_id,
    //           'title' => $row['product_name'],
    //           'slug' => $row['sku_code'],
    //           'product_type' => 'simple',
    //           'status' => $row['stock_quantity'] ? 1 : 0,
    //           'sku' => $row['sku_code'],
    //           'price'=>$row['price'],
    //           'length' =>  $dimensions[0],
    //           'width' =>   $dimensions[1],
    //           'height' =>  $dimensions[2],
    //           'weight' => $row['weight'],
    //       ]);

    //       $Product_meta = Product_meta::create([
    //         'Product_id' => $Product->id,
    //         'tax' =>  0,
    //         'manage_stock' => 1,
    //         'categories'=> $row['category'],
    //         'stock_quantity' =>  $row['stock_quantity'],
    //      ]); 
        

    // }


   public function headingRow(): int
    {
        return 1;
       /// die;
    }
    public function sheets(): array
    {
        return [
            // Select by sheet index
            0 => new ImportProduct(),
        ];
      //  die;
    }

     public function rules(): array
    {
        // return [            
        //     'company_id'                  => 'required',
        //     'product_name'                  => 'required',
        //     'sku_code'                      => 'required',
        //     'weight'                        => 'required|numeric',
        //     'dimensions'                    => 'required',
        //     'category'                      => 'required',
        //     'price'                         => 'required',
        // ];

      return [            
              // 'product_name' => 'required',
             //  'sku' => 'required',
             //  'stock_quantity' => 'required',
             //  'price' => 'required',
             
          ];
    }

}
