<?php
function update_table($id_field,$product_id,$local_id)
{
    global $table;
    $sql="update $table set $id_field='$product_id' where pri_key=$local_id";
	$r1=mysqli_execution($sql);
	echo 'Connected: ' . $id_field . ': Local id ' . $local_id . ' with shop id ' . $product_id . '<br />';
}

//email the not_found items and suggestions    
function notification($not_found,$total_changes)    
{
global $notification_email,$headers,$subject,$table;
$message.="\r<br>\r\n<br>\r\n<br>\r\n<br><b>PRODUCTS NOT FOUND</b><br/>";
$message.=join("\r<br>",$not_found);
//how many records we have  ?
$r=fetch("select count(*) as cnt from $table");
$total=$r[0];
if($total>0)
    $percent=round($total_changes*100/$total);
else
    $percent=0;    
if($percent>10)
{
    $message.="\r<br>\r<br>\r<br>\r<br> Many Changes Warning";
    $message.="\r<br>There are over $percent % changes of price in database";
}

$message.="\r<br>\r<br>\r<br>\r<br>Products to be deleted";
$res=mysqli_execution("select pri_key, name, quantity from $table where to_delete=0");
while($r=mysqli_fetch_array($res))
{
    $message.="\r<br>Product $r[0] $r[name] $r[quantity] seems to be missing from CSV";
    
    
}
//echo $message;
if ($_GET["mail"] == 1) { // only send with URL param
  echo($notification_email . $subject . $message . $headers);
  mail($notification_email,$subject,$message,$headers);
}
    
}
 
 
 function update_price($data,$store_id)
 {
 //deppendign on store ID from stores_array it calls the right function, with it's ID and price fields'
    switch($store_id)
    {
        case 0: manage_sql($data,"id_misterspex", 'price_misterspex',$store_id);break;
        case 1: manage_sql($data,"id_lensway", 'price_lensway',$store_id);break;
        case 2: manage_sql($data,"id_lenson", 'price_lenson',$store_id);break;        
        case 3: manage_sql($data,"id_shopping4net", 'price_shopping4net',$store_id);break;        
        case 4: manage_sql($data,"id_yourlenses", 'price_yourlenses',$store_id);    // in yourlenses case update both price and url    

//        case 6: manage_sql($data,"id_piilaritnetista", 'price_piilaritnetista',$store_id);    // in update both price and url    
    }
 }
//        case 1: manage_sql($data,"id_netlens", 'price_netlens',$store_id);break;


//         case 6: manage_sql($data,"id_yourlenses", 'price_yourlenses',$store_id);    // in yourlenses case update both price and url    



 function update_url($data,$store_id)
 {
 //deppendign on store ID from stores_array it calls the right function, with it's ID and price fields'
    switch($store_id)
    {

        case 0: manage_sql_url($data,"id_misterspex", 'url_misterspex',$store_id);break;  // in misterspex case update also url
//        case 0: break; // nothing to update here
        case 1: manage_sql_url($data,"id_lensway", 'url_lensway',$store_id);break;  // in lensway case update also url
        case 2: manage_sql_url($data,"id_lenson", 'url_lenson',$store_id);break;  // in lenson case update also url
        case 3: manage_sql_url($data,"id_shopping4net", 'url_shopping4net',$store_id);break;  // in shopping4net case update also url, change 250814
        case 4: manage_sql_url($data,"id_yourlenses", 'url_yourlenses',$store_id);break;    // in this case update also url    

    }
 }

//        case 6: manage_sql_url($data,"id_piilaritnetista", 'url_piilaritnetista',$store_id);break;    // in piilaritnetista case update also url    

//        case 6: manage_sql_url($data,"id_yourlenses", 'url_yourlenses',$store_id);break;    // in yourlenses case update also url    



function manage_sql($data,$id_field,$price_field,$store_id)
{
    global $not_found,$stores_array,$storenames_array,$table,$total_changes,$connect_product;
    global $bd;
   //the same for all stores 
    foreach($data as $val)
    {
        //locate the product in database
        $sql="select count(*) as cnt from $table where $id_field='$val[1]'";
//        echo $sql;
        $r=fetch($sql);
        if($r[0]>0)
            {
                //record located, updating the price
                echo '<br>Now checking price of product '.$val[1].' (' . $val[2] . ')';
				flush();

//lensway system deprecated
//				if ($price_field == "price_lensway") {  // special update for LENSWAY, because there we have same id for every product in that product group, etc. quantities 30 and 90
//				$quantity_helper1 = substr ($val[2],-5,4); // take 4 chars from the end of the name but not the last, for example "Frequency 38 (3)" would be => "8 (3"
//				$quantity_helper2 = explode ('(',$quantity_helper1); // divide the string where is "(", example would be "8 " and "3"
//				$quantity_helper3 = $quantity_helper2[1]; // the latter part - finally, this is the actual quantity!
//				$sql="update $table set ".$price_field."_backup=$price_field,$price_field='$val[0]',to_delete=1 where $id_field='$val[1]' and quantity=$quantity_helper3";
//				} else { // normal update of price
//                  $sql="update $table set ".$price_field."_backup=$price_field,$price_field='$val[0]',to_delete=1 where $id_field='$val[1]'";
//				}
                $sql="update $table set ".$price_field."_backup=$price_field,$price_field='$val[0]',to_delete=1 where $id_field='$val[1]'";
				mysqli_execution($sql);
                //compare those 2 prices
                $r=fetch("select $price_field as price_new, ".$price_field."_backup as price_old from $table where $id_field='$val[1]'");
                if($r[price_new]<>$r[price_old]) {
					echo '- <b>changed!</b>';
					$total_changes++;
				}

// this original code didn't make any sense!?
//                $r=fetch("select count(*) as cnt from $table where ".$price_field."_backup<>".$price_field);
//                if($r[cnt]>0) {
//					echo $r[cnt];
//					echo ' - changed!';
//					$total_changes++;
//				}



			}
            else
            {
                
                //find suggestions
                echo '<br>Product  '.$val[1]. '(' . $val[2] .') from  store '. $store_id.' not found, looking for suggestions';flush();
                 $search=explode(' ',$val[2]);
                 $search=$search[0];
				echo ' for: ' . $val[2];
				$res=mysqli_execution("select pri_key ,name, quantity from $table where name like '%" . mysqli_real_escape_string($bd, $search) . "%'");
                $sugestions="";
                while($r=mysqli_fetch_array($res))
                {
                  $sugestions.=$r[name]. ' (' . $r[quantity] . ') <a href="'.$connect_product.'&store='.$store_id.'&product_id='.$val[1].'&local_id='.$r[0].'">Connect product to this</a><br>' ;
                    
                }
                
                $nf="Product <b>$val[1] ($val[2])</b> from store ".$storenames_array[$store_id]. " wasn't found!<br /> " ;
                if(strlen($sugestions)>1)
                {
                    $sugestions=trim($sugestions,',');
                    $nf.="Suggestions :<br>".$sugestions;
                    
                    
                }
                $not_found[]=$nf;
                
            }
        
    }
    
}
    
function manage_sql_url($data,$id_field,$url_field,$store_id)
{
    global $not_found,$stores_array,$table,$total_changes,$connect_product;
   //the same for all stores 
    foreach($data as $val)
    {
        //locate the product in database
        $sql="select count(*) as cnt from $table where $id_field='$val[1]'";
        $r=fetch($sql);
        if($r[0]>0)
            {
                //record located, updating the URL
                echo '<br>Now checking url of product '.$val[1].' (' . $val[2] . ')';
				flush();

                $sql="update $table set ".$url_field."_backup=$url_field,$url_field='$val[3]',to_delete=1 where $id_field='$val[1]'";
				mysqli_execution($sql);
                //compare those 2 urls
                $r=fetch("select $url_field as url_new, ".$url_field."_backup as url_old from $table where $id_field='$val[1]'");
                if($r[url_new]<>$r[url_old]) {
					echo '- <b>url changed!</b> - ' .$url_new;
					$total_changes++;
				}

			}
        
    }
    
}

	
	
	
	
function convert($store_id,$store_csv)
{
    $return=array();
    switch($store_id)
    {
        case 0: $return=extract_store_0($store_csv);break;
        case 1: $return=extract_store_1($store_csv);break;
        case 2: $return=extract_store_2($store_csv);break;
        case 3: $return=extract_store_3($store_csv);break;
        case 4: $return=extract_store_4($store_csv);break;
    }
//        case 6: $return=extract_store_6($store_csv);break;        

return $return     ;
}
//for store 0, Misterspex FI
function extract_store_0($url)
{
    $return=array();
    $tmp=array();
    $lines=file($url);
    $cnt=0;
    foreach($lines as $line)
    {
    $tmp=explode("|",$line) ;
    //0 is price
//    $return[$cnt][0]=str_replace(",",'.',$tmp[9]); // replace in fact not necessary any more since 210214
    $return[$cnt][0]=$tmp[9]; // replace in fact not necessary any more since 210214
    $return[$cnt][3]=$tmp[2]; // 3 is url!!
//  echo '--- ---> ' . $tmp[5];

    //1 is id
//    $return[$cnt][1]=$tmp[13];  // SKU ID - new 010419
    $return[$cnt][1]=substr($tmp[13], 0, strlen($tmp[13]-1));
//2 is name
	$return[$cnt][2]=$tmp[10];
    $cnt++;
    }
  return $return;  
}

//for store 1, Netlens FI
//DISABLED
function extract_store_xxxx6545($url)
{
    $return=array();
    $tmp=array();
    $lines=file($url);
    $cnt=0;
    foreach($lines as $line)
    {
    $tmp=explode(";",$line) ;
    //0 is price
    $return[$cnt][0]=$tmp[4];
    //1 is id
    $return[$cnt][1]=$tmp[1];
    //2 is name
    $return[$cnt][2]=$tmp[0];
	//$cnt[3] is URL !!!
   	$return[$cnt][3]=$tmp[5];
    $cnt++;
    }
  return $return;  
}

//for store 1, Lensway FI
//2022 TD
function extract_store_1($url)
{
	echo 'lensway';
    $return=array();
    $tmp=array();
    $lines=file($url);
    $cnt=0;
    foreach($lines as $line)
    {
           	$line=str_replace("\"",'',$line);  // delete all "quotes"
echo $line;
            $tmp=explode("|",$line) ;
            //0 is price
            $return[$cnt][0]=str_replace(',','.',$tmp[13]); // 64,80 => 64.80
            echo $tmp[46];
            //1 is id
            $return[$cnt][1]=$tmp[46]; // product id
            //2 is name
            $return[$cnt][2]=$tmp[0];
    		//$cnt[3] is URL !!!
	    	$return[$cnt][3]=$tmp[2];
    $cnt++;
    }
  return $return;  
}

//for store 2, LensOn FI - changed 010319 to tradedoubler
//for store 2, LensOn FI - note this changed 250814 to lenson's new tracking
// changed 220917 to add 0.02 to all prices as they're cheating!
//new feed 04052018

function extract_store_2($url)
{
    $return=array();
    $tmp=array();
    $lines=file($url);
    $cnt=0;
//    foreach($lines as $line)   // looks like: product ID;"name";currency;price;description;productURL;...
    foreach($lines as $line)   // looks like: "name";"brand";"product id";"price";"productURL";...
    {
    $tmp=explode("|",$line) ;
    //$cnt[1] is id
    $return[$cnt][1]=str_replace("\"",'',$tmp[6]);  // delete all "quotes"

    //$cnt[0] is price
    $tmp[4]=str_replace(",",'.',$tmp[4]);  // decimals with dot not comma
    $return[$cnt][0]=str_replace("\"",'',$tmp[4]);
//    $cheating_lenses = array ("151", "346");
//    if (in_array ($return[$cnt][1], $cheating_lenses)) {  // if ID found on list
//      $return[$cnt][0]=$return[$cnt][0]+0.02;
//   }
    //$cnt[2] is name
    $return[$cnt][2]=str_replace("\"",'',$tmp[0]); // looks like: "1-Day Acuvue"
	//$cnt[3] is URL !!!
//	$tmp[1]=str_replace('country%3DNO','country%3DFI',$tmp[1]);
//	$tmp[1]=str_replace('country%3DNO','country%3DFI',$tmp[1]);
// omg what idiots we have to deal with

//	if (strpos($tmp[1], "%3F_country") == false) {
//  	  $tmp[1]=substr($tmp[1], 0, (strlen($tmp[1])-1));
//
//  	  $tmp[1].= '%3F_country%3DFI%26campaign_id%3D9240)';
//    }
    $return[$cnt][3]=str_replace("\"",'',$tmp[1]);
    $cnt++;
    }
  return $return;  
}


//for store 3, Shopping4net FI
function extract_store_3($url)
{
    $return=array();
    $tmp=array();
    $lines=file($url);
    $cnt=0;
    foreach($lines as $line)   // looks like: Opti-Free Express NoRub 355ml|...
    {
    $tmp=explode("|",$line) ;
    //$cnt[1] is id
    $return[$cnt][1]=$tmp[3];
    //$cnt[0] is price
    $return[$cnt][0]=$tmp[2]; 
    //$cnt[2] is name
    $return[$cnt][2]=$tmp[0];
    $return[$cnt][3]=$tmp[1]; //$cnt[3] is URL
    $cnt++;
    }
  return $return;  
}



//for store 5, LensMe FI
//DISABLED
function extract_store_dlkj5($url)
{
    $return=array();
    $tmp=array();
    $lines=file($url);
    $cnt=0;
    foreach($lines as $line) 
    {
//    echo $tmp[2]. " ";
//    echo $tmp[6]. " ";
//    echo $tmp[3]. " ";
	
	$line=str_replace("\"",'',$line);  // delete all "quotes"

     $tmp=explode("|",$line) ;
    //$cnt[1] is id
    $return[$cnt][1]=$tmp[2];
    //$cnt[0] is price
    $return[$cnt][0]=$tmp[1]; 
    //$cnt[2] is name
    $return[$cnt][2]=$tmp[3];
    //$cnt[3] is URL !!!
    $return[$cnt][3]=$tmp[0];
    $cnt++;
    }
  return $return;  
}



//for store 4, Yourlenses
function extract_store_4($url)
{
    $return=array();
    $tmp=array();
    $lines=file($url);
    $cnt=0;
    foreach($lines as $line) 
    {
	
//	$line=str_replace("\"",'',$line);  // delete all "quotes"

// BEFORE 200119
//     $tmp=explode("|",$line) ;
    //$cnt[1] is id
//    $return[$cnt][1]=$tmp[6];
    //$cnt[0] is price
//    $return[$cnt][0]=$tmp[4]; 
    //$cnt[2] is name
//    $return[$cnt][2]=$tmp[0];
    //$cnt[3] is URL !!!
//    $return[$cnt][3]=$tmp[1];

     $tmp=explode("|",$line) ;
    //$cnt[1] is id
    $return[$cnt][1]=$tmp[3];
    //$cnt[0] is price
    $return[$cnt][0]=$tmp[2]; 
    //$cnt[2] is name
    $return[$cnt][2]=$tmp[0];
    //$cnt[3] is URL !!!
    $return[$cnt][3]=$tmp[1];
    $cnt++;
    }
  return $return;  
}


//for store 6, Piilaritnetista.fi
//function extract_store_6($url)
//{
//    $return=array();
//    $tmp=array();
 //   $lines=file($url);
 //   $cnt=0;
 //   foreach($lines as $line) 
 //   {
//    echo $tmp[2]. " ";
//    echo $tmp[6]. " ";
//    echo $tmp[3]. " ";
	
//	$line=str_replace("\"",'',$line);  // delete all "quotes"

//     $tmp=explode(";",$line) ;
    //$cnt[1] is id
 //   $return[$cnt][1]=substr(md5($tmp[0]), 0, 8);  // ID not defined so using the 8 first chars of the md5 of the name as ID
    //$cnt[0] is price
 //   $return[$cnt][0]=$tmp[2]; 
    //$cnt[2] is name
//    $return[$cnt][2]=$tmp[0];
    //$cnt[3] is URL !!!
 //   $return[$cnt][3] = 'http://tc.tradetracker.net/?c=11176&m=12&a=79203&u=' . urlencode(str_replace('http://www.piilaritnetista.fi','',$tmp[1]));
 //   $cnt++;
 //   }
//  return $return;  
//}



//database functions

function fetch($sql){
$r=mysqli_fetch_array(mysqli_execution($sql));
return $r;
}


//execute a sql query, retunrs -1 if failed

function mysqli_execution($sql)
{
global $bd;
$result=mysqli_query($bd, $sql);

if(!$result){

//echo '<br>'.mysqli_error() . ' in sql query '. $sql  ;
echo '<br>'.mysqli_error($bd) . ' in sql query '. $sql  ;
return false;
}
else
{
return $result;
}

}

function table_to_array($table,$id_field,$name_field,$where=' where 1')
{
$return=array();
$res=mysqli_execution("select $id_field,$name_field from $table  $where");
while($r=mysqli_fetch_array($res))
$return[$r[$id_field]]=$r[$name_field];
return $return;
}


function print_pre($data)
{
?>
<pre>
<?
print_r($data);
?>
</pre>
<?
}
  function mysqli_insert($table, $fields_array, $values_array)
{
    // create the fields
    $fields_count = count($fields_array);
    $fields = '';
    $values = '';
    for ($i = 0;$i < $fields_count-1;$i++) {
        $fields .= ' ' . $fields_array[$i] . ',';
        $values .= ' ' . $values_array[$i] . ',';
    }
    $values .= ' ' . $values_array[$i];
    $fields .= ' ' . $fields_array[$i];
    // create the values
    $sql = " insert into $table ($fields) values ($values)";
    return mysqli_execution($sql);
}

function mysqli_update($table, $fields_array, $values_array, $where)
{
    // create the fields
    $sql = " update  $table set ";

    $fields_count = count($fields_array);
    if ($fields_count == 0) return;
    for ($i = 0;$i < $fields_count-1;$i++)
    $sql .= ' ' . $fields_array[$i] . '=' . $values_array[$i] . ',';
    $sql .= ' ' . $fields_array[$i] . '=' . $values_array[$i] . ' ' . $where;
    return mysqli_execution($sql);
}
function error_message($mesage, $redir = "index.php")
{
    echo '<table width="100%" border="0" cellpadding="3" cellspacing="1" align="center" style="BORDER-COLLAPSE: collapse" borderColor=#F1F1f1>
  <tr>
    <td colspan="9"><br>' . $mesage . '<br>
<br>
';
    echo 'Click <a href="' . $redir . '"><font color="red">here</font></a> </td>
  </tr>
</table>';
}
function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = TRUE)
    {
        $total_pages = ceil($num_items/$per_page);
        if ( $total_pages == 1 )
        {return '';}
        $on_page = floor($start_item / $per_page) + 1;
        $page_string = '';
        if ( $total_pages > 10 )
        {
            $init_page_max = ( $total_pages > 3 ) ? 3 : $total_pages;
            for($i = 1; $i < $init_page_max + 1; $i++)
            {
                $page_string .= ( $i == $on_page ) ? '<b>' . $i . '</b>' : '<a href="' . $base_url . "page=" . ( $i ) . '">' . $i . '</a>';
                if ( $i <  $init_page_max )
                {$page_string .= ", ";}
            }
            if ( $total_pages > 3 )
            {
                if ( $on_page > 1  && $on_page < $total_pages )
                {
                    $page_string .= ( $on_page > 5 ) ? ' ... ' : ', ';
                    $init_page_min = ( $on_page > 4 ) ? $on_page : 5;
                    $init_page_max = ( $on_page < $total_pages - 4 ) ? $on_page : $total_pages - 4;
                    for($i = $init_page_min - 1; $i < $init_page_max + 2; $i++)
                    {
                        $page_string .= ($i == $on_page) ? '<b>' . $i . '</b>' : '<a href="' . $base_url . "page=" . ( $i ) . '">' . $i . '</a>';
                        if ( $i <  $init_page_max + 1 )
                        {
                            $page_string .= ', ';
                        }
                    }

                    $page_string .= ( $on_page < $total_pages - 4 ) ? ' ... ' : ', ';
                }
                else
                {
                    $page_string .= ' ... ';
                }

                for($i = $total_pages - 2; $i < $total_pages + 1; $i++)
                {
                    $page_string .= ( $i == $on_page ) ? '<b>' . $i . '</b>'  : '<a href="' . $base_url . "page=" . ( $i ) . '">' . $i . '</a>';
                    if( $i <  $total_pages )
                    {
                        $page_string .= ", ";
                    }
                }
            }
        }
        else
        {
            for($i = 1; $i < $total_pages + 1; $i++)
            {
                $page_string .= ( $i == $on_page ) ? '<b>' . $i . '</b>' : '<a href="' . $base_url . "page=" . ( $i-1 ) . '">' . $i . '</a>';
                if ( $i <  $total_pages )
                {
                    $page_string .= ', ';
                }
            }
        }

        if ( $add_prevnext_text )
        {
            if ( $on_page > 1 )
            {
                $page_string = ' <a href="' . $base_url . "page=" . ( ( $on_page - 2 ) ) . '">' . 'Previous' . '</a>&nbsp;&nbsp;' . $page_string;
            }

            if ( $on_page < $total_pages )
            {
                $page_string .= '&nbsp;&nbsp;<a href="' . $base_url . "page=" . ( $on_page ) . '">' . 'Next' . '</a>';
            }

        }

       $page_string = 'Goto page' . ' ' . $page_string;

        return $page_string;
    }

?>