<?php

session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once "../config.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;
} */



$updatedCount = 0;
if(isset($_GET['updated']))
{
    $updatedCount = $_GET['updated'];
}



//require_once "check_admin.php";
include_once "../database1.php";
class Upload extends database
{
   

   public function updateSpecificationsBulk($products, $totalCount)
    {
        $count  = 0;
        $currentDateTime = date('Y-m-d H:i:s');
        
        $insertHTML = '';
        $where = [];
        
        $bulkCount = 1;
        
        $smallSpecificationHtml = '  cl_small_specification= CASE ';
        $bigSpecificationHtml = '  cl_big_specification= CASE ';
        $bigSpecificationEnglishHtml = '  cl_big_specification_english= CASE ';
        
        $whereMultipleSmallSpecification = [];
          $whereMultipleBigSpecification = [];
          $whereMultipleBigSpecificationEnglish = [];
          

        foreach($products AS $product)
        {
            
                $smallSpecificationHtml.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereMultipleSmallSpecification[] = 'abpl';
                $whereMultipleSmallSpecification[] = $product['cl_product_id'];
                $whereMultipleSmallSpecification[] = $product['cl_small_specification'];
                
                $bigSpecificationHtml.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereMultipleBigSpecification[] = 'abpl';
                $whereMultipleBigSpecification[] = $product['cl_product_id'];
                $whereMultipleBigSpecification[] = $product['cl_big_specification'];
                
                $bigSpecificationEnglishHtml.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereMultipleBigSpecificationEnglish[] = 'abpl';
                $whereMultipleBigSpecificationEnglish[] = $product['cl_product_id'];
                $whereMultipleBigSpecificationEnglish[] = $product['cl_big_specification'];
                
                
                

                
            }
            
            $whereMultiple = array_merge($whereMultipleSmallSpecification,$whereMultipleBigSpecification, $whereMultipleBigSpecificationEnglish);
            
             $sql = ' UPDATE tb_product SET ' . $smallSpecificationHtml . ' ELSE cl_small_specification END, ' . $bigSpecificationHtml . ' ELSE cl_big_specification END, ' . $bigSpecificationEnglishHtml . ' ELSE cl_big_specification_english END ';

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

           
        


        return 1;
    
    }
    
    public function getAllAbplProducts()
    {
        return $this->fetchAll('tb_product', ['cl_supplier' => 'abpl']);
    }
}

$obj = new Upload();


$productArray = array();
if(isset($_GET['message']))
{
	$msg=$_GET['message'];
}
	/*if(isset($_FILES['csv']['tmp_name']) && is_uploaded_file($_FILES['csv']['tmp_name']))
    {
        
        $target_dir = "uploads/cenas-category/";
        $randName = date('dmYhis') . rand(10000,99999) . basename($_FILES['csv']["name"]);
        $target_file = $target_dir . $randName;
        $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
        // Check if image file is a actual image or fake image

      

        // Check if file already exists
        if (file_exists($target_file)) {
            $msg.=  "Sorry, file already exists.";
            $uploadOk = 0;
        }
        // Check file size
        if ($_FILES['csv']["size"] > 500000000) {
            $msg.=  "Sorry, your file is too large.";
            $uploadOk = 0;
        }
        // Allow certain file formats
        if($imageFileType != "csv" ) {
            $msg.=  "Sorry, only CSV files are allowed.";
            $uploadOk = 0;
        }
        // Check if $uploadOk is set to 0 by an error
        if(trim($msg) == '')
        { */
         //  $csvAsArray = array_map('str_getcsv', file('582415_cennik_AB.csv'));
          
          $count1 = 0;
           $params2 = simplexml_load_file('params2.xml');
          
          $params2Array = [];
          
           foreach($params2->params2->param2 AS $param)
           {
                $arrayParam = (array)$param;   
                
               $params2Array[json_decode($param->id)]['id'] = json_decode($param->id);
               $params2Array[json_decode($param->id)]['name'] = $arrayParam['sysname'];
              
               $count3 = 0;
               
               if($param->enums2->enum)
               foreach($param->enums2->enum AS $enum)
               {
                   $arrayEnum = (array)$enum;   
                   $params2Array[json_decode($param->id)]['enum'][json_decode($enum->id)]['id'] = json_decode($enum->id);
                   $params2Array[json_decode($param->id)]['enum'][json_decode($enum->id)]['name'] = $arrayEnum['sysname'];
                    $count3++;
               }
             //  print_r($param);
              $count1++;
              
             // echo '<br/><br/><br/>';
              
           }
         
           
           $ob = simplexml_load_file('abpl_product_list.xml');
           
          
           ?>
          
               <?php
               $dataUpdate = [];
               $count = 0;
               $totalCount = 0;
               foreach($ob->products->product AS $key => $each)
               {
                   
                    
                   
                      
                   /*$productID = $each['cl_product_id'];
                   if($count >= $start)
                   { */
                    ?>
                  
                          <?php   $productID = json_decode($each->id) ?> 
                      
                          
                           <?php
                           $arrayParam = (array)$each->paramsvalues2;
                           
                           
                           
                           $insideCount = 1;
                           
                           if(isset($arrayParam['paramvalue2']))
                           {
                                $shortSpecification = '<table class="table short_description_table" border="0" cellpadding="1" cellspacing="1" style="width:100%">';
                                $bigSpecification = '<table class="table  big_description_table" border="0" cellpadding="1" cellspacing="1" style="width:100%">';
                               foreach($arrayParam['paramvalue2'] AS $param)
                               {
                                   
                                   $insideParamArray = (array)$param;
                                      if(isset($insideParamArray['prm']))
                                      {
                                       $id = $insideParamArray['prm'];
                                       if($params2Array[$id]['name'] != 'Opis')
                                        {
                                        
                                           if(isset($params2Array[$id]) && isset($insideParamArray['enum']) && isset($params2Array[$id]['enum']))
                                           {
                                               $enumID = $insideParamArray['enum'];
                                                 if(isset($params2Array[$id]['enum'][$enumID]))
                                                 {
                                                   
                                                   
                                                   if($insideCount <= 4)
                                                    {
                                                        $shortSpecification.= '<tr><th>' . $params2Array[$id]['name'] . '</th><td>' . $params2Array[$id]['enum'][$enumID]['name'] . '</td></tr>';
                                                        
                                                    }
                                                    $bigSpecification.= '<tr><th>' . $params2Array[$id]['name'] . '</th><td>' . $params2Array[$id]['enum'][$enumID]['name'] . '</td></tr>';
                                                    
                                                    $insideCount++;
                                                 }
                                               
                                           }
                                      }
                                      }
                                   
                                   
                                   
                               }
                               $shortSpecification.= '</table>';
                            $bigSpecification.= '</table>';
                           }
                           
                           
                            
                            
                            $dataUpdate[$count]['cl_product_id'] = $productID;
                            $dataUpdate[$count]['cl_small_specification'] = $shortSpecification;
                            $dataUpdate[$count]['cl_big_specification'] = $bigSpecification;
                            $dataUpdate[$count]['cl_big_specification_english'] = $bigSpecification;
                           
                           
                         
                          //print_r($each->paramsvalues2);
                          
                           ?>
                      
                    <?php
                    
                    
                    echo $productID;
                    if($count == 250)
                    {
                         $obj->updateSpecificationsBulk($dataUpdate, $totalCount);

                        $count = 0;
                    }
                   
                    
                   
                    $count++;
                     $totalCount++;
                    //$totalCount++;
                   
                    
                }
                //$obj->updateDimentions($dataUpdate, $count);
                 
                ?>
              
           <?php
          
          
       /* }
    }*/
  /* if($count < $start)
   {
    echo 'finished';
    echo '<br/>';
    echo $count;
    exit;
   }*/
?>


<script>
    //window.location.href = 'test_csv_insert?start=<?php echo ($start + 500) ?>&updated=<?php echo $updatedCount ?>';

    </script>