<?php

ini_set("memory_limit","1024M");
set_time_limit(600000);

// get data
// connect import database
/*
$connection=mysql_connect('localhost', 'root', '1234') or die ("Verbindungsversuch fehlgeschlagen");
mysql_select_db('intelectra', $connection) or die("Konnte die Datenbank nicht waehlen.");
*/
$connection=mysql_connect('localhost', 'intelectra_shop_', 'Wwja71!3') or die ("Verbindungsversuch fehlgeschlagen");
mysql_select_db('intelectra_shop__', $connection) or die("Konnte die Datenbank nicht waehlen.1");

echo "get items";
$query = mysql_query("SELECT * FROM items WHERE name!='' and id > 8900") or die("Anfrage nicht erfolgreich");
$data = array();
echo "set uris";
while($obj = mysql_fetch_object($query)) {
        // get number
        $sql = 'SELECT bestellcode FROM passendwie WHERE nr="'.$obj->number.'" AND bestellcode != ""';
        $query2 = mysql_query($sql) or die("Anfrage nicht erfolgreich".$sql);
	$number = '';
        $org_number = '';
	while($obj2 = mysql_fetch_object($query2)) {
            $org_number = $obj2->bestellcode;
            $teilnr = split('=', $obj2->bestellcode);
            foreach ($teilnr as $bestellcode) {
                $number =  preg_replace("@[^0-9\-]@si", "", $bestellcode.' ');
                $number = str_replace('-', '', $number);
                if ($number != '' && strlen($number) > 4) {
                    //echo '<hr>'.$number.'<br>';
                    //echo $org_number.'<br>';

                }
                if ($number != '') {
                    break;
                }
            }
            if ($number != '') {
                break;
            }
	}
    
    //echo preg_replace("@[^0-9\-]@si", "", $number).'<br>';
        $obj->name = utf8_encode($obj->name);
	$short_uri = $obj->name.'-'.$number;
	$short_uri = str_replace(array('ä', 'Ä', 'ö', 'Ö', 'ü', 'Ü', 'ß'), array('ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss'), $short_uri);
	$short_uri = preg_replace("@[^0-9aA-zZ\-]@si", "-", $short_uri);
	$short_uri = preg_replace("@(-{2,})@si", "-", $short_uri);
	$new_uri = '';
	$old_uri = $short_uri;
	$i = 0;
	while ($new_uri == '') {
		$sql = "SELECT id FROM items WHERE short_uri = '$short_uri' AND id != ".$obj->id;
		$result = mysql_query($sql);
		if (mysql_num_rows($result) == 0) {
			$new_uri = $short_uri;
		} else {
			$i++;
			$short_uri = $old_uri . '_' . $i;
		}
	}
	
	$sql = "
		UPDATE items
		SET
                    short_uri='".$short_uri."'
		WHERE id=".$obj->id."
	";
	//echo $sql.'<br>';
	$query2 = mysql_query($sql);
        if (!$query2) {
                echo $sql;
                echo "<br />";
        }
	
}
echo "ende";
?>