<?php defined( 'DATALIFEENGINE' ) || die;

$config_mod = json_decode( file_get_contents( ENGINE_DIR . '/data/config.mylists.json' ), true );

if ( isset( $_POST['news_id'] ) && isset( $_POST['status_id'] ) ) {
	if ( !$is_logged ) {
		die ( '{"success":false,"message":"Ошибка: вы не авторизованы на сайте"}' );
	}

	$news_id = intval( $_POST['news_id'] );
	$status_id = intval( $_POST['status_id'] );

	$member_id['mylists'] = explode( "|", $member_id['mylists'] );

	foreach ( $member_id['mylists'] as $index => $row ) {
	    $row = explode( "/", $row );

	    if ( $row[0] == $news_id ) {
	        if ( !$status_id ) {
	            unset( $member_id['mylists'][$index] );
	            $message = "Метка успешно удалена";
	        } else {
	            $member_id['mylists'][$index] = "{$news_id}/{$status_id}";
	            $message = "Метка успешно изменена";
	        }
	    }
	}

	if ( !isset( $message ) && $status_id ) {
	    $member_id['mylists'][] = "{$news_id}/{$status_id}";
	    $message = "Метка успешно установлена";
	}

	$member_id['mylists'] = implode( "|", $member_id['mylists'] );

	$db->query( "UPDATE `" . PREFIX . "_users` SET `mylists` = '{$member_id['mylists']}' WHERE user_id = {$member_id['user_id']}" );

	die ( '{"success":true,"message":"' . $message . '"}' );
}

if ( $action == "init" ) {
	$mylists = $is_logged ? "'{$member_id['mylists']}'" : "false";

	$tmp = array(); 
	foreach ( $config_mod['options'] as $id => $value ) $tmp["_".$id."_"] = $value;

	echo "<script type=\"text/javascript\" src=\"/engine/classes/js/mylists.js\"></script><script type=\"text/javascript\">$(document).ready(function(e) { MyLists = new MyLists({$mylists}, '" . json_encode( $tmp ) . "'); });</script>";

	return;
}

if ( $do == 'mylists' ) {

	$list_ids = array( 0 );
	$list_num = 0;
	foreach ( $config_mod['options'] as $index => $value ) if ( $value[1] == $_GET['listname'] ) $list_num = $index;

	if ( !$list_num && $_GET['listname'] ) {
		header("HTTP/1.0 301 Moved Permanently");
		header("Location: /mylists/");
		die("Redirect");
	}

	if ( !$is_logged ) { 
		if ( isset( $_COOKIE['mylists'] ) ) $mylists = $_COOKIE['mylists'];
			else $mylists = "";
	} else {
		if ( isset( $_COOKIE['mylists'] ) ) {
			$temp_array = array();
			
			foreach ( explode( "|", $member_id['mylists'] ) as $index => $row ) {
			    $row = explode( "/", $row );
			    $temp_array[$row[0]] = "{$row[0]}/{$row[1]}";
			}

			foreach ( explode( "|", $_COOKIE['mylists'] ) as $index => $row ) {
				$row = explode( "/", $row );
				$row[0] = intval( $row[0] );
				$row[1] = intval( $row[1] );

				if ( $row[0] && $row[1] ) $temp_array[$row[0]] = "{$row[0]}/{$row[1]}";
			}

			$temp_array = implode( "|", $temp_array );

			$db->query( "UPDATE " . PREFIX . "_users SET mylists = '" . $temp_array . "' WHERE user_id = {$member_id['user_id']}" );

			setcookie('mylists', 'DELETED', strtotime('-3 hour'), '/');

			$mylists = $temp_array;
		} else $mylists = $member_id['mylists'];
	}

	$count_array = array();

	foreach ( explode( "|", $mylists ) as $index => $row ) {
		$row = explode( "/", $row );
		if ( !$row[0] ) continue;
		if ( $row[1] == $list_num || !$list_num && intval( $row[0] ) ) $list_ids[] = intval( $row[0] );
		$count_array[$row[1]]++;
		$count_array['all']++;
	}
		
	$thisdate = date ( "Y-m-d H:i:s", time () );
	if ($config['no_date'] AND !$config['news_future']) $where_date = " AND date < '" . $thisdate . "'";
	else $where_date = "";

	$allow_list = explode ( ',', $user_group[$member_id['user_group']]['allow_cats'] );
	$stop_list = "";

	if ($allow_list[0] != "all") {
		
		if ($config['allow_multi_category']) {
			
			$stop_list = "category regexp '[[:<:]](" . implode ( '|', $allow_list ) . ")[[:>:]]' AND ";
		
		} else {
			
			$stop_list = "category IN ('" . implode ( "','", $allow_list ) . "') AND ";
		
		}

	}

	$not_allow_cats = explode ( ',', $user_group[$member_id['user_group']]['not_allow_cats'] );

	if( $not_allow_cats[0] != "" ) {
		
		if ($config['allow_multi_category']) {
			
			$stop_list = "category NOT REGEXP '[[:<:]](" . implode ( '|', $not_allow_cats ) . ")[[:>:]]' AND ";
		
		} else {
			
			$stop_list = "category NOT IN ('" . implode ( "','", $not_allow_cats ) . "') AND ";
		
		}
		
	}

	if ($user_group[$member_id['user_group']]['allow_short']) $stop_list = "";

	if ($cstart) {
		$cstart = $cstart - 1;
		$cstart = $cstart * $config['news_number'];
	}
		
	$url_page = $config['http_home_url'] . "mylists" . ( $list_num ? "/" . $config_mod['options'][$list_num][1] : "" );
	$user_query = "do=mylists" . ( $list_num ? "&listname=" . $config_mod['options'][$list_num][1] : "" );

	$news_number = $config_mod['news_number'] ? intval($config_mod['news_number']) : $config['news_number'];

	$sql_select = "SELECT p.id, p.autor, p.date, p.short_story, CHAR_LENGTH(p.full_story) as full_story, p.xfields, p.title, p.category, p.alt_name, p.comm_num, p.allow_comm, p.fixed, p.tags, e.news_read, e.allow_rate, e.rating, e.vote_num, e.votes, e.view_edit, e.editdate, e.editor, e.reason FROM " . PREFIX . "_post p LEFT JOIN " . PREFIX . "_post_extras e ON (p.id=e.news_id) WHERE {$stop_list}approve=1" . $where_date . " AND id IN (" . implode( ",", $list_ids ) . ")" . " ORDER BY FIND_IN_SET(id, '" . implode(",", $list_ids) . "') DESC LIMIT " . $cstart . "," . $news_number;
	$sql_count = "SELECT COUNT(*) as count FROM " . PREFIX . "_post WHERE {$stop_list}approve=1" . $where_date . " AND id IN (" . implode( ",", $list_ids ) . ")";

	$sql_result = $db->query( $sql_select );

	$custom_limit = $news_number;
	$build_navigation = true;
	$custom_all = 0;

	if ( $config['version'] < 11 ) {
		$count_all = $db->super_query( $sql_count );
		$count_all = $count_all['count'] - $custom_all;
	}

	$tpl->load_template( $config_mod['template'] );

	include (ENGINE_DIR . '/modules/show.custom.php');

	if ( !$tpl->result['content'] ) {
	    if ( $config_mod['not_found'] != "" ) {
	     	$tpl->result['content'] = $config_mod['not_found'];
	    } else {
	      	$tpl->result['content'] = " ";
	    }
	}

	$metatags = $config_mod['metatags'];
	$metatags = str_replace( '{list}', $list_num ? $config_mod['options'][$list_num][0] : "", $metatags );
	$metatags = preg_replace( "'\\[list\\](.*?)\\[/list\\]'iu", $list_num ? '\1' : "", $metatags );
	$metatags = preg_replace( "'\\[not-list\\](.*?)\\[/not-list\\]'iu", $list_num ? '' : '\1', $metatags );
	$config_mod['metatags'] = $metatags;

	$mylists_tabs = "";

	$mylists_tabs .= '<li' . ( !$list_num ? ' class="active"' : '' ) . '><a href="/mylists/">Показать все</a> <span>' . ( $count_array['all'] ? $count_array['all'] : '0' ) . '</span></li>';

	foreach ( $config_mod['options'] as $key => $value ) {
		$mylists_tabs .= '<li' . ( $key == $list_num ? ' class="active"' : '' ) . '><a href="/mylists/' . $value[1] . '/">' . $value[0] . '</a> <span>' . ( $count_array[$key] ? $count_array[$key] : '0' ) . '</span></li>'; 
	}

	$mylists_tabs = '<ul class="mylists-tabs">' . $mylists_tabs . '</ul>';
}

?>