<?php


require_once ENGINE_DIR . '/kodik/func.php';

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

check_license_kodik();

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

set_time_limit(0);

$log_file = ENGINE_DIR.'/data/kodik.txt';

if($_POST['start_new']) {
	file_put_contents($log_file, '0|0');
}

if (file_exists($log_file)) {
	list($rebuildcount, $last_id) = explode('|', file_get_contents($log_file));
} else {
	$rebuildcount = $last_id = 0;
}



$next_id = intval($_POST['next_id']);
$limit = 2;


$result = $db->query("SELECT id, date, autor, title, xfields, category, alt_name, approve FROM " . PREFIX . "_post WHERE id>'{$next_id}' ORDER BY id LIMIT ".$limit);

while($row = $db->get_row($result))
{

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

	$title = stripslashes($row['title']);

	$query = []; 

	if (!empty($xfields['kinopoisk_id'])) {
		$query[] = 'kinopoisk_id='.$xfields['kinopoisk_id'];
	}
	if (!empty($xfields['shikimori_id'])) {
		$query[] = 'shikimori_id='.$xfields['shikimori_id'];
	}
	if (!empty($xfields['mdl_id'])) {
		$query[] = 'mdl_id='.$xfields['mdl_id'];
	}

	if (!count($query)) {
		continue;
	}

	$res = request('https://kodikapi.com/search?with_material_data=true&with_episodes_data=true&token='.$config_kodik['api_token'].'&'.implode('&', $query));

	$res = json_decode($res, true);

	if(!empty($res['error'])) die('{"error": "'.$res['error'].'"}');

	if(!count($res['results'])) continue;

	$result = $res;

	$res = $res['results'][0];

	$serials = [];
	foreach ($result['results'] as $value) {
		foreach ($value['seasons'] as $sez => $serArr) {
			foreach ($serArr['episodes'] as $ser => $epArr) {
				$serials[$sez][$ser] = $epArr['screenshots'][0];
			}
		}
	}



	$request = [];

	$ex_genres = array();

	if (in_array($res['type'], ['russian-serial','foreign-serial','multi-part-film'])) 
	    $ex_genres[] = $request['video_type'] = 'сериал';

	elseif (in_array($res['type'], ['russian-movie','foreign-movie'])) 
	    $ex_genres[] = $request['video_type'] = 'фильм';

	elseif ($res['type']=='anime') 
	    $ex_genres[] = $request['video_type'] = 'аниме';

	elseif (in_array($res['type'], ['soviet-cartoon','russian-cartoon','foreign-cartoon'])) 
	    $ex_genres[] = $request['video_type'] = 'мультфильм';

	elseif (in_array($res['type'], ['russian-cartoon-serial','cartoon-serial'])) 
	    $ex_genres[] = $request['video_type'] = 'мультсериал';

	elseif ($res['type']=='anime-serial') 
	    $ex_genres[] = $request['video_type'] = 'аниме сериал';


	if (in_array($res['type'], ['russian-serial','foreign-serial', 'russian-cartoon-serial','cartoon-serial', 'anime-serial','multi-part-film'])){
	    $request['last_season'] = (int)$res['last_season'];    
	    $request['last_episode'] = (int)$res['last_episode'];  
	    $is_serial = true;  
	}
	else $is_serial = false;

	if($res['type']=='anime-serial') $res['material_data']['all_genres'] = array_diff($res['material_data']['all_genres'], ['мультфильм', 'аниме']);

	$cats = array();
	$genres = fixGenres( array_merge((array)$res['material_data']['all_genres'],(array)$res['material_data']['anime_genres']) );


	$res['material_data']['countries'] = (array)$res['material_data']['countries'];


	if($is_serial && $res['type']!='anime' && $res['type']!='anime-serial' && count(array_intersect(['Южная Корея', 'Корея Южная', 'Япония', 'Китай'], $res['material_data']['countries']))) {
	    $ex_genres[] = 'дорама';
	}

	$anime_kind = ( stripos($res['material_data']['anime_kind'], 'ova')!==false || stripos($res['material_data']['anime_kind'], 'ona')!==false ) ? array(strtoupper($res['material_data']['anime_kind'])) : [];

	$inter = array_merge($ex_genres, $genres, $res['material_data']['countries'], array($res['year']), $anime_kind);

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

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

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

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

	$translation = [];
	foreach ($result['results'] as $value) {
	    $translation[] = $value['translation']['title'];
	}
	$translation = array_diff($translation, ['']);


	if( ($aired_at = strtotime($res['material_data']['aired_at']))!==false && $res['material_data']['aired_at'] ){
	    $res['aired_at'] = date('j', $aired_at).' '.$langdate[date('F', $aired_at)].' '.date('Y', $aired_at);
	}

	if( ($released_at = strtotime($res['material_data']['released_at']))!==false && $res['material_data']['released_at'] ){
	    $res['released_at'] = date('j', $released_at).' '.$langdate[date('F', $released_at)].' '.date('Y', $released_at);
	}

	if ($config_kodik['max_actors']) {
	    $res['material_data']['actors'] = array_slice($res['material_data']['actors'], 0, intval($config_kodik['max_actors']));
	}

	if ($config_kodik['max_directors']) {
	    $res['material_data']['directors'] = array_slice($res['material_data']['directors'], 0, intval($config_kodik['max_directors']));
	}

	$request['title_ru']      = $res['title'];
	$request['title_en']      = (!empty($res['title_orig']) ? $res['title_orig'] : '');
	$request['other_title']   = $res['other_title'];
	$request['year']          = $res['year'];
	$request['description']   = html_entity_decode($res['material_data']['description']);
	$request['countries']     = implode(', ', $res['material_data']['countries']);
	$request['genres']        = implode(', ', $res['material_data']['all_genres']);
	$request['actors']        = implode(', ', $res['material_data']['actors']);
	$request['directors']     = implode(', ', $res['material_data']['directors']);
	$request['writers']       = implode(', ', $res['material_data']['writers']);
	$request['producers']     = implode(', ', $res['material_data']['producers']);
	$request['composers']     = implode(', ', $res['material_data']['composers']);
	$request['designers']     = implode(', ', $res['material_data']['designers']);
	$request['editors']       = implode(', ', $res['material_data']['editors']);
	$request['operators']     = implode(', ', $res['material_data']['operators']);
	$request['tagline']       = implode(', ', $res['material_data']['tagline']);
	$request['collection']    = implode(', ', $res['collection']);
	$request['iframe_url']    = $res['link'];
	$request['quality']       = preg_replace('#\s\d+p#', '', $res['quality']);
	$request['translator']    = (!empty($translation)) ? implode(', ', $translation) : '';

	$request['rating_kp']        = $res['material_data']['kinopoisk_rating'];
	$request['kinopoisk_votes']  = $res['material_data']['kinopoisk_votes'];
	$request['rating_imdb']      = $res['material_data']['imdb_rating'];
	$request['imdb_votes']       = $res['material_data']['imdb_votes'];
	$request['rating_world_art'] = $res['material_data']['world_art'];
	$request['mpaa_rating']      = $res['material_data']['mpaa_rating'];
	$request['premiere_world']   = $res['material_data']['premiere_world'];
	$request['premiere_ru']      = $res['material_data']['premiere_ru'];
	$request['released_at']      = $res['released_at'];
	$request['aired_at']         = $res['aired_at'];

	$request['anime_license_name'] = $res['material_data']['anime_license_name'];         
	$request['anime_kind']         = $res['material_data']['anime_kind'];                         
	$request['anime_status']       = $res['material_data']['anime_status'];  
switch ($request['anime_status']) {
    case 'anons':
      $request['anime_status'] = $config_kodik['status_anonsq'];
      break;
    case 'ongoing':
      $request['anime_status'] = $config_kodik['status_ongoingq'];
      break;
    case 'released':
      $request['anime_status'] = $config_kodik['status_releasedq'];
      break;
}                   
	$request['episodes_total']     = $res['material_data']['episodes_total'];                 
	$request['episodes_count']     = $episodes_count;                 
	$request['episodes_aired']     = $res['material_data']['episodes_aired'];                 
	$request['other_titles']       = implode(', ', $res['material_data']['other_titles']);      
	$request['other_titles_en']    = implode(', ', $res['material_data']['other_titles_en']);
	$request['other_titles_jp']    = implode(', ', $res['material_data']['other_titles_jp']);
	$request['anime_genres']       = implode(', ', $res['material_data']['anime_genres']);      
	$request['anime_studios']      = implode(', ', $res['material_data']['anime_studios']);    
	$request['shikimori_rating']   = $res['material_data']['shikimori_rating'];             
	$request['shikimori_votes']    = $res['material_data']['shikimori_votes'];               


	$request['mydramalist_rating'] = $res['material_data']['mydramalist_rating'];
	$request['next_episode_at']    = $res['material_data']['next_episode_at'];
	$request['drama_genres']       = implode(', ', $res['material_data']['drama_genres']);
	$request['mydramalist_votes']  = $res['material_data']['mydramalist_votes'];
	$request['drama_status']       = $res['material_data']['drama_status'];
	$request['aired_at']           = $res['material_data']['aired_at'];
	$request['released_at']        = $res['material_data']['released_at'];
	$request['episodes_aired']     = $res['material_data']['episodes_aired'];


	$request['kinopoisk_id']     = $res['kinopoisk_id'];
	$request['imdb_id']          = $res['imdb_id'];
	$request['mdl_id']           = intval($res['mdl_id']);
	$request['world_art_link']   = $res['worldart_link'];
	$request['shikimori_id']     = $res['shikimori_id'];
	$request['camrip']           = $res['camrip']== true ? 1 :0;

	$request['time']             = $res['material_data']['duration'];

	$request['age']              = $res['material_data']['minimal_age'];

	$request['kodik_id'] = $res['id'];
	$request['mdl_id'] = $res['mdl_id'];


	if($request['title_en']==$request['title']) $request['title_en']='';


	$kadry = [];
	
	if ($res['last_season']) {
		kodik_mass_series($kadry, $row['id'], $res);
	}

	if(count($kadry)){

		$images = $kadry;
		$images = array_diff($images, ['']);
		$images = implode('|||', $images);

		$irow = $db->super_query(" SELECT * FROM " . PREFIX . "_images WHERE news_id='{$row['id']}'");
		
		if( $irow['id'] ) {
			if ($irow['images']) {
				$db->query(" UPDATE " . PREFIX . "_images SET images=CONCAT(images, '|||', '".$images."') WHERE news_id='{$row['id']}'");
			} else {
				$db->query(" UPDATE " . PREFIX . "_images SET images='{$images}' WHERE news_id='{$row['id']}'");
			}
			
		} else {
			$db->query(" INSERT INTO " . PREFIX . "_images (images, news_id, author, date) VALUES ('{$images}', '{$row['id']}', '{$row['autor']}', '".time()."') ");
		}
	}


	$request['episode_plus'] = $res['last_episode']+intval($config_kodik['plus']);
	$request['seasone_plus'] = $res['last_season']+intval($config_kodik['plus']);

	$request['episode_type_1'] = formatize_kodik($res['last_episode'], 4);
	$request['episode_type_2'] = formatize_kodik($res['last_episode'], 5);
	$request['episode_type_3'] = formatize_kodik($res['last_episode'], 6);
	$request['episode_type_4'] = formatize_kodik($res['last_episode'], 7);
	$request['episode_type_5'] = formatize_kodik($res['last_episode'], 8);

	$request['season_type_1'] = formatize_kodik($res['last_season'], 1);
	$request['season_type_2'] = formatize_kodik($res['last_season'], 2);
	$request['season_type_3'] = formatize_kodik($res['last_season'], 3);

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


// print_r($compile['xfields']); 

	$new_xfields = array_diff($compile['xfields'], [' ', '']);
	$new_xfields = array_replace($xfields,$new_xfields);
// print_r($new_xfields); 
// die();
	$xfields = $db->safesql(xfieldsdatasave($new_xfields));









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

	$next_id = $row['id'];

	$last_id = $row['id'];

	$rebuildcount++;

	file_put_contents($log_file, $rebuildcount.'|'.$last_id);
	
}


echo json_encode([
   'status' => 'ok',           
   'next_id' => $next_id,
   'rebuildcount' => $rebuildcount,
]);

clear_cache();

?>