<?php

namespace CCDN\Controllers;

use CCDN\Helpers\Api\ApiHandler;
use CCDN\Helpers\Api\Response\Trailers;
use CCDN\Helpers\Arr;
use CCDN\Helpers\CCDNUploadPoster;
use CCDN\Helpers\Controller;
use CCDN\Helpers\DB\Model;
use CCDN\Helpers\DB\SettingsSave;
use CCDN\Helpers\Entities\Post;
use CCDN\Helpers\Exception\CCDNException;
use CCDN\Helpers\Facade\DB\Model as ModelStatic;
use CCDN\Helpers\Facade\Http\Response;
use CCDN\Helpers\Facade\Http\Url;
use CCDN\Helpers\Http\Request;
use CCDN\Helpers\NotSeasonsFranchiseAltUrl;
use CCDN\Helpers\NotSeasonsFranchiseMetaTitle;
use CCDN\Helpers\NotSeasonsFranchiseTitle;
use CCDN\Helpers\PostCategories;
use CCDN\Helpers\SeasonsFranchiseAltUrl;
use CCDN\Helpers\SeasonsFranchiseMetaTitle;
use CCDN\Helpers\SeasonsFranchiseTitle;
use CCDN\Helpers\CCDNFunctions;
use CCDN\Helpers\Settings;
use CCDN\Helpers\XFields;
use URLify;

class FutureFranchisesController extends Controller
{
    protected $viewsFolder = 'future-franchises';
    protected $parent = '';

    public function __construct($parent = 'future-franchises')
    {
        $this->parent = $parent;
    }

    public function main()
    {
        global $cat_info;

        return Response::make($this->render('main', [
            'ccdnConf' => Settings::all(),
            'categories' => CCDNFunctions::getSequenceOfCategories($cat_info),
            'customFields' => XFields::load()
        ]));
    }

    public function saveSettings(Request $request)
    {
        $configSave = new SettingsSave($request->post());
        $configSave->futureFranchises();

        Response::redirect(Url::to($this->parent));
    }

    public function getFutureFranchises()
    {
        $api = new ApiHandler();
        $trailersAll = $api->getTrailersAll();
        $time = strtotime(date('Y-m-d'));
        $trailersAll = array_filter($trailersAll, static function ($item) use ($time) {
            return strtotime($item['availability']) >= $time && $item['kinopoisk_id'] !== null;
        });

        if (empty($trailersAll)) {
            return Response::json([
                'data' => [],
            ]);
        }

        $trailersAll = Arr::unique($trailersAll, 'id');
        $kinopoiskIdField = Settings::get('kinopoisk_id_field');
        $ccdnIdField = Settings::get('ccdn_id_field');

        $whereIn = [];

        foreach ($trailersAll as $key => $item) {
            unset($trailersAll[$key]['season'],
                $trailersAll[$key]['premier'],
                $trailersAll[$key]['imdb'],
                $trailersAll[$key]['kinopoisk'],
                $trailersAll[$key]['premier_rus'],
                $trailersAll[$key]['activate_time'],
                $trailersAll[$key]['imdb_id'],
                $trailersAll[$key]['origin_name'],
                $trailersAll[$key]['world_art_id'],
                $trailersAll[$key]['world_art']);
            $item = new Trailers($item);
            $trailersAll[$key]['type'] = $item->getType()->getName();
            $trailersAll[$key]['has_in_db'] = false;

            $whereIn['collaps_id'][] = $item->getId();

            if (($kp_id = $item->getKinopoiskId()) !== null) {
                $whereIn['kinopoisk_id'][] = $kp_id;
            }
        }

        $whereIn['collaps_id'] = implode(',', $whereIn['collaps_id']);
        $whereIn['kinopoisk_id'] = implode(',', $whereIn['kinopoisk_id']);

        $dbPrefix = ModelStatic::getPrefix();

        $query = "SELECT * FROM (SELECT id, SUBSTRING_INDEX(SUBSTRING_INDEX(xfields, '{$ccdnIdField}|', -1), '|', 1) AS collaps_id";

        if ($kinopoiskIdField) {
            $query .= ", SUBSTRING_INDEX(SUBSTRING_INDEX(xfields, '{$kinopoiskIdField}|', -1), '|', 1) AS kinopoisk_id";
        }

        $query .= " FROM `{$dbPrefix}_post`) as t WHERE t.collaps_id IN ({$whereIn['collaps_id']})";
        if ($kinopoiskIdField && $whereIn['kinopoisk_id']) {
            $query .= " OR t.kinopoisk_id IN ({$whereIn['kinopoisk_id']})";
        }
        $queryResult = ModelStatic::select($query, true);

        foreach ($trailersAll as $key => $franchise) {
            $item = new Trailers($franchise);
            $collaps_id = (int)$item->getId();
            $kp_id = $item->getKinopoiskId();

            foreach ($queryResult as $postItem) {
                if ($kinopoiskIdField && $kp_id !== null && (string)$postItem['kinopoisk_id'] !== (string)$kp_id) {
                    continue;
                }

                if ((int)$postItem['collaps_id'] !== $collaps_id)
                    continue;

                $trailersAll[$key]['has_in_db'] = true;
                $trailersAll[$key]['post_url'] = Url::toAdminPanel() . "?mod=editnews&action=editnews&id={$postItem['id']}";
                break;
            }
        }

        return Response::json([
            'data' => $trailersAll,
        ]);
    }


    /**
     * @param Request $request
     * @return string
     * @throws CCDNException
     */
    public function createPost(Request $request)
    {
        $id = $request->post('collaps_id');
        $ccdnConf = Settings::all();

        $model = new Model();
        $query = "SELECT * FROM (SELECT id,
 SUBSTRING_INDEX(SUBSTRING_INDEX(xfields, '{$ccdnConf->ccdn_id_field}|', -1), '|', 1) AS collaps_id
 FROM `{$model->getPrefix()}_post`) as t WHERE t.collaps_id = {$model->getDb()->safesql($id)}";

        if ($model->select($query)) {
            throw new CCDNException('Post is exist', 404);
        }

        $api = new ApiHandler();
        $response = $api->getFranchiseDetails([
            'id' => $id,
        ]);

        if ($response === null) {
            throw new CCDNException("Not found. Collaps id: {$id}", 404);
        }

        $season = '';
        $episode = '';

        $seasonsNumber = $response->getSeasons()->getLast()->getNumber();
        $episodesNumber = $response->getSeasons()->getLast()->getEpisodes()->getLast()->getNumber();

        if (!empty($seasonsNumber)) {
            $season = $seasonsNumber . ' ' . $ccdnConf->serial_season_field_suffix;
        }
        if (!empty($episodesNumber)) {
            $episode = $episodesNumber . ' ' . $ccdnConf->serial_episode_field_suffix;
        }


        $disabledVoices = $ccdnConf->getJsonDecode('video_voices_disabled');

        $iframeUrl = $response->getIframeUrl()->addQueryParam('soundBlock', implode(',', $disabledVoices))->get();

        $firstVoice = $response->getVoicesActing()
            ->removeFromList($disabledVoices)
            ->getVoiceActingByPriority($ccdnConf->getJsonDecode('video_voice_priority'));

        global $member_id, $config;

        $categoryPost = new PostCategories();
        $categoryPostArr = $categoryPost->make($ccdnConf, $response)
            ->push($ccdnConf->future_franchises_category);

        $post = new Post();
        $post->title = $response->getName();
        $post->metatitle = $response->getName();
        $post->alt_name = URLify::filter($response->getName(), 190);
        $post->date = date('Y-m-d H:i:s');
        $post->autor = $member_id['name'];
        $post->approve = $ccdnConf->new_franchise_approve;
        $post->category = $categoryPostArr->implode();
        $post->allow_comm = $config['allow_comments'];
        $post->allow_main = '1';

        if ($ccdnConf->new_franchise_description === '1') {
            $post->full_story = $response->getDescription();
        }

        if ($ccdnConf->new_franchise_short_desc === '1') {
            $post->short_story = $response->getDescription();
        }

        if ($config['create_metatags'] === '1' && $ccdnConf->new_franchise_description === '1') {
            $meta = create_metatags($response->getDescription());
            $post->descr = $meta['description'];
            $post->keywords = $meta['keywords'];
        }

        $premierFormatDate = !empty($ccdnConf->premier_format_date) ? $ccdnConf->premier_format_date : 'Y-m-d';
        $post->setField($ccdnConf->episode_count_field, $response->getSeasons()->getAllEpisodesCount());
        $post->setField($ccdnConf->post_status_field, '1');
        $post->setField($ccdnConf->new_franchise_origin_name, $response->getNameEng());
        $post->setField($ccdnConf->new_franchise_poster, $response->getPoster());
        $post->setField($ccdnConf->new_franchise_year, $response->getYear());
        $post->setField($ccdnConf->new_franchise_country, $response->getCountries()->implode());
        $post->setField($ccdnConf->new_franchise_director, $response->getDirectors()->implode());
        $post->setField($ccdnConf->new_franchise_actors, $response->getActors()->implode());
        $post->setField($ccdnConf->video_voice_field,
            $response->getVoicesActing()->removeFromList($disabledVoices)->implode());
        $post->setField($ccdnConf->video_first_voice_field, $firstVoice);
        $post->setField($ccdnConf->new_franchise_age, $response->getAge());
        $post->setField($ccdnConf->new_franchise_time, $response->getTime());
        $post->setField($ccdnConf->new_franchise_premier,
            langdate($premierFormatDate, strtotime($response->getPremier())));
        $post->setField($ccdnConf->new_franchise_premier_rus,
            langdate($premierFormatDate, strtotime($response->getPremierRus())));
        $post->setField($ccdnConf->new_franchise_genres, $response->getGenres()->implode());
        $post->setField($ccdnConf->video_quality_field, $response->getQuality());
        $post->setField($ccdnConf->imdb_id_field, $response->getImdbId());
        $post->setField($ccdnConf->world_art_id_field, $response->getWorldArtId());
        $post->setField($ccdnConf->kinopoisk_id_field, $response->getKinopoiskId());
        $post->setField($ccdnConf->new_franchise_rating_imdb, $response->getImdbRating());
        $post->setField($ccdnConf->new_franchise_rating_kinopoisk, $response->getKinopoiskRating());
        $post->setField($ccdnConf->new_franchise_rating_world_art, $response->getWorldArtRating());
        $post->setField($ccdnConf->new_franchise_trailer, $response->getTrailers()->getLast()->getIframeUrl()->get());
        $post->setField($ccdnConf->embed_field, $iframeUrl);
        $post->setField($ccdnConf->serial_season_field, $season);
        $post->setField($ccdnConf->serial_episode_field, $episode);
        $post->setField($ccdnConf->ccdn_id_field, $response->getId());
        $post->setField($ccdnConf->collaps_franchise_ads_status_field, (int)$response->getAds());
        $post->setField($ccdnConf->season_franchise_status, $response->getSerialStatus()->toCyrillic());

        $post->setField($ccdnConf->new_franchise_name, $response->getName());
        $post->setField($ccdnConf->new_franchise_slogan, $response->getSlogan());
        $post->setField($ccdnConf->new_franchise_screenwriter, $response->getScreenwriters()->implode());
        $post->setField($ccdnConf->new_franchise_producer, $response->getProducers()->implode());
        $post->setField($ccdnConf->new_franchise_operator, $response->getOperators()->implode());
        $post->setField($ccdnConf->new_franchise_composer, $response->getComposers()->implode());
        $post->setField($ccdnConf->new_franchise_design, $response->getDesigns()->implode());
        $post->setField($ccdnConf->new_franchise_editor, $response->getEditors()->implode());
        $post->setField($ccdnConf->new_franchise_actors_dubbing, $response->getActorsDuplicators()->implode());
        $post->setField($ccdnConf->new_franchise_budget, $response->getBudget());
        $post->setField($ccdnConf->new_franchise_fees_use, $response->getFeesUSA());
        $post->setField($ccdnConf->new_franchise_fees_rus, $response->getFeesRus());
        $post->setField($ccdnConf->new_franchise_fees_world, $response->getFeesWorld());
        $post->setField($ccdnConf->new_franchise_rate_mpaa, $response->getRateMPAA());
        $post->setField($ccdnConf->new_franchise_trivia, $response->getTrivia()->implode("\n\n"));
        $post->setField($ccdnConf->new_franchise_filed_description, $response->getDescription());
        $post->setField($ccdnConf->collection_field, $response->getCollection()->implode());
        $post->setField($ccdnConf->new_franchise_franchise_type, $response->getType()->getName());

        $post->setField($ccdnConf->future_franchises_premier, $response->getAvailability());


        if ($response->getType()->isSeasons()) {
            $post->title = SeasonsFranchiseTitle::handler($ccdnConf, $response, $post);
            $post->alt_name = SeasonsFranchiseAltUrl::handler($ccdnConf, $response, $post);
            $post->metatitle = SeasonsFranchiseMetaTitle::handler($ccdnConf, $response, $post);
        } else {
            $post->title = NotSeasonsFranchiseTitle::handler($ccdnConf, $response, $post);
            $post->alt_name = NotSeasonsFranchiseAltUrl::handler($ccdnConf, $response, $post);
            $post->metatitle = NotSeasonsFranchiseMetaTitle::handler($ccdnConf, $response, $post);
        }

        if ($config['create_catalog'] === '1') {
            $post->symbol = $post->getDb()->safesql(dle_substr(htmlspecialchars(strip_tags(stripslashes(trim($post->title))),
                ENT_QUOTES, $config['charset']), 0, 1, $config['charset']));
        }

        $insertPostCondition = $post->insertPost($categoryPostArr->toArray());

        $result = null;
        if (!empty($ccdnConf->new_franchise_download_poster) && $response->getPoster() !== null) {
            $result = CCDNUploadPoster::upload($ccdnConf, $response, $post->id);
            if (!empty($result['xfvalue'])) {
                $post->setField($ccdnConf->new_franchise_download_poster, $result['xfvalue']);
                $post->setField($ccdnConf->new_franchise_download_poster_url, '/uploads/posts/' . $result['xfvalue']);
                $post->setField($ccdnConf->new_franchise_download_poster_url_with_domain, Url::getDomain() . '/uploads/posts/' . $result['xfvalue']);
                $post->updatePost();
            }
        }

        return Response::json([
            'status' => $insertPostCondition ? 'ok' : 'Insert error',
            'item' => [
                'collaps_id' => $response->getId(),
                'name' => $response->getName(),
            ],
            'upload' => $result
        ]);
    }
}
