<?php


require_once DLEPlugins::Check(ENGINE_DIR . '/modules/alloha.func.php');

$config_mod = unserialize( file_get_contents( ENGINE_DIR . '/data/alloha.config' ) );
if ( !$config_mod ) $config_mod = array(); 

check_license_alloha();

if ($member_id['user_group']>1) {
	die('{"error": "for admin user only"}');
}


$last_file = ENGINE_DIR.'/data/alloha.last.file';
if (!file_exists($last_file)) {
	$startfrom = $rebuildcount = 0;
	file_put_contents($log_file, "0|0");
}
else {
	$data = file_get_contents($last_file);
	$data = explode('|', $data);
	$startfrom = $data[0];
	$rebuildcount = $data[1];
}

file_put_contents('log.txt', "$startfrom===$rebuildcount\n" , LOCK_EX|FILE_APPEND); 


$count_per_step = 10;

$where = $startfrom ? "WHERE id>'{$startfrom}'" : '';


$result = $db->query("SELECT id, date, xfields, category, alt_name, approve FROM " . PREFIX . "_post $where ORDER BY id LIMIT ".$count_per_step);

while($row = $db->get_row($result))
{
	
	$rebuildcount=$rebuildcount+1;

	$xfields = xfieldsdataload(stripslashes($row['xfields']));

	$res = request('https://api.apbugall.org/?token='.$config_mod['api_token'].'&kp='.intval($xfields['kinopoisk_id']));

	$res = json_decode($res, true);

	if(!count($res['data'])) {
		$startfrom = $row['id'];
		file_put_contents($last_file, "{$startfrom}|{$rebuildcount}", LOCK_EX); 
		continue;
	} 

	if($res['status']=='error') die('{"error": "'.$res['error_info'].'"}');

	$res = $res['data'];

	$request = [];

	$request['last_translate'] = trim( @array_shift(explode(',', $res['translation'])) );
	$request['iframe_url'] = $res['iframe'];

	$episodes = array_shift($res['seasons']);
	$episodes = count($episodes['episodes']);
	$request['episode_count'] = $episodes;

	$request['instream_ads'] = ($res['ads']=='') ? '' : 1;

	$request['trailer'] = $res['iframe_trailer'];
	$request['translator']    = $res['translation'];

	$request['last_season'] = $res['seasons_count'];
	$request['last_episode'] = $res['last_episode'];

	$request['quality'] = $res['quality'];

	if($res['seasons_count']){
	    $is_serial = true;
	} else {
		$is_serial = false;
	}


	$ex_genres = [];

	if ($res['category']=='2' && mb_stripos($res['genre'], 'мультфильм')===false) {
	    $ex_genres[] = "сериал"; $request['video_type'] = 'сериал';
	}

	if ($res['category']=='1' && mb_stripos($res['genre'], 'мультфильм')===false) {
	    $ex_genres[] = "фильм"; $request['video_type'] = 'фильм';
	}

	if ($res['category']=='5') {
	    $ex_genres[] = "тв шоу"; $request['video_type'] = 'тв шоу';
	}

	if (mb_stripos($res['genre'], 'мультфильм')!==false) {
	    if ($is_serial) {
	        $request['video_type'] = "мультсериал";
	        $ex_genres[] = "мультсериал";
	    } else {
	        $request['video_type'] = 'мультфильм';
	        $ex_genres[] = "мультфильм";
	    }
	}

	if (mb_stripos($res['country'], 'россия')===false && mb_stripos($res['country'], 'ссср')===false) {
	    $ex_genres[] = "зарубежный";
	}

	if ($res['category']=='4') {
	    $ex_genres[] = "аниме сериал"; $request['video_type'] = 'аниме сериал';
	}

	if ($alloha['type']=='anime') {
	    $ex_genres[] = "аниме"; $request['video_type'] = 'аниме';
	}


	$cats = array();
	$genres = fixGenres(explode(',', $res['genre']));


	$inter = array_merge($ex_genres, $genres, explode(',', $res['country']), array($res['year']));

	if ($request['video_type'] == 'мультсериал') {
	    $inter = array_diff($inter, ['мультфильм']);
	}

	if ($res['category']=='3') {
	    $inter = array_diff($inter, ['зарубежный', 'мультфильм']);
	}

	if ($res['category']=='4') {
	    $inter = array_diff($inter, ['зарубежный', 'мультсериал', 'мультфильм', 'аниме']);
	}


	foreach ($config_mod['category'] as $cat_id => $values) {
	    $f = true;

	    foreach ($values as $value) {
	        if ( !in_array($value, $inter) ) {
	            $f = false;
	            break;
	        }
	    }

	    if ( $f ) $cats[] = $cat_id;
	}

	$cats = array_unique(array_merge($cats, explode(',', $row['category'])));

	$config_mod['category'] =  implode(",", $cats);


	$compile = template($config_mod, $request);

	$new_xfields = array_diff($compile['xfields'], [' ', '']);
	$new_xfields = array_replace($xfields,$new_xfields);

	$xfields = $db->safesql(xfieldsdatasave($new_xfields));

	$category = $compile['category']; 

	$db->query( "UPDATE " . PREFIX . "_post SET $date xfields='$xfields', category='$category' WHERE id='{$row['id']}'" );

	if ($category) {
		$db->query( "DELETE FROM " . PREFIX . "_post_extras_cats WHERE news_id='{$row['id']}'" );
	    foreach (explode(',', $category) as $cat_id) {
	        $db->query( "INSERT INTO " . PREFIX . "_post_extras_cats (news_id, cat_id) VALUES ('{$row['id']}', '{$cat_id}')" );
	    }
	}

	$startfrom =  $row['id'];
	file_put_contents($last_file, "{$startfrom}|{$rebuildcount}", LOCK_EX); 
	
}

clear_cache();

$result = [
	'status' => 'ok',
	'startfrom' => $startfrom,
	'rebuildcount' => $rebuildcount
];

echo json_encode($result);


?>