<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	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();

$flip_config = array_flip($config_kodik['xfields']);

$screens_xf = $flip_config['{screenshots}'];
$iframe_xf = $flip_config['{iframe_url}'];
$ads_xf = $flip_config['{camrip}'];

if (isset($_POST['q_search']) ) {

	$q_search = trim($_POST['q_search']);

	if (preg_match('/[^0-9]/', $q_search)) {
		$search_type = 'by_name';
		$res = request('https://kodikapi.com/search?with_material_data=true&token='.$config_kodik['api_token'].'&title='.urlencode($q_search));
	} else {
		$search_type = 'by_kpid';
		$res = request('https://kodikapi.com/search?with_material_data=true&token='.$config_kodik['api_token'].'&kinopoisk_id='.intval($q_search));
	}


	$res = json_decode($res, true);
	// print_r($res);

	if(!count($res['results'])) die('{"error": "нет результатов"}');

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

	$all_ids = [];

	foreach ($res['results'] as $value) {

        $kinopoisk_id = $value['kinopoisk_id'] ? $value['kinopoisk_id'] : 0;
        $shikimori_id = $value['shikimori_id'] ? $value['shikimori_id'] : 0;
        $imdb_id      = $value['imdb_id']      ? $value['imdb_id']      : 0;
        $mdl_id       = $value['mdl_id']       ? $value['mdl_id']       : 0;

        $join_id = sprintf('%s_%s_%s_%s', $kinopoisk_id, $shikimori_id, $imdb_id, $mdl_id);

        if (isset($all_ids[$join_id])) {
            continue;
        }

        $all_ids[$join_id] = 1;

		$src = $value['material_data']['poster_url'] ? $value['material_data']['poster_url'] : 'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=';
		$data[] = '<div class="kodik_item" data-mdl_id="'.$value['mdl_id'].'" data-imdb_id="'.$value['imdb_id'].'" data-kinopoisk_id="'.$value['kinopoisk_id'].'" data-shikimori_id="'.$value['shikimori_id'].'"><div class="aone"><img src="'.$src.'"></div><div class="atwo"><span class="kp-id" title="kinopoisk id"><b>КП: </b>'.$value['kinopoisk_id'].'</span> <div class="title" title="Жми чтобы спарсить">'.$value['title'].'</div><div class="title_origin">'.$value['title_orig'].'</div></div></div>';
	}

	echo json_encode(["ok" => true, "result" => implode("\n", $data)]);

	exit();

}



if ($_POST['action']=='update') {

	$res = request('https://kodikapi.com/search?with_material_data=true&token='.$config_kodik['api_token'].'&kinopoisk_id='.intval($_POST['id_kp']));

	$type = $_POST['type'];

	$res = json_decode($res, true);
    

	if(!count($res['results'])) die('{"error": "нет результатов"}');

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

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


	if ($type=='iframe') {
		die('{"ok": "'.$res['link'].'"}');
	} elseif ($type=='trailer' and $res['data']['iframe_trailer']) {
		die('{"ok": "'.$res['data']['iframe_trailer'].'"}');	
	} else {
		die('{"error": "нет iframe"}');
	}


}





if ($_POST['action']=='parse') {

	if (!empty($_POST['shikimori_id'])) {
		
		$resUri = 'https://kodikapi.com/search?with_material_data=true&with_episodes_data=true&token='.$config_kodik['api_token'].'&shikimori_id='.$_POST['shikimori_id'];
	
	} elseif (!empty($_POST['kinopoisk_id'])) {

		$resUri = 'https://kodikapi.com/search?with_material_data=true&with_episodes_data=true&token='.$config_kodik['api_token'].'&kinopoisk_id='.intval($_POST['kinopoisk_id']);

	}  elseif (!empty($_POST['imdb_id'])) {
		
		$resUri = 'https://kodikapi.com/search?with_material_data=true&with_episodes_data=true&token='.$config_kodik['api_token'].'&imdb_id='.$_POST['imdb_id'];
	
	}   elseif (!empty($_POST['mdl_id'])) {
		
		$resUri = 'https://kodikapi.com/search?with_material_data=true&with_episodes_data=true&token='.$config_kodik['api_token'].'&mdl_id='.$_POST['mdl_id'];
	
	} else {

		$resUri = 'https://kodikapi.com/search?with_material_data=true&with_episodes_data=true&token='.$config_kodik['api_token'].'&title='.urlencode($_POST['name']);

	}

	$res = request($resUri);

	$res = json_decode($res, true);

	if(!count($res['results'])) die('{"error": "нет результатов"}');

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

	$result = $res;

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

	$res = $res['results'][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 = $res['material_data']['anime_kind'];

	$anime_status = $res['material_data']['all_status'];
	switch ($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;
	} 

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

	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;
	}

	if ($config_kodik['ongoing_cat'] && $res['material_data']['anime_status'] == 'ongoing') {
		$cats[] = $config_kodik['ongoing_cat'];
	}

	$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(', ', (array) $res['material_data']['countries']);
	$request['genres']        = implode(', ', (array) $res['material_data']['all_genres']);
	$request['actors']        = implode(', ', (array) $res['material_data']['actors']);
	$request['directors']     = implode(', ', (array) $res['material_data']['directors']);
	$request['writers']       = implode(', ', (array) $res['material_data']['writers']);
	$request['producers']     = implode(', ', (array) $res['material_data']['producers']);
	$request['composers']     = implode(', ', (array) $res['material_data']['composers']);
	$request['designers']     = implode(', ', (array) $res['material_data']['designers']);
	$request['editors']       = implode(', ', (array) $res['material_data']['editors']);
	$request['operators']     = implode(', ', (array) $res['material_data']['operators']);
	$request['tagline']       = implode(', ', (array) $res['material_data']['tagline']);
	$request['collection']    = implode(', ', (array) $res['collection']);
	$request['iframe_url']    = $res['link'];
	$request['quality']       = preg_replace('#\s\d+p#', '', $res['quality']);
	$request['translator']    = (!empty($translation)) ? implode(', ', (array) $translation) : '';

	$request['kinopoisk_rating'] = $res['material_data']['kinopoisk_rating'];
	$request['kinopoisk_votes']  = $res['material_data']['kinopoisk_votes'];
	$request['imdb_rating']      = $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['episodes_total']     = $res['material_data']['episodes_total'];                 
	$request['episodes_count']     = $episodes_count;                 
	$request['episodes_aired']     = $res['material_data']['episodes_aired'];                 
	$request['other_titles']       = implode(', ', (array) $res['material_data']['other_titles']);      
	$request['other_titles_en']    = implode(', ', (array) $res['material_data']['other_titles_en']);
	$request['other_titles_jp']    = implode(', ', (array) $res['material_data']['other_titles_jp']);
	$request['anime_genres']       = implode(', ', (array) $res['material_data']['anime_genres']);      
	$request['anime_studios']      = implode(', ', (array) $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(', ', (array) $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'];


	$news_id = intval($_POST['news_id']);
	$author = isset($_POST['author']) ? $_POST['author'] : $member_id['name'];
	$author = $db->safesql($author);


	$screenshots = [];

	if ($screens_xf) {
		$screenshots = upload_screenshots($res, $_POST['id_kp']);

		if(count($screenshots)) {
			$request['screenshots'] = implode(',', $screenshots);
		}
	}



	$kadry = [];
	
	if ($news_id && $res['last_season']) {
		set_time_limit(0);
		kodik_mass_series($kadry, $news_id, $res);
	}


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

	if ($config_kodik['upload_poster']) {
		// $poster_file = ($_POST['id_kp'] ? $_POST['id_kp'] : uniqid()).'_'.time();
		// $poster = request($res['material_data']['poster_url'], ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX.'/' .$poster_file);
		// if($poster){
		//     $request['poster'] = str_replace(ROOT_DIR.'/' , $config['http_home_url'], $poster);
		//     $poster = str_replace(ROOT_DIR."/uploads/posts/" , '', $poster);
		// }

		$kpIdAlter = $_POST['id_kp'] ? $_POST['id_kp'] : uniqid();

		$poster = upload_poster($res, $kpIdAlter);

	    if($poster){
	        $request['poster'] = str_replace(ROOT_DIR , '', $poster);
	        $poster = str_replace(ROOT_DIR."/uploads/posts/" , '', $poster);
	    }

	} else {
		$request['poster'] = $res['material_data']['poster_url'];
	}



	if($poster or count($screenshots) or count($kadry)){

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

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

	if (!empty($config_kodik['metatitle'])) {
	    $compile['meta_title'] = check_if_kodik($compile['metatitle'],$request);
	    $compile['meta_title'] = preg_replace('/\s{2,}/', ' ',  $compile['meta_title']);
	}



	if(count($screenshots)){
		$xf_screen = [];
		foreach ($screenshots as $value) {
			$file_info = pathinfo($value);
			$info = $file_info['basename'];
			$xf_screen[] = $value;
			$md5 = md5($value);
			$md5field = md5($screens_xf);
			$screns .= <<<HTML
<div id="xf_{$md5}" data-id="{$value}" data-alt="" class="uploadedfile"><div class="info">{$info}</div><div class="uploadimage"><img style="width:auto;height:auto;max-width:100px;max-height:90px;" src="/uploads/posts/{$value}"></div><div class="info"><a href="#" onclick="xfaddalt('{$md5}', '{$screens_xf}');return false;">Описание</a><br><a href="#" onclick="xfimagegalerydelete_{$md5field}('{$screens_xf}','{$value}', '{$md5}');return false;">Удалить</a></div></div>			
HTML;
}

	$compile['xfields'][$screens_xf] = implode(',', $xf_screen);
	$compile['xfields']['screens_xf'] = $screns;

	}
	



	unset($compile['api_token'], $compile['allow_year']);
	unset($compile['metatitle'], $compile['lickey'],$compile['api_token']);

	echo json_encode(['ok' => true, 'result' => $compile]);

	exit();
}





?>




<script type="text/javascript">
$(function(){
	var regexp = /id=(\d+)/;
	var href = window.location.href;
	var news_id = regexp.test(href) ? href.match(regexp)[1] : 0;
	var author = $("input[name='old_author']").val();
	var ads_xf = '<?= $ads_xf; ?>';
	var iframe_xf = '<?= $iframe_xf; ?>';
	$('#related_news').before('<div id="kodik_btns"></div>');
    $('#kodik_btns').append('<button id="kodik_parse" class="btn btn-green btn-sm btn-raised legitRipple bg-info-800">Искать в базе kodik</button>&nbsp;');
    $('#xf_'+iframe_xf).after('<br><button data-type="iframe" type="button" class="upd-iframe btn bg-slate-600 btn-sm btn-raised position-left legitRipple">Обновить kodik плеер</button>');
    $(document).on("click", "#kodik_parse", function(){
        var btn = $(this);
        btn.attr("disabled", "disabled").text('Ждем...');
        var q_search = $('#title').val();
        $.post("?mod=kodik_grabber", {q_search:q_search,news_id:news_id,author:author}, function(data){
            if(data.error) {
            	Growl.info({
            	    title: 'Информация',
            	    text: data.error
            	});
            }
            if(data.ok){
				$("#kodik_results").remove();
                $("body").append("<div id='kodik_results' title='Результаты поиска' style='display:none'>"+data.result+"</div>");
                var b = {};
                b["Закрыть"] = function() {
                    $(this).dialog("close")
                };
                $("#kodik_results").dialog({
                    autoOpen: 1,
                    width: 600,
                    height: 400,
                    resizable: !1,
                    buttons: b
                });                
            }
            btn.removeAttr("disabled").text('Искать в базе kodik');
        },"json");
        return false;
    })
    .on("click", ".kodik_item", function(){
    	ShowLoading('');
    	$("#kodik_results").remove();
        var t = $(this), kinopoisk_id = t.data('kinopoisk_id'), shikimori_id = t.data('shikimori_id'), imdb_id = t.data('imdb_id'), mdl_id = t.data('mdl_id'), name = t.find('.title').text(), poster = $('xf_poster').val() || $('[name="xfield[poster]"]').val();
        $.post("?mod=kodik_grabber", {action: 'parse', kinopoisk_id: kinopoisk_id, shikimori_id:shikimori_id, imdb_id:imdb_id, mdl_id:mdl_id, name:name, news_id:news_id,author:author, poster:poster}, function(data){
        	HideLoading('');
            if(data.error) {
            	Growl.info({
            	    title: 'Информация',
            	    text: data.error
            	});
            }
            if(data.result){
                $.each(data.result, function(key,val) {
                	$('[name="'+key+'"]').val(val);
                	if($.inArray(key, ['tags', 'keywords'] )>-1) {
                		$('[name="'+key+'"]').tokenfield('setTokens', val);
                	}
                	if($('#'+key).attr('data-rel')=='links'){
                		$('#'+key).tokenfield('setTokens', val);
                	}
                	if ( key == "short_story" || key == "full_story" ) {
                		if (typeof $.fn.froalaEditor != 'undefined') {
                			$('#' + key).froalaEditor('html.set', val);
                		} else $('#' + key);
                	}
                });
                $.each(data.result['xfields'], function(key,val) {
                	if(key=='screens_xf') {
                		$('#uploadedfile_<?=$screens_xf ?>').html(val)
                	}
                	else if($('#xf_'+key).attr('data-rel')=='links'){
                		$('#xf_'+key).tokenfield('setTokens', val);
                	} else {
                		$('#xf_'+key).val(val)
                	}
                });
                var cats = data.result['category'].split(',');
                var opt = $('#category option');
                opt.each(function(indx, element){
                    $(this).removeAttr('selected');
                });
                for (var i = 0; i < cats.length; i++) {
                    opt.each(function(indx, element){
	                    var o = $(this).val();
	                    if ( $.trim(o) == $.trim(cats[i] ) ) {$(this).prop("selected", true).trigger("liszt:updated").trigger("chosen:updated");;}
                    });
                }
                
                if (!ads_xf) return;
                var ads = $('[name="xfield['+ads_xf+']"]'), is_ads = ads.prop('checked');  
                if (data.result['xfields'][ads_xf] == '1') {
                	if (!is_ads) ads.trigger('click');
                } else {
                	if (is_ads) ads.trigger('click');
                }
            }
        },"json");
        return false;
    })
    .on("click", ".upd-iframe", function(){
    	var id_kp = $('#xf_kinopoisk_id').val();
    	var shikimori_id = $('#xf_shikimori_id').val();

    	if (!id_kp) {
    		Growl.error({
    			title: 'Error',
    			text: 'Нужен kinopoisk id'
    		});
    		return;
    	}
    	var t = $(this); t.attr("disabled", "disabled").text('Ждем...');

    	var type = t.data('type');

		$.post('?mod=kodik_grabber',{action:'update', type:type, id_kp:id_kp, shikimori_id:shikimori_id}, function(d){
			if (d.ok) {
				t.parent().find('input').val(d.ok)
			} else {
				Growl.error({
					title: 'Error',
					text: d.error
				});
			}
			t.removeAttr("disabled").text(type=='iframe' ? 'Обновить kodik плеер' : 'Обновить kodik трейлер');
		}, 'json');
    })
});
</script>


<style>
.atwo {
	padding-left: 10px;
    flex-grow: 1;
    position: relative;
}
.title_origin {
    font-size: 13px;
    color: #7c7f8a;
}
.kodik_item .kp-id {
    font-size: 12px;
    color: cadetblue;
    display: inline-block;
    position: absolute;
    right: 0;
    bottom: 0;
}
#kodik_results {
	counter-reset: li;
}
.kodik_item {
	display: flex;
    cursor: pointer;
    font-size: 15px;
    margin-bottom: 4px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    background: #f7f7f7;
    padding: 6px 6px;
    border-radius: 5px;
}
.kodik_item:hover {
	color: yellowgreen;
}
.kodik_item img {
    width: 90px;
    height: 130px;
    object-fit: cover;
}
.kodik_item:before {
    content: counter(li);
    display: inline-block;
    height: 28px;
    width: 28px;
    border: 3px solid yellowgreen;
    margin-right: 8px;
    counter-increment: li;
    text-align: center;
    border-radius: 20px;
    line-height: 1.7;
    font-size: 12px;
}
</style>