<?php

namespace CCDN\Controllers;

use CCDN\Helpers\Api\ApiHandler;
use CCDN\Helpers\Arr;
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\Exception\CCDNRuntimeException;
use CCDN\Helpers\Facade\Http\Response;
use CCDN\Helpers\Facade\Http\Url;
use CCDN\Helpers\Http\Request;
use CCDN\Helpers\PostCategories;
use CCDN\Helpers\SearchResolver;
use CCDN\Helpers\Settings;
use CCDN\Helpers\XFields;

class BtnController extends Controller
{

    protected $viewsFolder = 'button';
    protected $parent = '';

    public function __construct($parent = 'btn-settings')
    {
        $this->parent = $parent;
    }

    public function main()
    {
        return Response::make($this->render('main', [
            'ccdnConf' => Settings::all(),
            'customFields' => XFields::load(),
        ]));
    }

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

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

    }

    public function renderButton()
    {
        global $member_id;

        $searchButtonGroup = (int)Settings::get('button_group_permission');
        $searchButtonGroup = $searchButtonGroup === 0 ? 1 : $searchButtonGroup;

        $userGroup = (int)$member_id['user_group'];

        if ($userGroup > $searchButtonGroup) {
            throw new CCDNRuntimeException('Permission Exception');
        }

        if (empty(Settings::get('api_key'))) {
            throw new CCDNRuntimeException('Api key empty');
        }

        return $this->render('btn', [
            'ccdnConf' => Settings::all()
        ]);
    }


    /**
     * @param Request $request
     *
     * @return string
     * @throws CCDNException
     */
    public function getFranchiseDetails(Request $request)
    {
        $kinopoiskId = $request->post('kinopoisk_id');
        $imdbId = $request->post('imdb_id');
        $world_artId = $request->post('world_art_id');
        $ccdn_id = $request->post('ccdn_id');

        if (empty($kinopoiskId) && empty($imdbId) && empty($world_artId) && empty($ccdn_id)) {
            throw new CCDNException('Поиск невозможен из-за отсутствия данных!', 400);
        }

        $config = Settings::all();

        if ($request->post('news_id') === '0') {
            if (!empty($kinopoiskId)) {
                $model = new Model();
                $query = "SELECT * FROM (SELECT id,
 SUBSTRING_INDEX(SUBSTRING_INDEX(xfields, '{$config->kinopoisk_id_field}|', -1), '|', 1) AS kinopoisk_id
 FROM `{$model->getPrefix()}_post`) as t WHERE t.kinopoisk_id = {$model->getDb()->safesql($kinopoiskId)}";

                if ($model->select($query)) {
                    throw new CCDNException('Post is exist', 404);
                }
            } elseif (!empty($ccdn_id)) {
                $model = new Model();
                $query = "SELECT * FROM (SELECT id,
 SUBSTRING_INDEX(SUBSTRING_INDEX(xfields, '{$config->ccdn_id_field}|', -1), '|', 1) AS collaps_id
 FROM `{$model->getPrefix()}_post`) as t WHERE t.collaps_id = {$model->getDb()->safesql($ccdn_id)}";

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

        $post = new Post();
        $post->setField($config->ccdn_id_field, $ccdn_id);
        $post->setField($config->kinopoisk_id_field, $kinopoiskId);
        $post->setField($config->imdb_id_field, str_replace('tt', '', $imdbId));
        $post->setField($config->world_art_id_field, $world_artId);

        $api = new ApiHandler();

        if ($ccdn_id === null) {
            $searchResolver = new SearchResolver();
            $response = $searchResolver->singleHandler($api, $post);
        } else {
            $response = $api->getFranchiseDetails([
                'id' => $ccdn_id,
            ]);
        }

        if ($response === null) {
            $message = "Not found. Collaps id: {$ccdn_id}, Kp ID: {$kinopoiskId}, IMDB: {$imdbId}, World Art: {$world_artId}";
            throw new CCDNException($message, 404);
        }

        $response->addField('episode_count', $response->getSeasons()->getAllEpisodesCount());

        $videoVoicesDisabled = (array)$config->getJsonDecode('video_voices_disabled');

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

        $response->updateField('iframe_url', $iframeUrl);
        if (!$response->addField('trailer', $response->getTrailers()->getLast()->getIframeUrl()->get())) {
            $response->updateField('trailer', $response->getTrailers()->getLast()->getIframeUrl()->get());
        }

        if ($config->content_ads_filter === '1' && $response->getAds()) {
            $response->updateField('iframe_url', '');
        }

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

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

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

        $voiceActing = $response->getVoicesActing()->removeFromList($videoVoicesDisabled)->implode();


        $categoryPost = new PostCategories();
        $categoryPostArr = $categoryPost->make($config, $response)->toArray();

        $firstVoice = $response->getVoicesActing()
            ->removeFromList($videoVoicesDisabled)
            ->getVoiceActingByPriority($config->getJsonDecode('video_voice_priority'));

        $response->addField('season', $season);
        $response->addField('episode', $episode);
        $response->addField('firstVoice', $firstVoice);
        $response->addField('franchise_type', $response->getType()->getName());

        $response->addField('category', $categoryPostArr);
        $response->addField('set_category', (bool)$config->button_set_category);
        $response->addField('set_short_desc', (bool)$config->button_short_desc);
        $response->addField('set_description', (bool)$config->button_description);

        $response->updateField('voiceActing', $voiceActing);
        $response->updateField('country', $response->getCountries()->implode());
        $response->updateField('actors', $response->getActors()->implode());
        $response->updateField('director', $response->getDirectors()->implode());
        $response->updateField('ads', $response->getAds());
        $response->updateField('genre', $response->getGenres()->implode());
        $response->updateField('collection', $response->getCollection()->implode());

        $response->updateField('slogan', $response->getSlogan());
        $response->updateField('screenwriter', $response->getScreenwriters()->implode());
        $response->updateField('producer', $response->getProducers()->implode());
        $response->updateField('operator', $response->getOperators()->implode());
        $response->updateField('design', $response->getDesigns()->implode());
        $response->updateField('editor', $response->getEditors()->implode());
        $response->updateField('actors_dubl', $response->getActorsDuplicators()->implode());
        $response->updateField('trivia', $response->getTrivia()->implode("\n\n"));
        $response->updateField('composer', $response->getComposers()->implode());
        $response->updateField('composer', $response->getComposers()->implode());
        $response->updateField('serial_status', $response->getSerialStatus()->toCyrillic());


        $premierFormatDate = !empty($config->premier_format_date) ? $config->premier_format_date : 'Y-m-d';
        $response->updateField('premier', langdate($premierFormatDate, strtotime($response->getPremier())));
        $response->updateField('premier_rus', langdate($premierFormatDate, strtotime($response->getPremierRus())));

        return Response::json($response->getData());
    }


    public function search(Request $request)
    {
        $api = new ApiHandler();
        $body = $api->getList([
            'limit' => 20,
            'name' => $request->get('q'),
        ])->getBody();

        $results = $body['results'];

        $body = $api->getTrailers([
            'limit' => 20,
            'name' => $request->get('q'),
        ])->getBody();

        $results = array_merge($results, $body['results']);


        $body = $api->getVideoNews([
            'limit' => 20,
            'name' => $request->get('q'),
        ])->getBody();

        $results = array_merge($results, $body['results']);

        $results = Arr::unique($results, 'id');
        return Response::json([
            'results' => $results
        ]);
    }

}
