<?php
/**
 * |--------------------------------------------------------------------------
 * | CCDN Franchise parts v1.4.23
 * |--------------------------------------------------------------------------
 */

use CCDN\Helpers\Api\ApiHandler;
use CCDN\Helpers\Caching\Cache;
use CCDN\Helpers\DB\Model;
use CCDN\Helpers\Entities\Post;
use CCDN\Helpers\Exception\CCDNRuntimeException;
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;

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

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

    global $row;

    $postRow = new Post($row);
    $cacheTimeLife = SecondIn::week(2);
    $cacheKey = $name . $postRow->id;

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

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

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

    $api = new ApiHandler();

    $ccdnIdField = Settings::get('ccdn_id_field');
    $newFranchiseYear = Settings::get('new_franchise_year');

    $response = $api->getFranchiseDetails([
        'id' => $postRow->getField($ccdnIdField)
    ]);

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

    $model = new Model();
    $partsIds = implode(',', $response->getParts()->getData());

    $result = $model->select("SELECT * FROM (SELECT *, SUBSTRING_INDEX(SUBSTRING_INDEX(xfields, '{$ccdnIdField}|', -1), '|', 1) AS collaps_id, 
     SUBSTRING_INDEX(SUBSTRING(`xfields` FROM INSTR(`xfields`, '{$newFranchiseYear}|') FOR LENGTH('{$newFranchiseYear}|') + 4), '|',-1) as xfield_year 
     FROM `{$model->getPrefix()}_post`) as t WHERE t.collaps_id IN ({$partsIds}) ORDER BY t.xfield_year DESC", true);

    if (empty($result)) {
        $cache->set($cacheKey, '', $cacheTimeLife);
        throw new CCDNRuntimeException('Parts not found in DB. Collaps id:' . $response->getId());
    }

    $containerTpl = new dle_template();
    $containerTpl->dir = TEMPLATE_DIR;
    $containerTpl->load_template('/ccdn-franchise-parts/container.tpl');

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

    if (count($result) === 1) {
        $cache->set($cacheKey, '', $cacheTimeLife);
        throw new CCDNRuntimeException('Parts only one. Collaps id:' . $response->getId());
    }

    foreach ($result as $row) {

        $post = new Post($row);

        if ($post->getField($postStatusField) === '0') {
            continue;
        }

        if (!in_array($post->getField($ccdnIdField), $response->getParts()->getData())) {
            continue;
        }

        $templateItem = XFieldTpl::handler($templateItem, $row);
        $currentPartClass = $postRow->id === $post->id ? 'ccdn_current_part' : '';
        $templateItem->set('{name}', $post->title);
        $templateItem->set('{href}', $post->createUlr());
        $templateItem->set('{ccdn_current_part_class}', $currentPartClass);
        $templateItem->compile('templateItem');
    }

    $containerTpl->set('{ccdn_franchise_items}', $templateItem->result['templateItem']);
    $containerTpl->set('{ccdn_franchise_name}', $postRow->title);
    $containerTpl->compile('containerTpl');

    $cache->set($cacheKey, $containerTpl->result['containerTpl'], $cacheTimeLife);

    return $containerTpl->result['containerTpl'];
});

