<?php

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

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




class Insert extends database
{
    /*public function updateBulk($products)
    {
        $count  = 0;
        $currentDateTime = date('Y-m-d H:i:s');
        
        $insertHTML = '';
        $where = [];
        
        $bulkCount = 1;
          

        foreach($products AS $product)
        {

            if($count == 500)
            {

                  $sql = 'INSERT INTO tb_product (cl_cat_id, cl_sub_cat_id, cl_brand_id, cl_name, cl_slug, cl_regular_price, cl_sale_price,cl_supplier,cl_product_id,cl_stock,cl_ean, cl_x, cl_y, cl_z, cl_weight,cl_last_price_updated, cl_manufacturer, cl_created_at, cl_updated_at)
VALUES ' . $insertHTML;
            
  
             //   $sql = ' UPDATE tb_product SET ' . $stockHtml . ' ELSE cl_stock END, ' . $supplierPriceHTML . ' ELSE cl_supplier_price END, ' . $profitPercentageHTML . ' ELSE cl_profit_percentage END, ' . $monthlyPriceHTML . ' ELSE cl_monthly_price END ';



                //$whereMultiple = array_merge($whereMultipleStock,$whereMultipleSupplier, $whereMultipleProfitPercentage, $whereMultipleMonthlyPrice);

                $this->callQueryInsert($sql, $where);
                
                 $fp = fopen('action_insert_product_text.txt', 'a');
                //opens file in append mode  
                fwrite($fp, 'Inserted ' . $bulkCount * 500 . ' Products<br/>');  
                fclose($fp); 
                
                
                $bulkCount++;


                $count = 0;
                $insertHTML = '';
                $where = [];

                
            }
            
            $productArray = $product;
            
            if($count > 0)
            {
                $insertHTML.= ',';
            }
            $insertHTML.= '(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
            
            foreach($product AS $each)
            {
                $where[] = $each;
            }
            

           

                //	$productID = $this->update('tb_product', $productArray, $where);


           

            $count++;
        }

           $sql = 'INSERT INTO tb_product (cl_cat_id, cl_sub_cat_id, cl_brand_id, cl_name, cl_slug, cl_regular_price, cl_sale_price,cl_supplier,cl_product_id,cl_stock,cl_ean, cl_x, cl_y, cl_z, cl_weight,cl_last_price_updated, cl_manufacturer, cl_created_at, cl_updated_at)
VALUES ' . $insertHTML;
        //  $whereMultiple = array_merge($whereMultipleStock,$whereMultipleSupplier, $whereMultipleProfitPercentage, $whereMultipleMonthlyPrice);
     
         $this->callQueryInsert($sql, $where);

         $fp = fopen('action_insert_product_text.txt', 'a');
                //opens file in append mode  
                fwrite($fp, 'Inserted All<br/>');  
                fclose($fp); 
            


         /* UPDATE table1 SET val1= CASE  
                           WHEN campid = 259 AND date = 22/6/2011 THEN 200
                            WHEN campid = 259 AND date = 21/6/2011 THEN 210
                          ELSE val1
                        END, 
                 val2= CASE id 
                          WHEN campid = 259 AND date = 22/6/2011 THEN 200
                            WHEN campid = 259 AND date = 21/6/2011 THEN 210
                          ELSE val2 
                        END
             WHERE id IN (1, 2, 3, 4); */

        	/*$this->dbh->commit();
    			return 1;
    			exit;*/

       // }
       // catch (PDOException $e) {
            // roll back transaction
       /*     $this->dbh->rollback();
            return 0;
        }

        return 1;
    }*/
    
    public function getActionItems()
    {
        return $this->fetchAll('tb_product', ['cl_supplier' => 'action']);
    }
    
    public function singleProductInsert($products)
    {
      foreach($products AS $product)
      {
          $updateData['cl_small_specification'] = $product['cl_small_specification'];
          $updateData['cl_big_specification'] = $product['cl_big_specification'];
          $updateData['cl_big_specification_english'] = $product['cl_big_specification_english'];
          return $this->update('tb_product', $updateData, ['cl_product_id' => $product['cl_product_id']]);
      }
    }
    
    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[] = 'action';
                $whereMultipleSmallSpecification[] = $product['cl_product_id'];
                $whereMultipleSmallSpecification[] = $product['cl_small_specification'];
                
                $bigSpecificationHtml.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereMultipleBigSpecification[] = 'action';
                $whereMultipleBigSpecification[] = $product['cl_product_id'];
                $whereMultipleBigSpecification[] = $product['cl_big_specification'];
                
                $bigSpecificationEnglishHtml.= ' WHEN cl_supplier=? AND cl_product_id=? THEN ? ';
                $whereMultipleBigSpecificationEnglish[] = 'action';
                $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('action_insert_specification_text.txt', 'a');
                //opens file in append mode  
                fwrite($fp, 'Inserted ' . $totalCount . ' Products<br/>');  
                fclose($fp); 
            
           

           
        


        return 1;
    
    }
}

$obj = new Insert();
$products = $obj->getActionItems();
$dataInsert = [];
$itemCount = 0;
$totalCount = 0;

foreach($products AS $product)
{
    
        $url = 'https://api.action.pl/api/ade/v2/ProductMarketingDescription?ProductId=' . $product['cl_product_id'] . '&Language=English';
        $headers = array(
          'CustomerId: 83473',
          'UserName: axo9622',
          'ActionApiKey: UtCNXXjIRHRR0w0gL2P6FbMc2FBknu5MzhMZckzAKS0=',

        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($ch);

        $response = json_decode($response);
        
        print_r($response);
         echo '<br/>';
          echo '<br/>';
           echo '<br/>';
        if($response->data->summaryDescriptionShort != null)
        {
            
/*
            $itemSpecifications = $response->data;

            $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%">';
            $count = 1;
            foreach($itemSpecifications->parameters AS $itemSpecification)
            {
                if($count <= 4)
                {
                    $shortSpecification.= '<tr><th>' . $itemSpecification->parameterName . '</th><td>' . $itemSpecification->parameterValue . '</td></tr>';
                }

                $bigSpecification.= '<tr><th>' . $itemSpecification->parameterName . '</th><td>' . $itemSpecification->parameterValue . '</td></tr>';
                $count++;
            }

            $shortSpecification.= '</table>';
            $bigDescription.= '</table>';

            $dataInsert[$itemCount]['cl_product_id'] = $product['cl_product_id'];
            $dataInsert[$itemCount]['cl_small_specification'] = $shortSpecification;
            $dataInsert[$itemCount]['cl_big_specification'] = $bigSpecification;
            $dataInsert[$itemCount]['cl_big_specification_english'] = $bigSpecification;


            if($itemCount == 250)
            {
                $obj->updateSpecificationsBulk($dataInsert, $totalCount);

                 $itemCount = 0;
            }
            */
        }
       

      //  $obj->singleProductInsert($dataInsert);
       // exit;
        $itemCount++;
        $totalCount++;
    
    
}

/*
$url = 'https://api.action.pl/api/ade/v2/ProductTechnicalSpecification/GetListForAllProduct?Language=English';
$headers = array(
  'CustomerId: 83473',
  'UserName: axo9622',
  'ActionApiKey: UtCNXXjIRHRR0w0gL2P6FbMc2FBknu5MzhMZckzAKS0=',
    
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);

$response = json_decode($response);



//print_r($response->data[0]);

$insertData = array();
$count = 0;
/*print_R($response);
exit;
foreach($response->data AS $data)
{
    
   
    $productNameSlug = preg_replace('/\s+/', '-',  $data->productName);
    $productNameSlug = str_replace('+', '-', $productNameSlug);
    $productNameSlug = str_replace('?', '-', $productNameSlug);
    $productNameSlug = str_replace('&', '-', $productNameSlug);
    $productNameSlug = str_replace('#', '-', $productNameSlug);
    $productNameSlug = str_replace('/', '-', $productNameSlug);
    $productNameSlug = str_replace('\\', '-', $productNameSlug);
    $productNameSlug = str_replace('.', '-', $productNameSlug);
    $productNameSlug = str_replace(',', '-', $productNameSlug);
    $productNameSlug = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE',  $productNameSlug);
    
   
    
    
    
    
    $insertData[$count]['cl_cat_id'] = 1587;
    $insertData[$count]['cl_sub_cat_id'] = 344;
    $insertData[$count]['cl_brand_id'] = 1291;
    $insertData[$count]['cl_name'] = $data->productName;
    $insertData[$count]['cl_slug'] = $productNameSlug;
    $insertData[$count]['cl_regular_price'] = $data->price;
    $insertData[$count]['cl_sale_price'] = $data->price;
    $insertData[$count]['cl_supplier'] = 'action';
    $insertData[$count]['cl_product_id'] = $data->productId;
    if($data->quantity > 0)
    {
        $insertData[$count]['cl_stock'] = 1;
    }
    else {
        $insertData[$count]['cl_stock'] = 0;
    }
    
    $insertData[$count]['cl_ean'] = $data->ean;
    $insertData[$count]['cl_x'] = $data->sizeX;
    $insertData[$count]['cl_y'] = $data->sizeY;
    $insertData[$count]['cl_z'] = $data->sizeZ;
    $insertData[$count]['cl_weight'] = $data->weight;
    $insertData[$count]['cl_last_price_updated'] = date('Y-m-d H:i:s');
    $insertData[$count]['cl_manufacturer'] = $data->producerId;
    $insertData[$count]['cl_created_at'] = date('Y-m-d H:i:s');
    $insertData[$count]['cl_updated_at'] = date('Y-m-d H:i:s');
    
    
    $count++;
    
}

$obj = new Insert();
$obj->updateBulk($insertData);

curl_close($ch);

*/