<?php
/**
 * SeekQuarry/Yioop --
 * Open Source Pure PHP Search Engine, Crawler, and Indexer
 *
 * Copyright (C) 2009 - 2026  Chris Pollett chris@pollett.org
 *
 * LICENSE:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * END LICENSE
 *
 * @author Chris Pollett chris@pollett.org
 * @license https://www.gnu.org/licenses/ GPL3
 * @link https://www.seekquarry.com/
 * @copyright 2009 - 2026
 * @filesource
 */
namespace seekquarry\yioop\views\helpers;

use seekquarry\yioop\configs as C;
use seekquarry\yioop\library as L;
use seekquarry\yioop\library\CrawlConstants;
use seekquarry\yioop\library\UrlParser;

/**
 * Helper used to draw thumbnails strips for images
 *
 * @author Chris Pollett
 */
class VideosHelper extends Helper implements CrawlConstants
{
    /**
     * Takes page summaries for image pages and the current query
     * and draw a thumbnail strip so that clicking on an image goes to
     * the cache of that image.
     *
     * @param array $video_pages page data and thumbnails for videos
     * @param string $query the current search query
     * @param string $subsearch name of subsearch page this image group on
     * @param bool $video_subsearch whether the video subsearch is
     *  enabled on this Yioop instance
     * @param boolean $open_in_tabs whether new links should be opened in
     *  tabs
     * @param string $default_thumb default data url to use if a video does
     *  not have a thumb
     */
    public function render($video_pages, $query, $subsearch,
        $video_subsearch = true, $open_in_tabs = false, $default_thumb = "")
    {
        if ($subsearch != 'videos' && !stristr($query, "media%3Avideo")) {
            if (!empty($video_subsearch)) {
                $query .= '&s=videos';
            } else {
                if (!stristr($query, "media%3Avideo")) {
                    $query .= '%20media%3Aivdeo';
                }
            }
            ?>
            <h2><a href="<?= $query ?>" rel="nofollow"
                ><?=tl('videos_helper_view_video_results') ?></a></h2>
                <?php
        }
        $iconlink_helper = new IconlinkHelper();
        $feeds_helper = new FeedsHelper();
        ?><div class="video-list"><div class="sub-video-list" >
        <?php
        foreach ($video_pages as $page) {
            $link = htmlentities($page[self::URL]);
            $host = UrlParser::getHost($page[self::URL]);
            $host_parts = explode(".", $host);
            $company = $host;
            foreach ($host_parts as $host_part) {
                if (!in_array(substr($host_part, 0, 3), ["www", "htt"]) &&
                    strlen($host_part) > 2) {
                    $company = $host_part;
                    break;
                }
            }
            $site_name = (!empty($page['SITE_NAME'])) ?
                $page['SITE_NAME'] : $company;
            $title = strip_tags(explode("\n", $page[self::TITLE])[0]);
            $title_parts = preg_split('/\s+[\-|\|]\s+/u', $title);
            $title = "";
            $sep = "";
            foreach ($title_parts as $title_part) {
                if (stristr($title_part, $site_name) != false) {
                    break;
                }
                $title .= $sep . $title_part;
                $sep = " - ";
            }
            $max_title_length = (!empty($_SERVER["MOBILE"])) ?
                C\AD_HOC_TITLE_LENGTH * 0.8 : C\AD_HOC_TITLE_LENGTH * 0.9;
            if (mb_strlen($title) > $max_title_length) {
                $new_title = mb_substr($title, 0, intval($max_title_length));
                if ($title != $new_title) {
                    $title = $new_title . "...";
                }
            }
            $quality = "SD";
            if (!empty($page[self::HEIGHT])) {
                if ($page[self::HEIGHT] >= 4000) {
                    $quality = "4K";
                } else if ($page[self::HEIGHT] >= 1080) {
                    $quality = "FHD";
                } else if ($page[CrawlConstants::HEIGHT] >= 720) {
                    $quality = "HD";
                }
            }
            $pub_date = "";
            if (!empty($page[self::PUBDATE])) {
                $pub_date = $page[self::PUBDATE];
                $time = time();
                $pub_date = " | ".
                    $feeds_helper->getPubdateString($time, $pub_date);
            }
            $cache_link = $link;
            if (C\p('CACHE_LINK') && (!isset($page[self::ROBOT_METAS]) ||
                !(in_array("NOARCHIVE", $page[self::ROBOT_METAS]) ||
                  in_array("NONE", $page[self::ROBOT_METAS])))) {
                $cache_link = $query . "&amp;a=cache&amp;arg=".
                    urlencode($link). "&amp;its=" . $page[self::CRAWL_TIME];
            }
            ?><figure class="video-detail" >
            <?php
            $open_in_tabs = ($open_in_tabs) ? ' target="_blank" ' : "";
            ?><a href="<?=$link
                ?>" rel="noopener nofollow noreferer" ><img class="video-thumb"
                <?= $open_in_tabs ?> src="<?=
                    $page[self::THUMB] ?? $default_thumb ?>"
                alt="<?= tl('video_helper_videothumb'); ?>" >
            </a>
            <div class="video-quality"><?= $quality ?></div>
            <div class="video-play-button"><?=
            $iconlink_helper->renderLink($link, "play") ?></div>
            <?php
            if (!empty($page[self::DURATION]) &&
                is_numeric($page[self::DURATION])) {
                $duration = $page[self::DURATION];
                $hours = intval($duration/C\ONE_HOUR);
                $minutes = intval(($duration % C\ONE_HOUR)/
                    C\ONE_MINUTE);
                $seconds = $minutes % C\ONE_MINUTE;
                $minutes = sprintf("%'.02d", $minutes);
                $seconds = sprintf("%'.02d", $seconds);
                $formatted_duration = "$minutes:$seconds";
                if (!empty($hours)) {
                    $formatted_duration = "$hours:$formatted_duration";
                }
                ?>
                <div class="video-duration"><?=
                $formatted_duration; ?></div><?php
            }
            ?>
            <figcaption class="align-same">
            <?php
            if (!empty($page[self::VIEW_COUNT])) {?>
                <div class="float-opposite">
                <?=L\intToMetric(intval($page[self::VIEW_COUNT])).
                " " . tl('video_helper_views'); ?>
                </div>
                <?php
            }?>
            <div><a href="<?=$cache_link
            ?>"  rel="noopener nofollow noreferer" <?=$open_in_tabs
            ?> ><b><?=$title ?></b></a></div><div><?php
            if (!empty($page[self::FAVICON_URL])) {
                ?><img class="result-fav" src="<?=$query .
                "&amp;a=cache&amp;field=favicon&amp;arg=" . urlencode(
                    $page[self::FAVICON_URL]). "&amp;its=".
                    $page[self::CRAWL_TIME]
                ?>" ><?php
            }?><?= $site_name . $pub_date ?></div>
            </figcaption>
            </figure><?php
        }
        ?>
        </div></div>
        <?php
    }
}
