<?php

namespace pictpostpersonal\controller\page;

use pictpostpersonal\controller\ControllerBase;
use pictpostpersonal\controller\api\NavigateApi;
use pictpostpersonal\renderer\ArticleRenderer;
use pictpostpersonal\model\Article;
use pictpostpersonal\model\Account;
use pictpostpersonal\NoSixTemplate2;
use pictpostpersonal\Environment;
use pictpostpersonal\Result;
use pictpostpersonal\Request;
use pictpostpersonal\service\ThemeService;
use pictpostpersonal\Utility;
use pictpostpersonal\service\PluginApiService;

class IndexPage extends ControllerBase
{
    function show(Request $req): ?Result
    {
        try {
            $show_indexes = explode(',', $req->getArgs('page', '1'));
        } catch (\Exception $ex) {
            //引数が不正
            return new Result(400);
        }

        //NSFWチェック
        $nsfw_ans = false;
        if ($this->setting->getValue('always_nsfw_check', false)) {
            //常時NSFWチェックの場合、引数で同意が渡されていなければ警告
            $nsfw_ans = $req->getArgs('nsfw_consent', false);
        } else {
            //通常チェック
            $nsfw_ans = ($req->getCookie('nsfw_consent', false));
        }

        //移動履歴削除
        $navi = new NavigateApi($this->context);
        $navi->delete_all($req);

        //アカウントデータ
        $account_model = new Account($this->db);
        $accounts = $account_model->findAll();


        //トップページ用データ
        $article = new Article($this->db, $this->setting);
        $index_data = $article->getIndexPage();
        //コンテンツ部分をレンダリング / 固定ページ用メニュー生成
        $data = [
            'current' => [
                'id' => -1,
                'created_at' => '',
                'title' => '',
                'contents' => $index_data['contents'],
                'tag' => '',
                'media' => $index_data['media'],
                'alt_url' => ''
            ],
            'next' => [],
            'prev' => [],
            'next_link' => '',
            'prev_link' => '',
            'manga_mode' => false,
            'nsfw_ans' => $nsfw_ans
        ];

        //ArticleServiceにより本文とメニューをレンダリング
        $article_service = new ArticleRenderer($this->context);
        $article_service->setUrl($data['current']);
        $contents = $article_service->createContents($data, $index_data['contents'], true, $show_indexes);
        $home_menu = $article_service->createHomeMenu($article);
        //画像拡大処理用のスクリプトを指定する
        if ($this->setting->getValue('use_lightbox', false)) {
            //ライトボックスを使用
            $contents .= "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js\"></script><link rel=\"stylesheet\" href=\"" . SITE_URL . "/system_resource/vender/lightbox/css/lightbox.min.css\"><script src=\"" . SITE_URL . "/system_resource/vender/lightbox/js/lightbox.min.js\"></script>";
        } else {
            //標準の画像ビュアーを使用
            $contents .= "<script src=\"" . SITE_URL . "/system_resource/script/image_viewer2.js\"></script>";
        }


        //記事一覧処理
        $exclude_tags_setting = $this->setting->getValue('exclude_index_list_tag', '');
        if ($exclude_tags_setting == '*ALL*' || $this->setting->getValue('index_articles', 0) == 0) {
            //一覧除外タグに「*ALL*」が指定されている場合 または 一覧表示件数が0の場合は一覧表示なし
            $articles = [];
            $pages = 0;
        } else {
            //記事一覧を取得
            $query = '[type] = 0 and hidden_at_list != 1 and status = 0';

            //一覧非掲示タグを条件に追加
            $exclude_tags = array_filter(explode(' ', trim($exclude_tags_setting, '')));
            $exclude_tags_array = [];
            foreach ($exclude_tags as $index => $tag) {
                $query .= " and (tags not like :tag{$index})";
                $exclude_tags_array["tag{$index}"] = "% $tag %";
            }

            ['articles' => $articles_raw, 'count' => $count] = $article->searchWithTotalCount($query, $exclude_tags_array, ['pin desc', 'sort desc', 'created_at desc'], $this->setting->getValue('index_articles', 28), $show_indexes[0]);
            $articles = [];
            $key = 0;
            foreach ($articles_raw  as  $item) {
                $title = s($item['title']);

                $thumbnail_class = '';
                $multi_image = false;
                if ($item['media_count'] == 0) {
                    //画像なし記事
                    $thumbnail_class .= ' thumb_text';
                    if ($item['nsfw'] && $nsfw_ans == false) {
                        $thumbnail_title = "[NSFW]<br>$title";
                    } else {
                        $thumbnail_title = $title;
                    }
                } else {
                    //画像ありの場合 thumbnail_title なし
                    $thumbnail_title = "";
                    if ($item['nsfw']) {
                        $thumbnail_class .= ' thumb_nsfw';
                    }
                    if ($data['nsfw_ans']) {
                        $thumbnail_class .= ' thumb_nsfw_consent';
                    }

                    if ($item['media_count'] > 1) {
                        $multi_image = true;
                    }
                }
                $thumbnail = Utility::getThumbnailUrl($item, $nsfw_ans);
                if ($item['media_count'] == 0) {
                    $raw_thumbnail = Utility::getThumbnailUrl($item, $nsfw_ans);
                } else {
                    $raw_thumbnail = Utility::getThumbnailUrl($item, true);
                }

                $articles[$key] = $item;
                $articles[$key]['url'] = SITE_URL . Environment::getLogUrl($item);
                $articles[$key]['created_at'] = s($item['created_at']);
                $articles[$key]['title'] = $title;
                $articles[$key]['caption'] = Utility::createCaption($item['contents']);;
                $articles[$key]['nsfw_type'] = $item['nsfw'] ? '0' : '1';
                $articles[$key]['nsfw_status'] = $data['nsfw_ans'] ? '0' : '1';
                $articles[$key]['thumbnail_class'] = $thumbnail_class;
                $articles[$key]['thumbnail_path'] =  $thumbnail;
                $articles[$key]['raw_thumbnail_path'] =  $raw_thumbnail;
                $articles[$key]['thumbnail_title'] = $thumbnail_title;
                $articles[$key]['multi_image'] = $multi_image;

                if ($item['thumbnail_type'] == 2) {
                    //全画像を表示する場合、記事を複製
                    $base_article_url = $articles[$key]['url'];
                    foreach ($item['media'] as $media_index => $media) {
                        if ($media_index == 0) {
                            continue;
                        }
                        $key++;

                        $raw_thumbnail = Utility::getThumbnailUrl($item, true, $media_index);
                        $thumbnail = Utility::getThumbnailUrl($item, $nsfw_ans, $media_index);
                        $media_index_link = $media_index + 1;

                        $articles[$key] = $articles[$key - 1];
                        $articles[$key]['raw_thumbnail_path'] = $raw_thumbnail;
                        $articles[$key]['thumbnail_path'] =  $thumbnail;
                        $articles[$key]['url'] = $base_article_url . "#$media_index_link";
                    }
                }
                $key++;
            }

            //ページネーション
            $pages = ceil($count / $this->setting->getValue('index_articles', 30));
        }

        //テンプレートに適用
        $template_name = 'template2_index.php';
        $template = ThemeService::getThemeTemplate($template_name, $this->db, $this->setting);

        self::setSiteData($template); //サイト関連情報を設定
        self::setSystemArea($template); //管理系情報を設定
        $template->set_data('api', new PluginApiService($this->db, $this->setting, $nsfw_ans));

        //ページ情報群
        $template->set_data_h('page_description', $this->setting->getValue('og_text', ''), true);
        $template->set_data_h('page_keywords', '');
        $template->set_data_h('page_author', $this->setting->GetValue('display_name', ''));
        $template->set_data_h('page_title', $this->setting->getValue('site_title', ''), true);
        $template->set_data_h('page_url', SITE_URL, true);
        $template->set_data_h('page_type', 'index');
        $template->set_data_h('page_og_image', '');
        $template->set_data_h('home_menu', $home_menu);

        //インデックス固有情報群
        $template->set_data('contents', $contents);
        $template->set_data('tag_links_html', $this->createTagLinks());
        $template->set_data('accounts', $accounts);
        $template->set_data('articles', $articles);
        $template->set_data('pagination', $this->createPagination($show_indexes[0], $pages));

        $template->display();

        return null;
    }

    private function createTagLinks(): string
    {
        include('./env/tagcloud.php');
        return $tagcloud_links . $tagcloud_links_more;
    }

    private function createPagination($current_index, $pages): array
    {
        $pagination = [];
        $min_page = max(1, $current_index < 5 ? 1 : $current_index - 5);
        $max_page = min($pages, $min_page + 9);

        if ($current_index >= 5) {
            $max_page = min($pages, $current_index + 5);
            $min_page = max(1, $max_page - 10);
        }

        for ($i = $min_page; $i <= $max_page; $i++) {
            if ($i == $current_index) {
                $pagination[] = ['index' => $i, 'is_current' => true, 'is_first' => $i == 1, 'is_last' => $i == $pages, 'is_page_first' => ($i == $min_page && $i != 1), 'is_page_last' => ($i == $max_page && $i != $pages), 'url' => ''];
            } else {
                $pagination[] = ['index' => $i, 'is_current' => false, 'is_first' => $i == 1, 'is_last' => $i == $pages, 'is_page_first' => ($i == $min_page && $i != 1), 'is_page_last' => ($i == $max_page && $i != $pages), 'url' => "?page={$i}"];
            }
        }
        return $pagination;
    }
}
