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


include_once "../config.php";
include_once "../database1.php";
// Load the XML file
$xmlFile = 'csv/innpro_products_full.xml';

// Check if the file exists
if (!file_exists($xmlFile)) {
    die("File not found: $xmlFile");
}




class Insert extends database
{
    public function checkBrand($name)
    {
            return $this->fetchRow('tb_brands', ['cl_name' => $name]);
    }
    
    public function insertBrand($brand)
    {
      return $this->insert('tb_brands', ['cl_name' => $brand]);
    }
  
    public function checkProduct($productID)
    {
        return $this->fetchRow('tb_product', ['cl_product_id' => $productID, 'cl_supplier' => 'wave']);
    }
    
    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_price,cl_supplier,cl_product_id,cl_stock,cl_ean, cl_weight,cl_last_price_updated, cl_manufacturer,cl_description,cl_meta_description,cl_keywords, cl_created_at, cl_updated_at, cl_small_specification,cl_big_specification,cl_big_specification_english,cl_image,cl_image_location)
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('innpro_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;
            }
            

            $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_price,cl_supplier,cl_product_id,cl_stock,cl_ean, cl_weight,cl_last_price_updated, cl_manufacturer,cl_description,cl_meta_description,cl_keywords, cl_created_at, cl_updated_at, cl_small_specification,cl_big_specification,cl_big_specification_english,cl_image,cl_image_location)
VALUES ' . $insertHTML;
        //  $whereMultiple = array_merge($whereMultipleStock,$whereMultipleSupplier, $whereMultipleProfitPercentage, $whereMultipleMonthlyPrice);
     
         $this->callQueryInsert($sql, $where);

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

// Parse the XML file using SimpleXML
$xml = simplexml_load_file($xmlFile);

// Use namespaces if required
$namespaces = $xml->getNamespaces(true);
$iaiext = $xml->children($namespaces['iaiext']);

$obj = new Insert();
$insertData = array();
$count = 0;
// Extract data from the XML
foreach ($xml->products->product as $product) {
   
    if(!$obj->checkProduct($product['id']))
    {
        



        $insertData[$count]['cl_cat_id'] = 50;
        $insertData[$count]['cl_sub_cat_id'] = 3925;
        
        if(isset($product->producer['name']) && trim($product->producer['name']) != '') {
            $brand = trim($product->producer['name']);
            $res = $obj->checkBrand($brand);

            if(!$res)
            {
              $brandID = $obj->insertBrand($brand);
              $insertData[$count]['cl_brand_id'] = $brandID;
                  //$fileError.= 'Brand not found in database for ' . ($count + 1) . ' row<br/>';
            }
            else
            {
                  $insertData[$count]['cl_brand_id'] = $res['cl_id'];
            }
        }
        else
        {
            $insertData[$count]['cl_brand_id'] = 1291;
        }
        
      
      
      $polish_chars = [
            'ą' => 'a',
            'ć' => 'c',
            'ę' => 'e',
            'ł' => 'l',
            'ń' => 'n',
            'ó' => 'o',
            'ś' => 's',
            'ź' => 'z',
            'ż' => 'z',
            'Ą' => 'A',
            'Ć' => 'C',
            'Ę' => 'E',
            'Ł' => 'L',
            'Ń' => 'N',
            'Ó' => 'O',
            'Ś' => 'S',
            'Ź' => 'Z',
            'Ż' => 'Z',
        ];
      
      
      $productName = strtr((string) $product->description->name, $polish_chars);

      
      
      $productNameSlug = preg_replace('/\s+/', '-',  (string) $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);
        $productNameSlug = $productNameSlug . '-innpro';
        
       // $insertData[$count]['cl_brand_id'] = 1291;
        $insertData[$count]['cl_name'] = $productName;
        
        $insertData[$count]['cl_slug'] = $productNameSlug;
        $insertData[$count]['cl_regular_price'] = (float) $product->price['gross'];
        $insertData[$count]['cl_sale_price'] = (float) $product->price['gross'];
        $insertData[$count]['cl_supplier_price'] = (float) $product->price['gross'];
        $insertData[$count]['cl_supplier'] = 'innpro';
        $insertData[$count]['cl_product_id'] = (string) $product['id'];
        
        
        foreach ($product->sizes->size as $size) {
            $available_stock_quantity = (int) $size->stock['available_stock_quantity'];
            if($available_stock_quantity > 0)
            {
                $insertData[$count]['cl_stock'] = 1;
            }
            else
            {
                $insertData[$count]['cl_stock'] = 0;
            }
            $insertData[$count]['cl_ean'] = (string) $size->attributes($namespaces['iaiext'])['code_external'];
            $insertData[$count]['cl_weight'] = (float) $size['weight'];
            
            
            
        }
        
        
        if(!isset($insertData[$count]['cl_stock']))
        {
            $insertData[$count]['cl_stock'] = 0;
        }
        
        if(!isset($insertData[$count]['cl_ean']))
        {
            $insertData[$count]['cl_ean'] = '';
        }
        
        if(!isset($insertData[$count]['cl_weight']))
        {
            $insertData[$count]['cl_weight'] = 0;
        }
        
        
        
        
        $insertData[$count]['cl_last_price_updated'] = date('Y-m-d H:i:s');
        $insertData[$count]['cl_manufacturer'] = (string) $product->producer['name'];
        $insertData[$count]['cl_description'] = (string) $product->description->long_desc;
        $insertData[$count]['cl_meta_description'] = (string) $product->description->long_desc;
        $insertData[$count]['cl_keywords'] = null;
        $insertData[$count]['cl_created_at'] = date('Y-m-d H:i:s');
        $insertData[$count]['cl_updated_at'] = date('Y-m-d H:i:s');
        
        
        $smallSpecification = $bigSpecification = '<table class="table short_description_table" border="0" cellpadding="1" cellspacing="1" style="width:100%">';
        $specificationCount = 1;
        foreach ($product->parameters->parameter as $parameter) {
            if($specificationCount <= 4)
            {
                $smallSpecification.= '<tr><th>' . $parameter['name'] . "</th><td>" . $parameter->value['name'] . '</td></tr>';
            }
            $bigSpecification.= '<tr><th>' . $parameter['name'] . "</th><td>" . $parameter->value['name'] . '</td></tr>';
            $specificationCount++;
        }
        
        $smallSpecification.= '</table>';
        $bigSpecification.= '</table>';
        $insertData[$count]['cl_small_specification'] = $smallSpecification;
        $insertData[$count]['cl_big_specification_english'] = $insertData[$count]['cl_big_specification'] = $bigSpecification;
        
        
        
        
        $imageCount = 1;
        foreach ($product->images->large->image as $image) {
            if($imageCount == 1)
            {
                $insertData[$count]['cl_image'] = $image['url'];
                $insertData[$count]['cl_image_location'] = 'Link';
            }
            $imageCount++;
        }
        
        
        if(!isset($insertData[$count]['cl_image']))
        {
            $insertData[$count]['cl_image'] = '';
            $insertData[$count]['cl_image_location'] = '';
        }
        
        $count++;
        
    }
    
    
}


$obj->updateBulk($insertData);
