<?php

//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 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;
          $currentDateTime = date('Y-m-d H:i:s');
        	foreach($products AS $product)
        	{
            $productArray = $product;
            $productArray['cl_last_price_updated'] = $currentDateTime;
            $productArray['cl_active'] = 1;

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

            unset($productArray['cl_supplier']);
            unset($productArray['cl_product_id']);

        		$productID = $this->update1('tb_product', $productArray, $where);
	        	if(!$productID)
    				{
    					$this->dbh->rollback();
    					return 0;
    					exit;
    				}

            http_response_code(200);
           // echo json_encode(['message' => $count . ' column update - productID : ' . $where['cl_product_id']]);
            $count++;
        	}

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

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

if(!isset($_FILES["file"]["name"]))
{
	http_response_code(404);
	echo json_encode(array('error_text' => 'File Not Found'));
	exit;
}

$target_dir = "../product_category/uploads/files/";
$newName = rand(100000,999999) . '_' . date('dmyHis') . '_' . basename($_FILES["file"]["name"]);
$target_file = $target_dir . $newName;
$message = '';
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($target_file)) {
    $message.="Sorry, file already exists.";
}
// Check file size
if ($_FILES["file"]["size"] > 500000000) {
    $message.="Sorry, your file is too large.";
}
// Allow certain file formats
if($imageFileType != "csv") {
    $message.="Sorry, only CSV files are allowed.";
}
// Check if $uploadOk is set to 0 by an error
if (trim($message) != '') {
    http_response_code(400);
    echo json_encode(['error_text' => $message]);
    exit;
// if everything is ok, try to upload file
} else {
	$obj = new uploadProductCSV();
	$fileError = '';
	$count = 0;
    $tmpName = $_FILES['file']['tmp_name'];
  $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 != '')
    {
    	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;
    	}

    	http_response_code(200);
	    	echo json_encode(['message' => 'File Updated Successfully']);
	    	exit;
    }
  }
}
