<?php

@error_reporting ( E_ALL ^ E_WARNING ^ E_NOTICE );
@ini_set ( 'display_errors', true );
@ini_set ( 'html_errors', false );
@ini_set ( 'error_reporting', E_ALL ^ E_WARNING ^ E_NOTICE );

define( 'DATALIFEENGINE', true );
define( 'ROOT_DIR', substr( dirname(  __FILE__ ), 0, -13 ) );
define( 'ENGINE_DIR', ROOT_DIR . '/engine' );

if(file_exists(ENGINE_DIR .'/data/cron.job')){
    if( (time()-filectime(ENGINE_DIR .'/data/cron.job'))>3) {
        unlink(ENGINE_DIR .'/data/cron.job');
        file_put_contents(ENGINE_DIR .'/data/cron.job', '');
    } else die('dubl cron');
} else {
    file_put_contents(ENGINE_DIR .'/data/cron.job', '');
}

include ENGINE_DIR . '/data/config.php';

require_once (ENGINE_DIR . '/classes/plugins.class.php');

date_default_timezone_set ( $config['date_adjust'] );

require_once ENGINE_DIR . '/classes/mysql.php';
require_once ENGINE_DIR . '/data/dbconfig.php';
require_once ENGINE_DIR . '/modules/functions.php';
include_once ENGINE_DIR . '/classes/composer/vendor/autoload.php';
include_once ENGINE_DIR . '/classes/thumb.class.php';

@include_once ROOT_DIR . '/language/' . $config['langs'] . '/website.lng';


ini_set("memory_limit","512M");
ini_set('max_execution_time',600);
ignore_user_abort(true);
set_time_limit(600);
session_write_close();




$_TIME = time();

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


if ( !$config['allow_cache'] ) $config['allow_cache'] = 1;

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


$secret_key = $config_kodik['secret_key'];


if (!$secret_key) {
    die('secret key is required');
}

if ($_GET['secret_key'] != $secret_key) {
    die('bad secret key');
}

check_license_kodik();


if ( isset($_GET['type']) ) {

    $url = $film_sort_by = $allow_year = $allow_country = $translations = $translation_type = $grab_camrip = $not_blocked_in = $genres = $mpaa_rating = $minimal_age = $all_status = $kinopoisk_rating = $imdb_rating = $shikimori_rating = $mydramalist_rating = '';
    $ex_time = time()-2*24*3600;
    $db->query( "UPDATE " . PREFIX . "_kodik SET status=1, err_time='0' WHERE (err_time>'0' AND err_time<'$ex_time')" );

    $type = $_GET['type'];

    if ($config_kodik['film_sort_by']) {
        $film_sort_by = '&sort='.$config_kodik['film_sort_by'];
    }

    if ($config_kodik['allow_year']) {
        $allow_year = '&year='.implode(',', $config_kodik['allow_year']);
    }

    if ($config_kodik['allow_country']) {
        $allow_country = '&countries='.urlencode(implode(',', $config_kodik['allow_country']));
    }

    if ($config_kodik['translations']) {
        $translations = '&translation_id='.urlencode(implode(',', $config_kodik['translations']));
    }

    if ($config_kodik['translation_type']) {
        $translation_type = '&translation_type='.urlencode($config_kodik['translation_type']);
    }

    if ($config_kodik['grab_camrip']) {
        $grab_camrip = '&grab_camrip='.urlencode($config_kodik['grab_camrip']);
    }

    if ($config_kodik['not_blocked_in']) {
        $not_blocked_in = '&not_blocked_in='.urlencode(implode(',', $config_kodik['not_blocked_in']));
    }

    if ($config_kodik['genres']) {
        $genres = '&all_genres='.urlencode(implode(',', $config_kodik['genres']));
    }

    if ($config_kodik['mpaa_rating']) {
        $mpaa_rating = '&mpaa_rating='.urlencode(implode(',', $config_kodik['mpaa_rating']));
    }

    if ($config_kodik['minimal_age']) {
        $minimal_age = '&minimal_age='.$config_kodik['minimal_age'];
    }

    if ($config_kodik['all_status']) {
        $all_status = '&all_status='.implode(',', $config_kodik['all_status']);
    }

    if ($config_kodik['kinopoisk_rating']) {
        $kinopoisk_rating = '&kinopoisk_rating='.$config_kodik['kinopoisk_rating'];
    }

    if ($config_kodik['imdb_rating']) {
        $imdb_rating = '&imdb_rating='.$config_kodik['imdb_rating'];
    }

    if ($config_kodik['shikimori_rating']) {
        $shikimori_rating = '&shikimori_rating='.$config_kodik['shikimori_rating'];
    }

    if ($config_kodik['mydramalist_rating']) {
        $mydramalist_rating = '&mydramalist_rating='.$config_kodik['mydramalist_rating'];
    }

    if($config_kodik['add_film'] && $type=='film'){
        $url = 'https://kodikapi.com/list?limit=100&token='.$config_kodik['api_token'].'&types=russian-movie,foreign-movie';
    } 
    elseif($config_kodik['add_serial'] && $type=='serial'){
        $url = 'https://kodikapi.com/list?limit=100&token='.$config_kodik['api_token'].'&types=russian-serial,foreign-serial,multi-part-film';
    }
    elseif($config_kodik['add_anime'] && $type=='anime'){
        $url = 'https://kodikapi.com/list?limit=100&token='.$config_kodik['api_token'].'&types=anime';
    }
    elseif($config_kodik['add_mult'] && $type=='mult'){
        $url = 'https://kodikapi.com/list?limit=100&token='.$config_kodik['api_token'].'&types=soviet-cartoon,foreign-cartoon,russian-cartoon';
    }
    elseif($config_kodik['add_multserial'] && $type=='multserial'){
        $url = 'https://kodikapi.com/list?limit=100&token='.$config_kodik['api_token'].'&types=cartoon-serial,russian-cartoon-serial';
    }
    elseif($config_kodik['add_animeserial'] && $type=='animeserial'){
        $url = 'https://kodikapi.com/list?limit=100&token='.$config_kodik['api_token'].'&types=anime-serial';
    }    

    if(!$url) die('choise video type. film serial mult or anime');

    include ENGINE_DIR . '/kodik/class.php';
    $kodik = new Kodik($type, $db, $config_kodik);
    $kodik->start($url.$kinopoisk_rating.$imdb_rating.$mydramalist_rating.$shikimori_rating.$film_sort_by.$allow_year.$allow_country.$translations.$translation_type.$grab_camrip.$not_blocked_in.$genres.$mpaa_rating.$minimal_age.$all_status);

    die('Insert and update data');
}






if (isset($_GET['last'])) {

    $kp_ids = [];

    $xf_config = array_map(function($el) {
        return str_replace(['{', '}'], '', $el);
    }, $config_kodik['xfields']);

    $status_cats = [];
    foreach ($config_kodik['category'] as $cat_id => $value) {
        if (in_array($value[0], ['ongoing', 'released', 'anons'])) {
            $status_cats[$value[0]] = $cat_id;
        }
    }

    $xf_config = array_flip($xf_config);

    $response = request("https://kodikapi.com/list?token={$config_kodik['api_token']}&with_episodes_data=true&sort=updated_at&with_material_data=true");

    $response = json_decode($response, true);
//print_r($response);die();
    if (!$response) {
        die('bad data');
    }

    foreach ($response['results'] as $result) {

        $imdb_id = $result['imdb_id'] ? $result['imdb_id'] : 1;
        $mdl_id = $result['mdl_id'] ? $result['mdl_id'] : 1;
        $kinopoisk_id = $result['kinopoisk_id'] ? $result['kinopoisk_id'] : 1;

        $shikimori_id = $result['shikimori_id'] ? $result['shikimori_id'] : '';

        $kinopoisk_id_shikimori_id = ! empty ($shikimori_id)
        ? $kinopoisk_id . '_' . $shikimori_id : $kinopoisk_id;

        if (isset($kp_ids[$kinopoisk_id_shikimori_id])) {
            continue;
        }

        $kp_ids[$kinopoisk_id_shikimori_id] = 1;
            
        $post_row = $db->super_query( "SELECT id, autor, title, category, xfields FROM " . PREFIX . "_post 
            WHERE 
                xfields REGEXP 'kinopoisk_id[|]{$kinopoisk_id}([|]|$)'
        " );

        if (!$post_row) {
            $post_row = $db->super_query( "SELECT id, autor, title, category, xfields FROM " . PREFIX . "_post 
                WHERE
                    xfields REGEXP 'shikimori_id[|]{$shikimori_id}([|]|$)'
            " );
        }

        if (!$post_row) {
            $post_row = $db->super_query( "SELECT id, autor, title, category, xfields FROM " . PREFIX . "_post WHERE xfields REGEXP 'imdb_id[|]{$imdb_id}([|]|$)'" );
        }

        if (!$post_row) {
            $post_row = $db->super_query( "SELECT id, autor, title, category, xfields FROM " . PREFIX . "_post WHERE xfields REGEXP 'mdl_id[|]{$mdl_id}([|]|$)'" );
        }


        if (!$post_row) {
            echo "{$result['title']} --- {$result['title_orig']} --- kp_id {$kinopoisk_id}";
            echo ' --- <span style="color:red;"'.">not found</span><br>\n";
            continue;
        }

        $news_id = $post_row['id'];

        if (preg_match('#[[:<:]](0|0|0)[[:>:]]#', $post_row['category'])) {
            continue;
        }


        echo "{$result['title']} --- {$result['title_orig']} --- kp_id {$kinopoisk_id}";


        $xfields = xfieldsdataload( $post_row['xfields'] );



        $update_news = false;
        $new_date = false;
        $es_result = [];

        $last_season = isset($xfields[$xf_config['last_season']]) ? $xfields[$xf_config['last_season']] : '';
        $last_episode = isset($xfields[$xf_config['last_episode']]) ? $xfields[$xf_config['last_episode']] : '';

        if ($xfields[$xf_config['quality']]!=$result['quality']) {
            $update_news = true;
            $xfields[$xf_config['quality']]=$result['quality'];
            $config_kodik['update_if_quality'] && ($new_date = true);
        }


        if ($xfields[$xf_config['trailer']]!=$result['link']) {
            $update_news = true;
            $xfields[$xf_config['trailer']] = $result['link'];
        }

        if ($xfields[$xf_config['instream_ads']]!=$result['camrip']) {
            $update_news = true;
            $xfields[$xf_config['instream_ads']] = $result['camrip'];
        }


        $anime_status = $result['material_data']['all_status'];


        $cat_arr = explode(',', $post_row['category']);


        if ($xfields[$xf_config['all_status']] != $anime_status) {
            $cat_arr = array_diff($cat_arr, array_values($status_cats));
            $cat_arr[] = $status_cats[$anime_status];
            $update_news = true;
        }

        switch ($anime_status) {
            case 'anons':
              $xfields[$xf_config['anime_status']] = $config_kodik['status_anonsq'];
              break;
            case 'ongoing':
              $xfields[$xf_config['anime_status']] = $config_kodik['status_ongoingq'];
              break;
            case 'released':
              $xfields[$xf_config['anime_status']] = $config_kodik['status_releasedq'];
              break;
        } 

 

        if ($config_kodik['trailer_cat'] && in_array($config_kodik['trailer_cat'], $cat_arr)) {
            $cat_arr = array_diff($cat_arr, [$config_kodik['trailer_cat']]);
            $update_news = true;
        }

 


        if (!empty($result['last_episode'])) {

            if ($result['last_episode']>$last_episode or $result['last_season']>$last_season) {
                $update_news = true;
                $xfields[$xf_config['last_episode']]=$result['last_episode'];
                $xfields[$xf_config['last_season']]=$result['last_season'];
                ($config_kodik['update_if_seasone'] or $config_kodik['update_if_quality']) && ($new_date = true);
            }


            $kadry = [];
            
            if ($news_id && $result['last_season']) {
                
                $serials = [];
                foreach ($result['seasons'] as $sez => $serArr) {
                    foreach ($serArr['episodes'] as $ser => $serArr) {
                        $serials[$sez][$ser] = $serArr['screenshots'][0];
                    }
                }
                kodik_mass_series($kadry, $news_id, $result);
            }


            if(count($kadry)){

                $images = implode('|||', $kadry);

                $row = $db->super_query(" SELECT * FROM " . PREFIX . "_images WHERE news_id='{$news_id}' AND author='{$post_row['autor']}' ");
                
                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}', '{$post_row['autor']}', '".time()."') ");
                }
            }


            $xfields[$xf_config['episode_plus']] = $es_result['episode_plus'] = $result['last_episode']+intval($config_kodik['plus']);
            $xfields[$xf_config['seasone_plus']] = $es_result['seasone_plus'] = $result['last_season']+intval($config_kodik['plus']);

            $xfields[$xf_config['episode_type_1']] = $es_result['episode_type_1'] = formatize_kodik($result['last_episode'], 4);
            $xfields[$xf_config['episode_type_2']] = $es_result['episode_type_2'] = formatize_kodik($result['last_episode'], 5);
            $xfields[$xf_config['episode_type_3']] = $es_result['episode_type_3'] = formatize_kodik($result['last_episode'], 6);
            $xfields[$xf_config['episode_type_4']] = $es_result['episode_type_4'] = formatize_kodik($result['last_episode'], 7);
            $xfields[$xf_config['episode_type_5']] = $es_result['episode_type_5'] = formatize_kodik($result['last_episode'], 8);

            $xfields[$xf_config['season_type_1']] = $es_result['season_type_1'] = formatize_kodik($result['last_season'], 1);
            $xfields[$xf_config['season_type_2']] = $es_result['season_type_2'] = formatize_kodik($result['last_season'], 2);
            $xfields[$xf_config['season_type_3']] = $es_result['season_type_3'] = formatize_kodik($result['last_season'], 3);
            
        }


        if ($update_news) {

            $xfields[$xf_config['iframe_url']]=$result['link'];

            $xfields = array_diff($xfields, ['']);

            $date = '';

            if ($new_date) {
                $date = date('Y-m-d H:i:s', $_TIME);
                $date = "date='$date',";
            }

         

            $compile = template($config_kodik, [
                'title_ru' => $result['title'],
                'title_en' => $result['title_orig'],
                'year' => $result['year'],
            ]); 

            $es_type = ['episode_plus', 'seasone_plus', 'episode_type_1', 'episode_type_2', 'episode_type_3', 'episode_type_4', 'episode_type_5', 'season_type_1', 'season_type_2', 'season_type_3'];


            foreach ($es_type as $key => $value) {
                if (!isset($xf_config[$value])) {
                    unset($xfields[$xf_config[$value]]);
                }
            }

            

            if (!empty($config_kodik['metatitle'])) {
                $compile['metatitle'] = check_if_kodik($compile['metatitle'], $es_result);
                $compile['metatitle'] = preg_replace('/\s{2,}/', ' ',  $compile['metatitle']);
                $metatitle = ", metatitle='".$db->safesql($compile['metatitle'])."'";
            } else {
                $metatitle = '';
            }
            

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

            $category = implode(',', $cat_arr);

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


            if ($result['last_episode'] and $rewrite_meta_resone) {
                $reason = "{$result['last_season']} сезон {$result['last_episode']} $series серия - ".date('d.m.Y');
            } else {
                $reason = $result['quality'];
            }
            


            $db->query("UPDATE " . PREFIX . "_post_extras SET editdate = '$_TIME', reason='$reason' WHERE news_id = '{$post_row['id']}'");

            echo ' --- <span style="color:green;"'.">updated</span><br>\n";


        }

        else {
            echo ' --- <span style="color:red;"'.">no updated</span><br>\n";
        }
//die();
    }


exit();

}









$and = [];
if($config_kodik['add_film'])         $and[] = "'russian-movie','foreign-movie'";
if($config_kodik['add_serial'])       $and[] = "'russian-serial','foreign-serial','multi-part-film'";
if($config_kodik['add_anime'])        $and[] = "'anime'";
if($config_kodik['add_mult'])         $and[] = "'soviet-cartoon','russian-cartoon','foreign-cartoon'";
if($config_kodik['add_multserial'])   $and[] = "'cartoon-serial','russian-cartoon-serial'";
if($config_kodik['add_animeserial'])  $and[] = "'anime-serial'";

if(count($and)) $and = "AND type IN(".implode(", ", $and).")";
else $and = '';

if($config_kodik['first_new']){
    $kodik = $db->super_query( "SELECT * FROM " . PREFIX . "_kodik WHERE news_id=0 $and ORDER BY `year` DESC, `status` ASC" );
}
else {
    $kodik = $db->super_query( "SELECT * FROM " . PREFIX . "_kodik WHERE news_id=0 $and ORDER BY `status` ASC" );
}

if (!$kodik) {
    die('no rows');
}

$sqlQuery = "SELECT id, title FROM " . PREFIX . "_post WHERE ";

$sqlWhere = [];

if ($kodik['kp_id']) {
    $sqlWhere[] = "xfields REGEXP 'kinopoisk_id[|]{$kodik['kp_id']}([|]|$)'"; 
}
if ($kodik['shikimori_id']) {
    $sqlWhere[] = "xfields REGEXP 'shikimori_id[|]{$kodik['shikimori_id']}([|]|$)'"; 
}
if ($kodik['mdl_id']) {
    $sqlWhere[] = "xfields REGEXP 'mdl_id[|]{$kodik['mdl_id']}([|]|$)'"; 
}

if (count($sqlWhere)) {
    $post_row = $db->super_query($sqlQuery.implode(' OR ', $sqlWhere));
} else {
    $post_row = null;
}


if ($post_row) {
    $db->query( "UPDATE " . PREFIX . "_kodik SET news_id='{$post_row['id']}' WHERE id='{$kodik['id']}'" );
    die("news exists --- {$post_row['id']} --- {$post_row['title']}");
}



if($config_kodik['blacklist']){
    $blacklist = explode("\n", $config_kodik['blacklist']);
    if(in_array($kodik['kp_id'], $blacklist) and $kodik['kp_id']) {
        $db->query( "UPDATE " . PREFIX . "_kodik SET status=0, err_time='$_TIME' WHERE id='{$kodik['id']}'" );
        die("in blacklist --- kinopoisk_id --- {$kodik['kp_id']}");    
    }
}

$whereID = [];

if ($kodik['kp_id']) {
    $whereID[] = 'kinopoisk_id='.$kodik['kp_id'];
}
if ($kodik['shikimori_id']) {
    $whereID[] = 'shikimori_id='.$kodik['shikimori_id'];
}
if ($kodik['mdl_id']) {
    $whereID[] = 'mdl_id='.$kodik['mdl_id'];
}

$whereID = implode('&', $whereID);

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


if (preg_match('#"episodes_count"\s*:\s*(\d+)#', $result, $find)) {
	$episodes_count = $find[1];
} else {
	$episodes_count = '';
}

$res = json_decode($result, true);

$result = $res;

if(!$res or empty($res['results'])) {
    $db->query( "UPDATE " . PREFIX . "_kodik SET status=0, err_time='$_TIME' WHERE id='{$kodik['id']}'" );
    die($result." --- $id");    
}


if ($config_kodik['not_add_if_no_poster'] AND empty($result['poster_url'])) {
    $db->query( "UPDATE " . PREFIX . "_kodik SET news_id='1' WHERE id='{$kodik['id']}'" );
    die("the news has no poster");
}


if ($config_kodik['not_add_if_no_descr'] AND empty($result['description'])) {
    $db->query( "UPDATE " . PREFIX . "_kodik SET news_id='2' WHERE id='{$kodik['id']}'" );
    die("the news has no description");
}


$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];

if($config_kodik['disallow_year'] && in_array(intval($res['year']), $config_kodik['disallow_year'])){
    $db->query( "UPDATE " . PREFIX . "_kodik SET status=0, err_time='$_TIME' WHERE id='{$kodik['id']}'" );
    die('not allowed year');
}


if(disallow_country((array)$res['material_data']['countries'], (array)$config_kodik['disallow_country'])) {
    $db->query( "UPDATE " . PREFIX . "_kodik SET status=0, err_time='$_TIME' WHERE id='{$kodik['id']}'" );
    die('disallow countryes');
}



$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'];
}

$flip_config = array_map(function($el) {
    return str_replace(['{', '}'], '', $el);
}, $config_kodik['xfields']);

$flip_config = array_flip($flip_config);

$screens_xf = $flip_config['screenshots'];


$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['kodik_id']         = $res['id'];
$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['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);



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

//print_r($request);
// die();

$screenshots = [];
$poster = '';


if(!$kodik['news_id']){

    $poster = upload_poster($res, $kodik['kp_id']);

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

    if ($screens_xf) {
        $screenshots = upload_screenshots($res, $kodik['kp_id']);

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

}

else {

	foreach ($request as $key => $value) {
		if(!$xfdata[$key]) $xfdata[$key] = $request[$key];
	}

	$xfdata['episodes_count'] = $request['episodes_count'];
	$xfdata['anime_status']   = $request['anime_status'];
	$xfdata['episodes_count'] = $request['episodes_count'];
	$xfdata['episodes_total'] = $request['episodes_total'];
	$xfdata['episodes_aired'] = $request['episodes_aired'];

	if (empty($xfdata['screenshots']) && $screens_xf) {

		$screenshots = upload_screenshots($res, $kodik['kp_id']);

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

	if (empty($xfdata['poster'])) {

		$poster = upload_poster($res, $kodik['kp_id']);

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

	$request = $xfdata;
}


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

// print_r($compile);
// die();

if($compile['category']=='') $compile['category']=0;

$compile['metatitle'] = check_if_kodik($compile['metatitle'], $request);
$compile['metatitle'] = preg_replace('/\s{2,}/u', ' ',  $compile['metatitle']);


$compile['xfields'] = xfcompile($compile['xfields']);
$compile['alt_name'] = totranslit( stripslashes( $compile['alt_name'] ), true, false );
$compile['date'] = date('Y-m-d H:i:s');


$compile['short_story'] = $compile['short_story'] ? $compile['short_story'] : '';
$compile['full_story']  = $compile['full_story']? $compile['full_story'] : '';
$compile['keywords']    = $compile['keywords'] ? $compile['keywords'] : '';
$compile['metatitle']   = $compile['metatitle'] ? $compile['metatitle'] : '';
$compile['descr']       = $compile['descr'] ? $compile['descr'] : '';

$approve = (!empty($config_kodik['go_moder']) && (bool)$config_kodik['go_moder'] === true) ? 0 : 1;

if (!empty($config_kodik['go_moder_empty_descr'])
    && (bool)$config_kodik['go_moder_empty_descr'] === true
    && empty(trim($request['description']))
) {
    $approve = 0;
}

if (!empty($config_kodik['go_moder_empty_poster'])
    && (bool)$config_kodik['go_moder_empty_poster'] === true
    && !$poster 
) {
    $approve = 0;
}

$disable_index = 0;
if (!empty($config_kodik['disable_index'])
    && (bool)$config_kodik['disable_index'] === true
) {
    $disable_index = 1;
}

$updateNewsDate = false;
if (!empty($config_kodik['update_news_date'])
    && (bool)$config_kodik['update_news_date'] === true
) {
    $updateNewsDate = true;
}

    $db->query(db_query("INSERT INTO `" . PREFIX . "_post` (`autor`, `date`, `short_story`, `full_story`, `xfields`, `title`, `descr`, `keywords`, `category`, `alt_name`, `comm_num`, `allow_comm`, `allow_main`, `approve`, `fixed`, `allow_br`, `symbol`, `tags`, `metatitle`) VALUES ('kodik', :date, :short_story, :full_story, :xfields, :title, :descr, :keywords, :category, :alt_name, 0, 1, 1, $approve, 0, 0, '', :tags, :metatitle);", $compile));

    $news_id = $db->insert_id();
    $db->query( "INSERT INTO " . PREFIX . "_post_extras (news_id,user_id,disable_index) VALUES('$news_id','1', '$disable_index')" );


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

    if($poster or count($screenshots) or count($kadry)){
    	$images = array_merge([$poster], $screenshots, $kadry);
    	$images = array_diff($images, ['']);
    	$images = implode('|||', $images);
        $db->query( "INSERT INTO " . PREFIX . "_images (images,news_id,author,date) VALUES('{$images}','$news_id','kodik','{$_TIME}')" );
    }


    $quality = $request['quality'];
    $db->query("UPDATE " . PREFIX . "_kodik SET status = '0', news_id = '$news_id', episode='$sum', quality='$quality' WHERE id = '{$kodik['id']}'");

    echo "insert news --- $news_id --- {$res['title']}";



if(version_compare('13.2', $config['version_id'], '<=') && !$kodik['news_id']){
    $ex_cats = explode(',', $compile['category']);
    foreach ($ex_cats as $ex_cat) {
        $ex_cat = intval($ex_cat);
        $db->query( "INSERT INTO " . PREFIX . "_post_extras_cats (news_id, cat_id) VALUES ('{$news_id}', '{$ex_cat}')" );
    }
}

$xfields = xfieldsload();
$news_xf = xfieldsdataload($compile['xfields']);
$xf_words = $xf_search_words = $newnews_xf = array ();

foreach ($xfields as $name => $value) {
    if($value[6] == 1 && !empty($news_xf[$value[0]])){
        $news_xf[$value[0]] = html_entity_decode($news_xf[$value[0]], ENT_QUOTES, $config['charset']);
        $newnews_xf[$value[0]] = trim( htmlspecialchars(strip_tags( stripslashes($news_xf[$value[0]]) ), ENT_QUOTES, $config['charset'] ));
        $temp_array = explode( ",", $newnews_xf[$value[0]] );

        foreach ($temp_array as $value2) {
            $value2 = trim($value2);
            if($value2) $xf_search_words[] = array( $db->safesql($value[0]), $db->safesql($value2) );
        }
    }
}

if (count($xf_search_words)) {
    $temp_array = array();
    foreach ( $xf_search_words as $value ) {
        $temp_array[] = "('" . $news_id . "', '" . $value[0] . "', '" . $value[1] . "')";
    }
    $xf_search_words = implode( ", ", $temp_array );
    $db->query( "INSERT INTO " . PREFIX . "_xfsearch (news_id, tagname, tagvalue) VALUES " . $xf_search_words );
}

if(!$kodik['news_id'] && $approve && function_exists('updateSocialPosting')) updateSocialPosting($news_id);

?>
