<?php

namespace CCDN\Helpers;

class CCDNFunctions
{

    /*
     * Constants: Sequence Of Categories
     */
    const KEY_SEQ_CATS = "_sequence_categories";

    /**
     * @param array $categories
     * @return array
     */
    public static function getSequenceOfCategories($categories)
    {
        if (!is_array($categories))
            return [];

        foreach ($categories as $catID => $category) {
            $categories[$catID][self::KEY_SEQ_CATS] = self::getSequenceByCategory($categories, $category);
        }

        return $categories;
    }

    /**
     * @param array $category
     * @param string $glue
     * @return string
     */
    public static function implodeCategories($category, $glue = '/')
    {
        if (!isset($category[self::KEY_SEQ_CATS]))
            return isset($category['name']) ? $category['name'] : null;

        return implode($glue, $category[self::KEY_SEQ_CATS]);
    }

    /**
     * @param array $categories
     * @param array $category
     * @return array
     */
    private static function getSequenceByCategory($categories, $category)
    {
        $result[] = $category['name'];
        $parent_id = $category['parentid'];

        while ($parent_id != 0) {
            $result[] = $categories[$parent_id]['name'];
            $parent_id = $categories[$parent_id]['parentid'];
        }

        return array_reverse($result);
    }

    /**
     * @param string $url
     * @return mixed|string
     */
    public static function useHttpProtocol($url)
    {
        if (strpos($url, 'https://') === 0)
            return 'http://' . substr($url, 8);

        return $url;
    }

    /**
     * @param string $url
     * @return false|string
     */
    public static function removeSchema($url)
    {
        if (strpos($url, 'https:') === 0)
            return substr($url, 6);

        if (strpos($url, 'http:') === 0)
            return substr($url, 5);

        return $url;
    }

    /**
     * @param $subtitle
     */
    public static function echoHeader($subtitle)
    {
        global $config;
        if ((float)$config['version_id'] < 12.0 && is_array($subtitle)) {
            $subtitle = end($subtitle);
        }

        echoheader(Settings::PLUGIN_NAME . ' v' . Settings::PLUGIN_VERSION, $subtitle);
    }
}