<?php

ini_set('memory_limit', '2048M');
header('Content-Type: text/html; charset=utf-8');
include_once "../../config.php";
include_once "../database1.php";
include_once "../../validation.php";
include_once "../../Helper.php";

class uploadProductCSV extends database{
    public function checkCategoryByName($name)
	{
		return $this->fetchRow('tb_product_category', ['cl_name' => $name]);
	}

	public function checkSubCategoryByName($name, $categoryID)
	{
		return $this->fetchRow('tb_product_subcategory', ['cl_name' => $name, 'cl_cat_id' => $categoryID]);
	}

	public function checkBrand($name)
	{
		return $this->fetchRow('tb_brands', ['cl_name' => $name]);
	}

  public function insertBrand($brand)
  {
    return $this->insert('tb_brands', ['cl_name' => $brand]);
  }

	public function checkSlug($slug)
	{
		return $this->fetchRow('tb_product', ['cl_slug' => $slug]);
	}

	public function insertData($products, $userID)
	{
            foreach($products AS $product)
            {
                $productArray = $product;
                $images = array();
                if(isset($productArray['images']))
                {
                  $images = $productArray['images'];
                  unset($productArray['images']);
                }

                $productID = $this->insert('tb_product', $productArray);
                
                
                foreach($images AS $image)
                {
                    $imageArray['cl_type'] = 'Product';
                    $imageArray['cl_product_id'] = $productID;
                    $imageArray['cl_actual_name'] = null;
                    $imageArray['cl_name'] = $image;
                    $imageArray['cl_extension'] = null;
                    $imageArray['cl_user_id'] = $userID;
                    $imageID = $this->insert('tb_files', $imageArray);
                    
                }
                
                $fp = fopen('upload_product_csv_static.txt', 'a');
                    //opens file in append mode  
                    fwrite($fp, 'Inserted <br/>' . $productArray['cl_product_id']);  
                    fclose($fp); 
            }
            
            
            return 1;
            
            
            /*$count  = 0;
            $currentDateTime = date('Y-m-d H:i:s');

            $insertHTML = '';
            $where = [];

            $bulkCount = 1;


            foreach($products AS $product)
            {

                if($count == 500)
                {

                      $sql = 'INSERT INTO tb_product (cl_cat_id, cl_sub_cat_id, cl_brand_id, cl_name, cl_slug, cl_regular_price, cl_sale_price,cl_supplier,cl_product_id,cl_stock,cl_ean, cl_x, cl_y, cl_z, cl_weight,cl_last_price_updated, cl_manufacturer, cl_created_at, cl_updated_at)
    VALUES ' . $insertHTML;

                    $this->callQueryInsert($sql, $where);

                     $fp = fopen('upload_product_csv_static.txt', 'a');
                    //opens file in append mode  
                    fwrite($fp, 'Inserted ' . $bulkCount * 500 . ' Products<br/>');  
                    fclose($fp); 


                    $bulkCount++;


                    $count = 0;
                    $insertHTML = '';
                    $where = [];


                }

                $productArray = $product;

                if($count > 0)
                {
                    $insertHTML.= ',';
                }
                $insertHTML.= '(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';

                foreach($product AS $each)
                {
                    $where[] = $each;
                }


                $count++;
            }

               $sql = 'INSERT INTO tb_product (cl_cat_id, cl_sub_cat_id, cl_brand_id, cl_name, cl_slug, cl_small_specification, cl_big_specification, cl_description, cl_regular_price, cl_sale_price,cl_monthly_price, cl_recommended, cl_featured, cl_image, cl_supplier,cl_product_id,cl_stock,cl_ean, cl_x, cl_y, cl_z, cl_weight,cl_last_price_updated, cl_manufacturer, cl_created_at, cl_updated_at)
    VALUES ' . $insertHTML;
            //  $whereMultiple = array_merge($whereMultipleStock,$whereMultipleSupplier, $whereMultipleProfitPercentage, $whereMultipleMonthlyPrice);

             $this->callQueryInsert($sql, $where);

             $fp = fopen('action_insert_product_text.txt', 'a');
                    //opens file in append mode  
                    fwrite($fp, 'Inserted All<br/>');  
                    fclose($fp); 

            return 1; */
	}
}


$fp = fopen('upload_product_csv_static.txt', 'w');
                    //opens file in append mode  
                    fwrite($fp, '');  
                    fclose($fp); 

$obj = new uploadProductCSV();
	$fileError = '';
	$count = 0;
    $tmpName = 'm1.csv';
  $row = 1;
  $data = array();
  if (($handle = fopen($tmpName, "r")) !== FALSE) {
    while (($Row = fgetcsv($handle, 5000, "\t")) !== FALSE) {
    		//$Row = array_map("utf8_encode", $Row); //added

  		$categoryID = 0;

      if(isset($Row[0]) && trim($Row[0]) != '') {
           $category =  trim($Row[0]);

          $res = $obj->checkCategoryByName($category);

          if(!$res)
          {
          	$fileError.= 'Category not found in database for ' . ($count + 1) . ' row<br/>';
          }
          else
          {
          	$categoryID = $data[$count]['cl_cat_id'] = $res['cl_id'];
          }
      }
      else
      {
      	$fileError.= 'Category is missing for ' . ($count + 1) . ' row<br/>';
      }

      if(isset($Row[1]) && trim($Row[1]) != '') {
           $subCategory = trim($Row[1]);

          $res = $obj->checkSubCategoryByName($subCategory, $categoryID);
          if(!$res)
          {
          	$fileError.= 'Sub Category ' . $subCategory . ' not found (Category: '  . $categoryID . ') in database for ' . ($count + 1) . ' row / (Could cause also due to category not found in databse)<br/>';
          }
          else
          {
          	$data[$count]['cl_sub_cat_id'] = $res['cl_id'];
          }
      }
      else
      {
      	$fileError.= 'Sub Category is missing for ' . ($count + 1) . ' row<br/>';
      }

      $email = "";
      if(isset($Row[2]) && trim($Row[2]) != '') {
          $brand = trim($Row[2]);
          $res = $obj->checkBrand($brand);
          if(!$res)
          {
            $brandID = $obj->insertBrand($brand);
            $data[$count]['cl_brand_id'] = $brandID;
          	//$fileError.= 'Brand not found in database for ' . ($count + 1) . ' row<br/>';
          }
          else
          {
          	$data[$count]['cl_brand_id'] = $res['cl_id'];
          }
      }
      else
      {
      	$fileError.= 'Brand is missing for ' . ($count + 1) . ' row<br/>';
      }

      $phone = "";
      if(isset($Row[3]) && trim($Row[3]) != '') {
          $data[$count]['cl_name'] = trim($Row[3]);
      }
      else
      {
      	$fileError.= 'Name is missing for ' . ($count + 1) . ' row<br/>';
      }

      $title = "";
      if(isset($Row[4]) && trim($Row[4]) != '') {
          $data[$count]['cl_slug'] = trim($Row[4]);
          $res = $obj->checkSlug(trim($Row[4]));
          if($res)
          {
          	$fileError.= 'Slug in database for ' . ($count + 1) . ' row. Use an unique slug<br/>';
          }
      }
      else
      {
      	$fileError.= 'Slug is missing for ' . ($count + 1) . ' row<br/>';
      }


      if(isset($Row[5])) {
          $data[$count]['cl_small_specification'] = trim($Row[5]);
      }

      if(isset($Row[6])) {
          $data[$count]['cl_big_specification'] = trim($Row[6]);
      }

      if(isset($Row[7])) {
          $data[$count]['cl_description'] = trim($Row[7]);
      }

      if(isset($Row[8])) {
  		if(trim($Row[8]) == '' || !is_numeric(trim($Row[8])))
  		{
  			$data[$count]['cl_regular_price'] = 0.00;
  		}
  		else
  		{
          $data[$count]['cl_regular_price'] = trim($Row[8]);
  		}
      }

      if(isset($Row[9])) {
      	if(trim($Row[9]) == '' || !is_numeric(trim($Row[9])))
  		{
  			$fileError.= 'Sale Price is not numeric for ' . ($count + 1) . ' row<br/>';
  		}
          $data[$count]['cl_sale_price'] = trim($Row[9]);
      }
      else
      {
      	$fileError.= 'Sale Price is not numeric for ' . ($count + 1) . ' row<br/>';
      }

      if(isset($Row[10])) {

      	if(trim($Row[10]) == '' || !is_numeric(trim($Row[10])))
  		{
  			$fileError.= 'Monthly Price is not numeric for ' . ($count + 1) . ' row<br/>';
  		}
          $data[$count]['cl_monthly_price'] = trim($Row[10]);
      }
      else
      {
      	$fileError.= 'Monthly Price is not numeric for ' . ($count + 1) . ' row<br/>';
      }

      if(isset($Row[11])) {

      		if(trim($Row[11]) != '0' && trim($Row[11]) != '1')
	  		{
	  			$fileError.= 'Recommeneded should be 0 or 1 for ' . ($count + 1) . ' row<br/>';
	  		}
          $data[$count]['cl_recommended'] = trim($Row[11]);
      }

      if(isset($Row[12])) {
      	if(trim($Row[12]) != '0' && trim($Row[12]) != '1')
	  		{
	  			$fileError.= 'Featured should be 0 or 1 for ' . ($count + 1) . ' row<br/>';
	  		}
          $data[$count]['cl_featured'] = trim($Row[12]);
      }

      if(isset($Row[13])) {

          $data[$count]['cl_image'] = trim($Row[13]);
      }

      $fileCount = 0;
      for($i = 13; $i<= 17; $i++)
      {
          if(isset($Row[$i])) {
            if(trim($Row[$i]) != '')
            {
              $data[$count]['images'][$fileCount] = trim($Row[$i]);
              $fileCount++;
            }

          }

      }

      if(isset($Row[18])) {
        if(trim($Row[18]) != '0' && trim($Row[18]) != '1')
        {
          $fileError.= 'Recent should be 0 or 1 for ' . ($count + 1) . ' row<br/>';
        }
          $data[$count]['cl_recent'] = trim($Row[18]);
      }

      if(isset($Row[19]) && trim($Row[19]) != '') {
          $data[$count]['cl_meta_description'] = trim($Row[19]);
      }
      
      if(isset($Row[20]) && trim($Row[20]) != '') {
          $data[$count]['cl_keywords'] = trim($Row[20]);
      }


      if(isset($Row[21])) {
        if(trim($Row[21]) != '0' && trim($Row[21]) != '1')
        {
          $fileError.= 'Active should be 0 or 1 for ' . ($count + 1) . ' row<br/>';
        }
        $data[$count]['cl_active'] = trim($Row[21]);
      }

      if(isset($Row[22])) {
          $data[$count]['cl_supplier'] = trim($Row[22]);
      }

      if(isset($Row[23])) {
          $data[$count]['cl_product_id'] = trim($Row[23]);
      }

       if(isset($Row[24])) {
          $data[$count]['cl_stock'] = trim($Row[24]);
      }

        if(isset($Row[25])) {
          $data[$count]['cl_supplier_price'] = trim($Row[25]);
      }

       if(isset($Row[26])) {
          $data[$count]['cl_profit_percentage'] = trim($Row[26]);
      }


       if(isset($Row[27])) {
          $data[$count]['cl_ean'] = trim($Row[27]);
      }


      $count++;

    }

    fclose($handle);


    if($fileError != '')
    {
    	http_response_code(400);
    	echo json_encode(['error_text' => $fileError]);
        
        $fp = fopen('upload_product_csv_static.txt', 'a');
                    //opens file in append mode  
                    fwrite($fp, json_encode($fileError));  
                    fclose($fp); 
    	exit;
    }
    else
    {
    	$res = $obj->insertData($data, 1);
    	if(!$res)
    	{
    		http_response_code(500);
	    	echo json_encode(['error_text' => 'Something Went Wrong']);
                $fp = fopen('upload_product_csv_static.txt', 'a');
                    //opens file in append mode  
                    fwrite($fp, 'Something Went Wrong');  
                    fclose($fp); 
    
	    	exit;
    	}

    	http_response_code(200);
	    	echo json_encode(['message' => 'File Updated Successfully']);
                
                $fp = fopen('upload_product_csv_static.txt', 'a');
                    //opens file in append mode  
                    fwrite($fp, 'File Updated Successfully');  
                    fclose($fp); 
    
	    	exit;
	    	exit;
    }
  }

