<?php
session_start();
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)
	{
		$this->dbh = $this->connectPDO1();
		$this->dbh->beginTransaction();
        try
        {
        	foreach($products AS $product)
        	{
            $productArray = $product;
            $images = array();
            if(isset($productArray['images']))
            {
              $images = $productArray['images'];
              unset($productArray['images']);
            }

        		$productID = $this->insert1($this->dbh, 'tb_product', $productArray);
	        	if(!$productID)
    				{
    					$this->dbh->rollback();
    					return 0;
    					exit;
    				}
            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->insert1($this->dbh, 'tb_files', $imageArray);
              if(!$imageID)
              {
                $this->dbh->rollback();
                return 0;
                exit;
              }
            }

        	}

        	$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, "\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]);
    	exit;
    }
    else
    {
    	$res = $obj->insertData($data, $_SESSION['id']);
    	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;
    }
  }
}
