<?php

//header('Content-Type: text/html; charset=utf-8');

ini_set("log_errors", 1);
ini_set("error_log", "/home/effxgroup/public_html/acpew11.axo.lv/ACP_new/ajax/cron/execute/error_cron.log");
error_log( "Hello, errors!" );
include_once "../../../config.php";
include_once "../../../database1.php";


error_reporting(E_ALL);
ini_set('display_errors', 1);

ini_set('memory_limit', '2048M');

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

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 checkSlug($slug, $id)
	{
    $where[0]['cl_id']['operator'] = '!=';
    $where[0]['cl_id']['value'] = $id;

    $where[1]['cl_slug']['operator'] = '=';
    $where[1]['cl_slug']['value'] = $slug;

		return $this->fetchRow('tb_product', $where);
	}

	public function updateData($products)
	{
		//$this->dbh = $this->connectPDO1();
		//$this->dbh->beginTransaction();
   //     try
     //   {
          $count  = 1;
          $totalCount = 1;
          $currentDateTime = date('Y-m-d H:i:s');
          
          $supplierHTML = '';
          $itemNumberHTML = '';
          $stockHtml = '  cl_stock= CASE ';
          $supplierPriceHTML = '  cl_supplier_price= CASE ';
          $profitPercentageHTML = '  cl_profit_percentage= CASE ';
          $monthlyPriceHTML = '  cl_monthly_price= CASE ';

          $whereMultipleStock = [];
          $whereMultipleSupplier = [];
          $whereMultipleProfitPercentage = [];
          $whereMultipleMonthlyPrice = [];
          $whereMultiple = [];
          
          $lastWhereString = '';

            foreach($products AS $product)
            {

                if($count == 600)
                {
                  
                   $lastWhereString = rtrim($lastWhereString, 'OR'); 

                    $sql = ' UPDATE tb_product SET ' . $stockHtml . ' ELSE cl_stock END, ' . $supplierPriceHTML . ' ELSE cl_supplier_price END, ' . $profitPercentageHTML . ' ELSE cl_profit_percentage END, ' . $monthlyPriceHTML . ' ELSE cl_monthly_price END WHERE ' . $lastWhereString . ' LIMIT 10000';


                  $whereMultiple = array_merge($whereMultipleStock,$whereMultipleSupplier, $whereMultipleProfitPercentage, $whereMultipleMonthlyPrice);
                    
                    
                  $updateCount = $this->callQueryUpdate($sql, $whereMultiple);
                

                  $count = 0;
                  $stockHtml = '  cl_stock= CASE ';
                  $supplierPriceHTML = '  cl_supplier_price= CASE ';
                  $profitPercentageHTML = '  cl_profit_percentage= CASE ';
                  $monthlyPriceHTML = '  cl_monthly_price= CASE ';
                  $whereMultipleStock = [];
                  $whereMultipleSupplier = [];
                  $whereMultipleProfitPercentage = [];
                  $whereMultipleMonthlyPrice = [];
                  $whereMultiple = [];
                  
                    $lastWhereString = '';

                }
                $productArray = $product;
                $productArray['cl_last_price_updated'] = $currentDateTime;
                $productArray['cl_active'] = 1;


                $stockHtml.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereMultipleStock[] = $productArray['cl_supplier'];
                $whereMultipleStock[] = $productArray['cl_product_id'];
                $whereMultipleStock[] = $productArray['cl_stock'];

                $supplierPriceHTML.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereMultipleSupplier[] = $productArray['cl_supplier'];
                $whereMultipleSupplier[] = $productArray['cl_product_id'];
                $whereMultipleSupplier[] = $productArray['cl_supplier_price'];

                $profitPercentageHTML.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereMultipleProfitPercentage[] = $productArray['cl_supplier'];
                $whereMultipleProfitPercentage[] = $productArray['cl_product_id'];
                $whereMultipleProfitPercentage[] = $productArray['cl_profit_percentage'];

                $monthlyPriceHTML.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereMultipleMonthlyPrice[] = $productArray['cl_supplier'];
                $whereMultipleMonthlyPrice[] = $productArray['cl_product_id'];
                $whereMultipleMonthlyPrice[] = $productArray['cl_monthly_price'];

                $supplier = $where['cl_supplier'] = $productArray['cl_supplier'];
                $where['cl_product_id'] = $productArray['cl_product_id'];

                unset($productArray['cl_supplier']);
                unset($productArray['cl_product_id']);
                
                
                $lastWhereString.= ' cl_product_id="' . $where['cl_product_id'] . '" OR';

                    //	$productID = $this->update('tb_product', $productArray, $where);


                $fp = fopen('check.txt', 'a');
                //opens file in append mode  
                fwrite($fp, 'Updated ' . $totalCount . ' Products on ' . date('d M Y H:i:s') . ' - ' . $supplier . '<br/>');  
                fclose($fp); 

                $count++;
                $totalCount++;
            }

            $sql = ' UPDATE tb_product SET ' . $stockHtml . ' ELSE cl_stock END, ' . $supplierPriceHTML . ' ELSE cl_supplier_price END, ' . $profitPercentageHTML . ' ELSE cl_profit_percentage END, ' . $monthlyPriceHTML . ' ELSE cl_monthly_price END WHERE ' . $lastWhereString . ' LIMIT 10000';

            $whereMultiple = array_merge($whereMultipleStock,$whereMultipleSupplier, $whereMultipleProfitPercentage, $whereMultipleMonthlyPrice);

          //  $updateCount = $this->callQueryUpdate($sql, $whereMultiple);


            


         /* UPDATE table1 SET val1= CASE  
                           WHEN campid = 259 AND date = 22/6/2011 THEN 200
                            WHEN campid = 259 AND date = 21/6/2011 THEN 210
                          ELSE val1
                        END, 
                 val2= CASE id 
                          WHEN campid = 259 AND date = 22/6/2011 THEN 200
                            WHEN campid = 259 AND date = 21/6/2011 THEN 210
                          ELSE val2 
                        END
             WHERE id IN (1, 2, 3, 4); */

        	/*$this->dbh->commit();
    			return 1;
    			exit;*/

       // }
       // catch (PDOException $e) {
            // roll back transaction
       /*     $this->dbh->rollback();
            return 0;
        }*/

        return 1;
	}

  public function getCurrentCSV($id)
  {
    return $this->fetchRow('tb_cron', ['cl_id' => $id]);
  }

  public function updateStarted($id)
  {
    return $this->update('tb_cron', ['cl_started' => date('Y-m-d H:i:s')], ['cl_id' => $id]);
  }

  public function updateEnded($id)
  {
    return $this->update('tb_cron', ['cl_ended' => date('Y-m-d H:i:s')], ['cl_id' => $id]);
  }

  public function updateError($id, $error)
  {
    return $this->update('tb_cron', ['cl_error_message' => $error], ['cl_id' => $id]);
  }
}

if(!isset($_GET['id']) || !is_numeric($_GET['id']))
{
  exit;
}
$id = $_GET['id'];

$obj = new uploadProductCSV();
$cron = $obj->getCurrentCSV($id);
if(!$cron)
{
  exit;
}


$obj->updateStarted($cron['cl_id']);

	
	$fileError = '';
	$count = 0;
     $tmpName = $cron['cl_file'];
  
  $row = 1;
  $data = array();
  
 
  if (($handle = fopen($tmpName, "r")) !== FALSE) {
    
    while (($Row = fgetcsv($handle, 1000, ",")) !== FALSE) {
    		//$Row = array_map("utf8_encode", $Row); //added

  		$categoryID = 0;

      $supplier = '';
      if(!isset($Row[0]) || trim($Row[0]) == '')
      {
        $fileError.= 'Supplier is missing at ' . ($count + 1) . ' row<br/>';
      }
        $data[$count]['cl_supplier'] = trim($Row[0]);
      

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

      $stock = "";
      if(isset($Row[2]) && trim($Row[2]) != '') {
         if(!is_numeric(trim($Row[2])))
        {
          $fileError.= 'Stock should be numeric for ' . ($count + 1) . ' row<br/>';
        }
        else if(trim($Row[2]) > 0)
        {
          $data[$count]['cl_stock'] = 1;
        }
        else if(trim($Row[2]) == 0)
        {
          $data[$count]['cl_stock'] = 0;
        }
      }
      else
      {
        $fileError.= 'Stock is missing for ' . ($count + 1) . ' row<br/>';
      }

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

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

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

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


       $count++;
    }

    fclose($handle);

   }
  

    if($fileError != '')
    {
      $obj->updateError($cron['cl_id'], $fileError);
    	http_response_code(400);
    	echo json_encode(['error_text' => $fileError]);
    	exit;
    }
    else
    {
    	$res = $obj->updateData($data);
    	if(!$res)
    	{
    		http_response_code(500);
	    	echo json_encode(['error_text' => 'Something Went Wrong']);
	    	exit;
    	}


      $obj->updateEnded($cron['cl_id']);
    	http_response_code(200);
	    	echo json_encode(['message' => 'File Updated Successfully']);
	    	exit;
    }

  
  