<?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;
} */


if(!isset($_GET['start']))
{
    die("Page Not Found");
}

$start = $_GET['start'];

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



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

   public function updateDimentions($products, $totalCount)
    {
        $count  = 0;
        $currentDateTime = date('Y-m-d H:i:s');
        
        $insertHTML = '';
        $where = [];
        
        $bulkCount = 1;
        
        $xHtml = '  cl_x= CASE ';
        $yHtml = '  cl_y= CASE ';
        $zHtml = '  cl_z= CASE ';
        
        $whereX = [];
          $whereY = [];
          $whereZ = [];
          

        foreach($products AS $product)
        {
            
                 $xHtml.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereX[] = 'abpl';
                $whereX[] = $product['cl_product_id'];
                $whereX[] = $product['cl_x'];
                
                 $yHtml.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereY[] = 'abpl';
                $whereY[] = $product['cl_product_id'];
                $whereY[] = $product['cl_y'];
                
                 $zHtml.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereZ[] = 'abpl';
                $whereZ[] = $product['cl_product_id'];
                $whereZ[] = $product['cl_z'];
                
               
                
            }
            
            $whereMultiple = array_merge($whereX,$whereY, $whereZ);
          
           $sql = ' UPDATE tb_product SET ' . $xHtml . ' ELSE cl_x END, ' . $yHtml . ' ELSE cl_y END, ' . $zHtml . ' ELSE cl_z END ';
         
                $this->callQueryUpdate($sql, $whereMultiple);
                
                 $fp = fopen('abpl_single_product_update.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'));
           $products = $obj->getAllAbplProducts();
           
           $count = 1;
           $itemCount = 0;

           ?>
           <table style="width:100%" border="1">
               <?php
               $dataUpdate = [];
               
               foreach($products AS $each)
               {
                   $productID = $each['cl_product_id'];
                   if($count >= $start)
                   {
                    ?>
                    <tr>
                       <?php
                       

                        if(trim($productID) != '')
                        {
                            
                            
                                            $data  = array('client'             => '00139726', 
                                                'login'             => 'samanta', 
                                                'pass'              => 'n3PPXWDp8Dg', 
                                                'req'               => 'product', 
                                              //  'pid'               => 'UKMIC290015;AKASS113043;KOTRAZT9008;121650;121974', 
                                                'pid'          => $productID,
                                                'withdesc'  => 1
                                                );

                                                // wykonujemy request
                                                $url        = 'https://xml.ab.pl/gateway.php';
                                                $curl       = curl_init();
                                                curl_setopt($curl, CURLOPT_URL, $url);
                                                curl_setopt($curl, CURLOPT_POST, true);
                                                curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                                                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                                                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                                                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
                                                $result     = curl_exec($curl);
                                                $err        = curl_error($curl);
                                                $errno      = intval(curl_errno($curl));
                                                curl_close($curl);
                                                
                                                //var_dump($err, $errno);
                                                
                                               
                                                // sprawdzamy odpowiedz
                                                if(!$err) 
                                                {
                                                    $ob = simplexml_load_string($result);
                                                     
                                                    if((string) $ob->product->dimentions->instock != 0)
                                                    {
                                                        print_r($result);
                                                        exit;
                                                    }
                                                    if((string) $ob->product->dimentions->height != '' 
                                                             && (string)$ob->product->dimentions->width != '' 
                                                             && (string) $ob->product->dimentions->depth != '')
                                                    {
                                                     
                                                        $dataUpdate[$itemCount]['cl_x'] = (string) $ob->product->dimentions->height;
                                                        $dataUpdate[$itemCount]['cl_y'] = (string)$ob->product->dimentions->width;
                                                        $dataUpdate[$itemCount]['cl_z'] = (string) $ob->product->dimentions->depth;

                                                        $dataUpdate[$itemCount]['cl_product_id'] = $productID;
                                                        $dataUpdate[$itemCount]['cl_supplier'] = 'abpl';
                                                        
                                                       


                                                        if($itemCount == 250)
                                                       {
                                                           $obj->updateDimentions($dataUpdate, $count);
                                                           $dataUpdate = [];
                                                            $itemCount = 0;
                                                       }
                                                    }
                                                   
                                                } else {
                                                    // problem CURLa z wykonaniem requestu
                                                    var_dump($err, $errno);
                                                }
                                                
                                                
                                            
                                    }
                                    else
                                    {
                                         ?>
                                            <td>
                                                Product ID is empty
                                            </td>
                                            <?php
                                    }
                
                     ?>
                    </tr>
                    <?php
                   }
                    $count++;
                    $itemCount++;
                    //$totalCount++;
                    
                }
               // $obj->updateDimentions($dataUpdate, $count);
                 
                ?>
               
           </table>
           <?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>