<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\CustomProduct;
use Session;
use DB;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class CustomProductController extends Controller {

    public function index() {
        $products = CustomProduct::where(['isDeleted' => 0])->get();
        return view('custom_products.list', compact('products'));
    }

    public function create() {
        return view('custom_products.add');
    }

    public function store(Request $request) {
        try {
            $tot = count($request->name) - 1;
            for ($i = 0; $i < $tot; $i++) {
                $customProducts = new CustomProduct();
                $customProducts->name = $request->name[$i];
                $customProducts->sku = $request->sku[$i];
                $customProducts->save();
            }
            Session::put('successMsg', 'Custom Product Added!');
        } catch (Exception $ex) {
            Session::put('errorMsg', 'Something went wrong!');
        }
        return redirect()->route('custom_products');
    }

    public function destroy(Request $request) {
        try {
            $product = CustomProduct::find($request->id);
            $product->isDeleted = 1;
            $product->save();
            $message = 'Product deleted !';
            $status = true;
        } catch (Exception $ex) {
            $message = "Something went wrong!";
            $status = false;
        }
        return response()->json([
                    'status' => $status,
                    'message' => $message
        ]);
    }

    public function isExistProduct(Request $request,$form_type="normal",$data_type = null ,$data_info = null) {
        if($form_type == "ajax"){
            $dataType = $data_type;
            $dataInfo = $data_info;
            }else{
                $dataType = $request->data_type;
                $dataInfo = $request->data_info;
            }
        $isProduct = CustomProduct::where($dataType, '=', $dataInfo)->first();

        if (count($isProduct)) {
            $isValid = false;
            $message = ucfirst($request->data_type) . ' already exists!';
        } else {
            $isValid = true;
            $message = "";
        }
        if($form_type == "ajax"){
            return $isValid;
        }else{
        return response()->json([
                    'isValid' => $isValid,
                    'message' => $message
        ]);
        }
            
    }

    public function importFile(Request $request){
             return view('custom_products.import_from_file');
   
    }
    public function saveImportFileAndData(Request $request){
    $return_data = NULL;
     if($request->hasFile('file_import')) {
                $file = $request->file('file_import');
                $name =$file->getClientOriginalName();
                $file->move('uploads', $name);
                $path = 'uploads/'.$name;
                $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($path);
                /**  Create a new Reader of the type that has been identified  **/
                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
                // /**  Load $inputFileName to a Spreadsheet Object  **/
                $spreadsheet = $reader->load($path);
                /**  Convert Spreadsheet Object to an Array for ease of use  **/
                $data = $spreadsheet->getActiveSheet()->toArray();
                 if($data)
                 {
                  foreach($data as $key =>$value)
                  {
                     $insert_data[] = array(
                     'product'  => $value[0],
                     'sku'   => $value[1],
                     'stock'   => $value[2],
                    );
                  }
                  if(!empty($insert_data))
                  {
                       for ($i = 1; $i < count($insert_data); $i++) {
                            $notValidName =$this->isExistProduct($request,"ajax","name",$insert_data[$i]['product']);
                                $notValidSku =$this->isExistProduct($request,"ajax","sku",$insert_data[$i]['sku']);
                               if($notValidName && $notValidSku){
                                    $customProducts = new CustomProduct();
                                    $customProducts->name = $insert_data[$i]['product'];
                                    $customProducts->sku = $insert_data[$i]['sku'];
                                    $customProducts->qty = $insert_data[$i]['stock'];
                                    $customProducts->save();
                               }else{
                                   $return_data[] = array(
                                 'product'  => $insert_data[$i]['product'],
                                 'sku'   => $insert_data[$i]['sku'],
                                 'stock'   => $insert_data[$i]['stock'],
                                );
                               }
                        }
                        
                  }
     }

    if(count($return_data)){
        return response()->json([
                    'isValid' => 0,
                    'message' => "Some of your data is already exist that are not uploaded! check the list!",
                    'returnData'=> $return_data
        ]);
    }else{
        return response()->json([
                    'isValid' => 1,
                    'message' => "Data uploaded!!",
                    'returnData'=>  NULL
        ]);
    }
        

    }
    else{
         return response()->json([
                    'isValid' => 0,
                    'message' => "File not uploaded!!",
                    'returnData'=> NULL
        ]);
    }
    }
}
