<?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";
//require_once "../check_admin.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, $userID)
	{
		$this->dbh = $this->connectPDO1();
		$this->dbh->beginTransaction();
        try
        {
        	foreach($products AS $product)
        	{
            $productArray = $product;
            $where['cl_id'] = $productArray['cl_id'];
            unset($productArray['cl_id']);

        		$productID = $this->update1('tb_product', $productArray, $where);
	        	if(!$productID)
    				{
    					$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, ",")) !== FALSE) {
    		//$Row = array_map("utf8_encode", $Row); //added

  		$categoryID = 0;

      $productID = '';
      if(!isset($Row[0]) || trim($Row[0]) == '' || !is_numeric(trim($Row[0])))
      {
        $fileError.= 'Product ID is missing at ' . ($count + 1) . ' row<br/>';
      }
        $data[$count]['cl_id'] = trim($Row[0]);
      

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

      $title = "";
      if(isset($Row[2]) && trim($Row[2]) != '') {
          $data[$count]['cl_slug'] = trim($Row[2]);
          if(trim($fileError) == '')
          {
            $res = $obj->checkSlug(trim($Row[2]), trim($Row[0]));
            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[3])) {
          $data[$count]['cl_small_specification'] = trim($Row[3]);
      }

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

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

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

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

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

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

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

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

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

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

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

      if(isset($Row[14]) && trim($Row[14]) != '') {
          $data[$count]['cl_image'] = trim($Row[14]);
      }

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

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

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

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

      $count++;
    }

    fclose($handle);


    if($fileError != '')
    {
    	http_response_code(400);
    	echo json_encode(['error_text' => $fileError]);
    	exit;
    }
    else
    {
    	$res = $obj->updateData($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;
    }
  }
}
