<?php

/**
 * |--------------------------------------------------------------------------
 * | CCDN Calendar Module (fullstory) v1.4.23
 * |--------------------------------------------------------------------------
 */

use CCDN\Helpers\Api\ApiHandler;
use CCDN\Helpers\Caching\Cache;
use CCDN\Helpers\Entities\Post;
use CCDN\Helpers\Logger\LogType;
use CCDN\Helpers\Modules\Calendar\XFieldTpl;
use CCDN\Helpers\Modules\CCDNModule;
use CCDN\Helpers\SecondIn;
use CCDN\Helpers\Settings;

require_once ENGINE_DIR . '/inc/CCDN/vendor/autoload.php';

echo CCDNModule::run(LogType::MODULE_CALENDAR_FULL_STORY, static function ($name, Cache $cache) {
    global $row;

    $post = new Post($row);
    $cacheKey = $name . $post->id . $post->xfields;
    $cacheTimeLife = SecondIn::DAY;
    $cssClassHasEpisode = 'ccdn_calendar_full_has_episode';

    if ($cache->has($cacheKey)) {
        return $cache->get($cacheKey);
    }

    $postStatusField = Settings::get('post_status_field');

    if ($post->getField($postStatusField) === '0') {
        $cache->set($cacheKey, '', $cacheTimeLife);
        return '';
    }

    $api = new ApiHandler();

    $response = $api->getFranchiseDetails([
        'id' => $post->getField(Settings::get('ccdn_id_field'))
    ]);


    if ($response === null || !$response->getType()->isSeasons()) {
        $cache->set($cacheKey, '', $cacheTimeLife);
        return '';
    }

    $hideReleased = Settings::get('module_calendar_hide_released');
    $allReleases = Settings::get('module_calendar_full_all_releases');

    if ($allReleases === '0' && $hideReleased === '1') {
        $episodeList = $response->getSeasons()->getLast()->getEpisodes()->getUnreleased();
    } else {
        $episodeList = $response->getSeasons()->getLast()->getEpisodes()->getAll();
    }

    $serialTypeDivided = Settings::get('module_calendar_serial_type_divided');
    $sortEpisodes = Settings::get('module_calendar_full_sort_episodes');
    $dateFormat = Settings::get('module_calendar_full_date_format');
    $postSeason = $post->getNumberFromField(Settings::get('serial_season_field'));
    $seasonNumber = $response->getSeasons()->getLast()->getNumber();
    $franchiseName = $response->getName();

    if ($allReleases === '0') {
        if ($serialTypeDivided === '1' && $postSeason !== $seasonNumber) {
            $cache->set($cacheKey, '', $cacheTimeLife);
            return '';
        }

        if (!count($episodeList)) {
            $cache->set($cacheKey, '', $cacheTimeLife);
            return '';
        }

        $templateFull = new dle_template();
        $templateFull->dir = TEMPLATE_DIR;
        $templateFull->load_template('/ccdn-calendar/full/last/full.tpl');

        $templateItem = new dle_template();
        $templateItem->dir = TEMPLATE_DIR;
        $templateItem->load_template('/ccdn-calendar/full/last/item.tpl');

        $lastSeason = $response->getSeasons()->getLast();


        $templateFull->set('{name}', $franchiseName);
        $templateFull->set('{season}', $lastSeason->getNumber());

        if ($sortEpisodes === '0') {
            krsort($episodeList);
        }

        foreach ($episodeList as $episode) {
            $templateItem = XFieldTpl::handler($templateItem, $row);
            $templateItem->set('{name}', $franchiseName);

            $hasEpisode = !empty($episode->getIframeUrl()->get()) ? $cssClassHasEpisode : '';
            $templateItem->set('{has_episode_class}', $hasEpisode);

            $templateItem->set('{episode_name}', $episode->getName());
            $templateItem->set('{season}', $lastSeason->getNumber());
            $templateItem->set('{episode}', $episode->getNumber());

            $availability = $episode->getAvailability();
            $pattern = "'\\[has-availability\\](.*?)(\\[else\\](.*?))?\\[/has-availability\\]'is";
            if (empty($availability)) {
                $templateItem->copy_template = preg_replace($pattern, '$3', $templateItem->copy_template);
                $templateItem->set('{availability}', '');
            } else {
                $templateItem->copy_template = preg_replace($pattern, '$1', $templateItem->copy_template);
                $templateItem->set('{availability}', langdate($dateFormat, strtotime($availability)));
            }

            $templateItem->compile('templateFullItem');
        }

        $templateFull->set('{ccdn_calendar_full_items}', $templateItem->result['templateFullItem']);
        $templateFull->compile('templateFull');
        $ccdnCalendarFullHTML = $templateFull->result['templateFull'];


        $cache->set($cacheKey, $ccdnCalendarFullHTML, $cacheTimeLife);
        return $ccdnCalendarFullHTML;
    }


    $templateContainer = new dle_template();
    $templateContainer->dir = TEMPLATE_DIR;
    $templateContainer->load_template('/ccdn-calendar/full/all/container.tpl');

    $templateContainer->set('{name}', $franchiseName);
    $templateSeason = new dle_template();
    $templateSeason->dir = TEMPLATE_DIR;
    $templateSeason->load_template('/ccdn-calendar/full/all/season.tpl');

    $allSeasons = $response->getSeasons()->getAll();
    krsort($allSeasons);

    foreach ($allSeasons as $season) {

        if ($serialTypeDivided === '1' && $postSeason !== $season->getNumber()) {
            continue;
        }

        $templateSeason->set('{season}', $season->getNumber());
        $templateSeason->set('{name}', $franchiseName);
        $templateItem = new dle_template();
        $templateItem->dir = TEMPLATE_DIR;
        $templateItem->load_template('/ccdn-calendar/full/all/item.tpl');

        $allEpisodes = $season->getEpisodes()->getAll();

        if ($sortEpisodes === '0') {
            krsort($allEpisodes);
        }
        foreach ($allEpisodes as $episode) {
            $templateItem = XFieldTpl::handler($templateItem, $row);

            $hasEpisode = !empty($episode->getIframeUrl()->get()) ? $cssClassHasEpisode : '';
            $templateItem->set('{has_episode_class}', $hasEpisode);

            $templateItem->set('{name}', $franchiseName);
            $templateItem->set('{episode_name}', $episode->getName());
            $templateItem->set('{season}', $season->getNumber());
            $templateItem->set('{episode}', $episode->getNumber());

            $availability = $episode->getAvailability();
            $pattern = "'\\[has-availability\\](.*?)(\\[else\\](.*?))?\\[/has-availability\\]'is";
            if (empty($availability)) {
                $templateItem->copy_template = preg_replace($pattern, '$3', $templateItem->copy_template);
                $templateItem->set('{availability}', '');
            } else {
                $templateItem->copy_template = preg_replace($pattern, '$1', $templateItem->copy_template);
                $templateItem->set('{availability}', langdate($dateFormat, strtotime($availability)));
            }

            $templateItem->compile('templateFullItem');
        }
        $templateSeason->set('{season_items}', $templateItem->result['templateFullItem']);
        $templateSeason->compile('templateSeason');
    }

    $templateContainer->set('{ccdn_seasons_items}', $templateSeason->result['templateSeason']);
    $templateContainer->compile('templateContainer');
    $ccdnCalendarFullHTML = $templateContainer->result['templateContainer'];
    $cache->set($cacheKey, $ccdnCalendarFullHTML, $cacheTimeLife);
    return $ccdnCalendarFullHTML;
});
