<?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";

include_once "../../ichat/admin/route.php";
if ($session->is_logged_in() != true ) {
        redirect_to(WEB_LINK.'/login');
} else {
    $current_user = User::get_specific_id($session->admin_id);
    $current_user->set_online();
    $group = $current_user->prvlg_group;
}


require_once("../../ichat/admin/assets/includes/Library/SessManager.php");
require_once("../../ichat/admin/assets/includes/Library/User.php");
$session = new  SessManager();

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_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;
    				}
        	}

        	$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/>';
      }

     

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

     


      $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;
    }
  }
}
