<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '2048M');

include_once "../config.php";
include_once "../database1.php";

class productCategoryUpdate extends database
{
    public function updateData($data, $totalCount)
    {
        echo $totalCount;
        
        
        $categoryHTML = '  cl_cat_id= CASE ';
        $subCategoryHTML = '  cl_sub_cat_id= CASE ';
        
        $whereCategoryHTML = [];
        $whereSubCategoryHTML = [];
        
        foreach($data AS $product)
        {
                $categoryHTML.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereCategoryHTML[] = $product['cl_supplier'];
                $whereCategoryHTML[] = $product['cl_product_id'];
                $whereCategoryHTML[] = $product['cl_cat_id'];
                
                $subCategoryHTML.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereSubCategoryHTML[] = $product['cl_supplier'];
                $whereSubCategoryHTML[] = $product['cl_product_id'];
                $whereSubCategoryHTML[] = $product['cl_sub_cat_id'];
        }
        
            
            $whereMultiple = array_merge($whereCategoryHTML,$whereSubCategoryHTML);
            
              $sql = ' UPDATE tb_product SET ' . $categoryHTML . ' ELSE cl_cat_id END, ' . $subCategoryHTML . ' ELSE cl_sub_cat_id END ';

            
                $this->callQueryUpdate($sql, $whereMultiple);
                
                 $fp = fopen('abpl_product_category_update_text.txt', 'a');
                //opens file in append mode  
                fwrite($fp, 'Inserted ' . $totalCount . ' Products<br/>');  
                fclose($fp); 
            
           

           
        


        return 1;
    }
}

$row = 1;
$itemCount = 1;
 $dataInsert = [];

$obj = new productCategoryUpdate();
if (($handle = fopen("csv/abplcategor.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    
      
   
    
    $dataInsert[$row]['cl_cat_id'] = $data[2];
    $dataInsert[$row]['cl_sub_cat_id'] = $data[3];
    $dataInsert[$row]['cl_product_id'] = $data[1];
    $dataInsert[$row]['cl_supplier'] = $data[0];
    
    
    if($itemCount == 250)
    {
        $obj->updateData($dataInsert, $row);
        $itemCount = 0;
    }
        
    $itemCount++;
    $row++;
  }
  fclose($handle);
}

$obj->updateData($dataInsert, $row);