<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
$success=true;

Db::i()->query("DROP TABLE IF EXISTS ?_comments_new");

Db::i()->query("DELETE FROM ?_comments WHERE user_id IS NULL");

Db::i()->query(
	"CREATE TABLE IF NOT EXISTS ?_comments_new (
	`comment_id` int(11) NOT NULL auto_increment,
	`parent_id` int(11),
	`item_id` int(11) NOT NULL,
	`text` text,
	`putdate` datetime NOT NULL default '0000-00-00 00:00:00',
	`updated` timestamp NOT NULL default CURRENT_TIMESTAMP,
	`user_id` int(11) default NULL,
	`login` varchar(20) default NULL,
	`email` varchar(50) default NULL,
	`status` tinyint(1) NOT NULL default '1',
	`level` tinyint(1) NOT NULL default '0',
	`left_key` int(11) NOT NULL,
	`right_key` int(11) NOT NULL,
	`abuse` varchar(255) default NULL,
	`ip` bigint(11) NOT NULL default '0',
	PRIMARY KEY  (`comment_id`)
	) ENGINE=MyISAM  DEFAULT CHARSET=utf8;"
);

Db::i()->query(
	"INSERT INTO ?_comments_new
	SELECT A.comment_id,
	B.comment_id AS parent_id, A.item_id, A.`text`, A.`putdate`, A.`updated`, A.`user_id`, A.`login`, A.`email`, A.`status`, 0, 0, 0, A.`abuse`, A.`ip`
	FROM ?_comments AS A
	LEFT OUTER JOIN ?_comments AS B
	ON B.left_key = (SELECT MAX(C.left_key)
	FROM ?_comments AS C
	WHERE A.left_key > C.left_key
	AND A.left_key < C.right_key
	AND B.item_id=C.item_id)
	AND B.item_id=A.item_id;"
);
		
if ($items=Db::i()->selectCol("SELECT item_id FROM ?_comments_items WHERE counter>0")) {
	foreach ($items as $item_id) {
		buildNestedKeys(NULL, 0, 0, $item_id);
	}
}

Db::i()->query("DROP TABLE ?_comments");
Db::i()->query("RENAME TABLE ?_comments_new TO ?_comments");


function buildNestedKeys($parent_id, $left, $level, $item_id)
{
	$right = $left+1;
	$level++;
	if ($rows = DB::i()->select(
		"SELECT comment_id FROM ?_comments_new
		WHERE item_id = ? { and parent_id = ? } { AND parent_id IS NULL and 1=?d}
		ORDER BY comment_id ASC", $item_id, !is_null($parent_id) ? $parent_id:DBSIMPLE_SKIP, is_null($parent_id) ? 1:DBSIMPLE_SKIP
	)) {
		foreach ($rows as $row) {
			$right = buildNestedKeys($row['comment_id'], $right, $level, $item_id);
		}
	}
	$level--;
	if (!is_null($parent_id)) {
		DB::i()->query(
			"UPDATE ?_comments_new
			SET left_key=?d, right_key=?d , `level`=?d
			WHERE comment_id=? ", $left, $right, $level, $parent_id
		);
	}
	return $right+1;
}

