<?php

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

use CCDN\Helpers\Api\ApiHandler;
use CCDN\Helpers\Api\Response\FranchiseCalendarInterface;
use CCDN\Helpers\Caching\Cache;
use CCDN\Helpers\DB\Model;
use CCDN\Helpers\Entities\Post;
use CCDN\Helpers\Logger\LogType;
use CCDN\Helpers\Modules\Calendar\Handler;
use CCDN\Helpers\Modules\Calendar\XFieldTpl;
use CCDN\Helpers\Modules\CCDNModule;
use CCDN\Helpers\SecondIn;
use CCDN\Helpers\Settings;
use GuzzleHttp\Promise;

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

echo CCDNModule::run(LogType::MODULE_CALENDAR_MAIN, static function ($name, Cache $cache) {

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

    $cacheTimeLife = SecondIn::DAY;

    $api = new ApiHandler();
    $model = new Model();
    $handler = new Handler();
    $settings = Settings::all();
    $promises = [];
    $dates = [];

    $beforeToday = $settings->module_calendar_main_before_today * -1;
    $afterToday = $settings->module_calendar_main_after_today;
    $dateFormatAvailability = $settings->module_calendar_main_date_format_availability;
    for ($i = $beforeToday; $i <= $afterToday; $i++) {
        $date = date('Y-m-d', strtotime("{$i} day"));
        $dates[] = $date;
        $promises[] = $api->getFranchiseCalendarAsync([
            'date' => $date
        ]);
    }

    $waitResponses = Promise\settle($promises)->wait();
    $responses = $handler->responseHandler($waitResponses);

    if ($settings->module_calendar_main_sort === '0') {
        krsort($responses);
    }

    $queryResult = [];
    if ($ids = $handler->getCCDNIdFromResponse($responses)) {
        $ids = implode(',', $ids);
        $queryResult = $model->select("SELECT * FROM (SELECT *, SUBSTRING_INDEX(SUBSTRING_INDEX(xfields, '{$settings->ccdn_id_field}|', -1), '|', 1) AS collaps_id " .
            " FROM `{$model->getPrefix()}_post`) as t WHERE t.collaps_id IN ({$ids})", true);
    }

    $dateFormat = $settings->module_calendar_main_date_format;

    $templateMain = new dle_template();
    $templateMain->dir = TEMPLATE_DIR;
    $templateMain->load_template('/ccdn-calendar/main/main.tpl');

    $templateDay = new dle_template();
    $templateDay->dir = TEMPLATE_DIR;
    $templateDay->load_template('/ccdn-calendar/main/day.tpl');

    /** @var FranchiseCalendarInterface[] $respons */
    foreach ($responses as $date => $respons) {

        if (!in_array($date, $dates, true)) {
            continue;
        }

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

        $templateDay->set('{ccdn_calendar_date}', langdate($dateFormat, strtotime($date)));

        $calendarCurrentDateClass = date('Y-m-d') === $date ? 'ccdn_calendar_active_date' : '';
        $templateDay->set('{ccdn_calendar_current_date_class}', $calendarCurrentDateClass);

        $hasItems = false;
        foreach ($queryResult as $postRaw) {
            $post = new Post($postRaw);
            if ($post->getField($settings->post_status_field) === '0') {
                continue;
            }
            $postSeason = $post->getNumberFromField($settings->serial_season_field);

            foreach ($respons as $item) {
                if ($settings->module_calendar_serial_type_divided === '1' && $postSeason !== $item->getSeasonNumber()) {
                    continue;
                }
                if ((int)$post->getField($settings->ccdn_id_field) === $item->getId()) {
                    $templateItem = XFieldTpl::handler($templateItem, $postRaw);
                    $templateItem->set('{news_url}', $post->createUlr());
                    $templateItem->set('{name}', $item->getName());
                    $templateItem->set('{season}', $item->getSeasonNumber());
                    $templateItem->set('{episode}', $item->getEpisodeNumber());
                    $templateItem->set('{availability}',
                        langdate($dateFormatAvailability, strtotime($item->getAvailability())));
                    $templateItem->compile('templateItem');
                    $hasItems = true;
                    break;
                }
            }

            $templateDay->set('{ccdn_calendar_items}', $templateItem->result['templateItem']);
        }

        $pattern = "'\\[has-items\\](.*?)(\\[else\\](.*?))?\\[/has-items\\]'is";
        if ($hasItems) {
            $templateDay->copy_template = preg_replace($pattern, '$1', $templateDay->copy_template);
        } else {
            $templateDay->set('{ccdn_calendar_items}', '');
            $templateDay->copy_template = preg_replace($pattern, '$3', $templateDay->copy_template);
        }

        $templateDay->compile('templateDay');
    }

    $templateMain->set('{ccdn_calendar_days}', $templateDay->result['templateDay']);

    $templateMain->compile('ccdn_calendar');
    $cache->set($name, $templateMain->result['ccdn_calendar'], $cacheTimeLife);

    return $templateMain->result['ccdn_calendar'];
});

