<?php

namespace App\Http\Controllers;

use App\Fortuneteller;
use App\Keyword;
use App\KeywordDetail;
use App\ShopMeta;
use App\ShopSlider;
use Illuminate\Http\Request;
use App\Article;
use Illuminate\Support\Arr;
use App\Http\Resources\ArticleResource;
use Illuminate\Support\Facades\Cache;

class ArticleController extends Controller
{
    const ITEM_PER_PAGE = 10;

    public function index(Request $request)
    {
        $params = $request->all();
        $limit = Arr::get($params, 'limit', static::ITEM_PER_PAGE);
        $keyword = Arr::get($params, 'keyword', '');
        $teller = Arr::get($params, 'teller', '');
        $shop = Arr::get($params, 'shop', '');

        $list = Article::select('id', 'title', 'slug', 'thumbnail', 'publish_at', 'description')
            ->where('is_activated', true)
            ->where('is_deleted', false);

        if ($keyword != null && $keyword != "") {
            $keywordItem = Keyword::where('is_deleted', 0)
                ->where(function ($query) use ($keyword) {
                    $query->where('name', $keyword)
                        ->orWhere('name', strtolower($keyword))
                        ->orWhere('name', strtoupper($keyword))
                        ->orWhere('name', ucfirst($keyword));
                })->first();

            $listDetailKeyword = [];
            if (isset($keywordItem) && $keywordItem->id != null) {
                $listDetailKeyword = KeywordDetail::select('ref_id')
                    ->where('keyword_id', $keywordItem->id)
                    ->where('type', 'article')
                    ->pluck('ref_id')
                    ->toArray();
            }

            $list = $list->where(function ($query) use ($keyword, $listDetailKeyword) {
                $query->where('title', 'like', "%$keyword%")
                    ->orWhere('description', 'like', "%$keyword%")
                    ->orWhereIn('id', $listDetailKeyword);
            });
        }

        if ($teller != null && $teller != "") {
            $list = $list->where('fortune_teller_id', $teller);
        }
        if ($shop != null && $shop != "") {
            $tellerIds = Fortuneteller::select('id')->isPublished()->where('shop_id', $shop)->pluck('id')->toArray();
            $list = $list->whereIn('fortune_teller_id', $tellerIds);
        }
        $list = $list->orderBy('created_at', 'DESC');

        return ArticleResource::collection($list->paginate($limit));
    }

    public function recent(Request $request)
    {
        $params = $request->all();
        $limit = Arr::get($params, 'limit', static::ITEM_PER_PAGE);
        $list = Article::select('id', 'title', 'slug', 'thumbnail', 'publish_at')
            ->where('is_activated', true)
            ->where('is_deleted', false)
            ->orderBy('created_at', 'DESC');

        return ArticleResource::collection($list->paginate($limit));
    }

    public function ranking(Request $request)
    {
        $params = $request->all();
        $limit = Arr::get($params, 'limit', static::ITEM_PER_PAGE);
        $list = Article::select('id', 'title', 'slug', 'thumbnail', 'publish_at')
            ->where('is_activated', true)
            ->where('is_deleted', false)
            ->orderBy('important', 'DESC')
            ->orderBy('view_number', 'DESC')
            ->orderBy('created_at', 'DESC');

        return ArticleResource::collection($list->paginate($limit));
    }

    public function rankingList(Request $request)
    {
        $params = $request->all();
        $limit = Arr::get($params, 'limit', static::ITEM_PER_PAGE);

        $year = Article::select('id', 'title', 'slug', 'thumbnail', 'publish_at')
            ->where('is_activated', true)
            ->where('is_deleted', false)
            ->orderBy('important', 'DESC')
            ->orderBy('view_number', 'DESC')
            ->orderBy('created_at', 'DESC')
            ->paginate($limit);

        $month = Article::select('id', 'title', 'slug', 'thumbnail', 'publish_at')
            ->where('is_activated', true)
            ->where('is_deleted', false)
            ->orderBy('id', 'ASC')->paginate($limit);

        $week = Article::select('id', 'title', 'slug', 'thumbnail', 'publish_at')
            ->where('is_activated', true)
            ->where('is_deleted', false)
            ->orderBy('important', 'DESC')
            ->orderBy('created_at', 'ASC')
            ->paginate($limit);

        return response()->json(['year' => $year, 'month' => $month, 'week' => $week], 200);
    }

    public function featureRecent(Request $request)
    {
        $params = $request->all();
        $limit = Arr::get($params, 'limit', static::ITEM_PER_PAGE);
        $list = Article::select('id', 'title', 'slug', 'description', 'thumbnail', 'content', 'publish_at')
            ->where('is_activated', true)
            ->where('is_deleted', false)
            ->orderBy('created_at', 'DESC')
            ->limit($limit)
            ->get();

        return response()->json(['data' => $list], 200);
    }

    public function hot(Request $request)
    {
        $params = $request->all();
        $limit = Arr::get($params, 'limit', static::ITEM_PER_PAGE);
        $list = Article::select('id', 'title', 'slug', 'thumbnail', 'description', 'publish_at')
            ->where('is_activated', true)
            ->where('is_deleted', false)
            ->orderBy('important', 'DESC')
            ->orderBy('created_at', 'DESC');

        return ArticleResource::collection($list->paginate($limit));
    }

    private function contentBetweenTags($content, $tagname){
        $pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
        preg_match($pattern, $content, $matches);

        if(empty($matches)) return "";

        $str = "<$tagname>".html_entity_decode($matches[1])."</$tagname>";
        return $str;
    }

    public function show(Request $request, $slug = '')
    {
        $preview = '';
        if ($request->has('preview') && $request->get('preview') != "" && $request->get('preview') != null && $request->get('preview') != "null") $preview = $request->get('preview');

        $cacheKey = "article_show_" . str_replace("-", "_", trim($slug));
        if ($preview != "" && $preview != null) {
            $list = Cache::remember($cacheKey . "_" . $preview, (7 * 24 * 60 * 60), function () use($slug, $preview) {
                $article = Article::select('slug', 'title', 'description', 'content', 'keyword', 'important', 'thumbnail', 'type', 'publish_at')
                    ->where('is_deleted', false)
                    ->where('slug', $slug)
                    ->where('preview', $preview)
                    ->first();
                if (!empty($article->content)) $article->content = $this->detectLinkContent($article->content);
                return ['item' => $article, 'lastModify' => (gmdate('D, d M Y H:i:s') . ' GMT')];
            });
        } else {
            $list = Cache::remember($cacheKey, (7 * 24 * 60 * 60), function () use($slug) {
                $article = Article::select('slug', 'title', 'description', 'content', 'keyword', 'important', 'thumbnail', 'type', 'publish_at')
                    ->where('is_deleted', false)
                    ->where('is_activated', true)
                    ->where('slug', $slug)
                    ->first();
                if (!empty($article->content)) $article->content = $this->detectLinkContent($article->content);
                return ['item' => $article, 'lastModify' => (gmdate('D, d M Y H:i:s') . ' GMT')];
            });
        }

        /*$relate = Article::select('slug', 'title', 'description', 'content', 'keyword', 'important', 'thumbnail', 'type', 'publish_at')
            ->where('is_deleted', false)
            ->where('is_activated', true)
            ->where('slug', '!=', $slug)
            ->orderBy('publish_at', 'DESC')
            ->paginate(20);

        $ranking = Article::select('slug', 'title', 'description', 'content', 'keyword', 'important', 'thumbnail', 'type', 'publish_at')
            ->where('is_deleted', false)
            ->where('is_activated', true)
            ->where('slug', '!=', $slug)
            ->orderBy('important', 'ASC')
            ->orderBy('publish_at', 'DESC')
            ->paginate(10);*/

        return response()->json(['data' => $list['item'], 'relate' => [], 'ranking' => []], 200);
    }

    public function tellerList(Request $request)
    {
        $params = $request->all();
        $limit = Arr::get($params, 'limit', static::ITEM_PER_PAGE);
        $teller = Arr::get($params, 'teller', '');
        $shopId = Arr::get($params, 'shop', '');
        $ids = [];
        if ($teller != null && $teller != "") $ids[] = $teller;
        if ($shopId != null && $shopId != "") {
            $tellerIds = Fortuneteller::select('id')->isPublished()->where('shop_id', $shopId)->pluck('id')->toArray();
            $ids = array_merge($ids, $tellerIds);
        }

        $list = Article::select('id', 'title', 'slug', 'thumbnail', 'publish_at', 'description', 'user_id')
            ->where('is_activated', true)
            ->where('is_deleted', false)
            ->whereIn('fortune_teller_id', $ids)
            ->orderBy('important', 'DESC')
            ->orderBy('created_at', 'DESC');

        return ArticleResource::collection($list->paginate($limit));
    }

    private function detectLinkContent($content) {
        $pattern = "#<\b[^>]*><\s*?a\b[^>]*>(.*?)</a\b[^>]*></\b[^>]*>#s";
        preg_match_all($pattern, $content, $matches);
        $rootTags = $matches[0];
        $linkTags = $matches[1];
        $history = ['teller' => [], 'shop' => []];
        $listLinks = [];

        foreach ($linkTags as $key => $item) {
            $item = strip_tags($item);
            if (strpos($item, "uramori.jp/shop/detail/") !== false || strpos($item, "127.0.0.1:8000/shop/detail/") !== false) {
                $item = str_replace("/shop/detail/", "|", $item);
                $shopInfo = explode("|", $item);
                $shopId = isset($shopInfo[1]) ? $shopInfo[1] : 0;

                $listInfo = "";
                if (isset($history['shop'][$shopId])) {
                    $listInfo = $history['shop'][$shopId];
                } else {
                    $sliders = ShopSlider::select('name', 'file_name')->where('shop_id', $shopId)->where('type', 'slider')->get();
                    if ($sliders->count() > 0) {
                        if (count($sliders) > 0) {
                            $imgUrls = '';
                            $imgDots = '';
                            foreach ($sliders as $k => $img) {
                                $imgUrls .= '<div class="slider-item fade"><div class="numbertext">' . ($k + 1) . ' / ' . count($sliders) . '</div>
                                    <img src="' . url("uploads/image/shop/thumb_760x550/" . $img->file_name) . '" ></div>';
                                $imgDots .= '<span class="dot"><img src="' . url("uploads/image/shop/thumb_760x550/" . $img->file_name) . '" ></span>';
                            }
                            $listInfo .= '<div class="c_slider_wrapper">
                                            <div class="slideshow-container">
                                                ' . $imgUrls . '
                                                <a class="prev">&#10094;</a><a class="next">&#10095;</a>
                                                <div class="thumbs">' . $imgDots . '</div>
                                            </div>
                                          </div>';
                        }
                    }

                    $shopMetas = ShopMeta::select('title', 'content')->where('shop_id', $shopId)->orderBy('order')->get();
                    foreach ($shopMetas as $meta) {
                        $listInfo .= '<div class="s_item"><div class="s_item_title">' . $meta->title . '</div><div class="s_item_content"><span>' . $meta->content . '</span></div></div>';
                    }
                    $history['shop'][$shopId] = $listInfo;
                }
                if ($listInfo != "") $content = str_replace($rootTags[$key], "<div class='shop_refer'>".$listInfo."</div>", $content);
            }

            if (strpos($item, "uramori.jp/fortune-teller/detail/") !== false || strpos($item, "127.0.0.1:8000/fortune-teller/detail/") !== false) {
                $item = str_replace("/fortune-teller/detail/", "|", $item);
                $tellerInfo = explode("|", $item);
                $code = isset($tellerInfo[1]) ? $tellerInfo[1] : 0;

                $listTellerInfo = "";
                if (isset($history['teller'][$code])) {
                    $listTellerInfo = $history['teller'][$code];
                } else {
                    $fortuneteller = Fortuneteller::with('shopMeta', 'profile')
                        ->isPublished()
                        ->where(function ($query) use ($code) {
                            $query->where('id', $code)
                                ->orWhere('slug', $code)
                                ->orWhere('number', $code);
                        })
                        ->first();

                    if (isset($fortuneteller) && $fortuneteller->id != null) {
                        $strTellerInfo = '';
                        foreach ($fortuneteller->profile as $p) {
                            $strTellerInfo .= '<tr><th>' . $p->title . '</th><td>' . $p->content . '</td></tr>';
                        }

                        $strTellerMeta = '';
                        foreach ($fortuneteller->shopMeta as $m) {
                            $strTellerMeta .= '<tr><td>' . $m->title . '</td><td>' . $m->content . '</td></tr>';
                        }

                        $gender = '男性';
                        if ($fortuneteller->gender == 0) $gender = '女性';
                        if ($fortuneteller->gender != 0 && $fortuneteller->gender != 1) $gender = 'LGBT';
                        $cost = ($fortuneteller->cost != '' && $fortuneteller->cost != null) ? $fortuneteller->cost : '～';

                        $listTellerInfo .= '<div class="teller_info">
                            <div class="teller_number">
                                <div class="t_n_num">' . $fortuneteller->number . '</div>
                                <div class="t_n_name">
                                    <p>' . $fortuneteller->display_name . ' 占い師</p>
                                    <p>' . $fortuneteller->name . '</p>
                                </div>
                                <div class="t_n_price">
                                    <p>性別：' . $gender . '</p>
                                    <p><i class="el-icon-phone-outline"></i>' . $cost . '</p>
                                </div>
                            </div>
                            <div class="teller_profile">
                                <div class="avatar">
                                    <img src="' . url('uploads/files/blank.webp') . '" style="background-image: url(' . url('uploads/files/' . $fortuneteller->avatar) . ');">
                                </div>
                                <table>' . $strTellerInfo . '</table>
                            </div>
                            <div class="teller_meta">
                                <label class="on_off_desc">続きを読む</label>
                                <div class="more_info_meta">
                                    <h3><span>所属・料金</span></h3>
                                    <table>
                                        <tbody>' . $strTellerMeta . '</tbody>
                                    </table>
                                </div>
                            </div>
                        </div>';

                        $listLinks[] = [
                            'name'  => [
                                $fortuneteller->display_name . "（" . $fortuneteller->name . "）" . "占い師",
                                $fortuneteller->display_name . " (" . $fortuneteller->name . ") " . "占い師",
                                $fortuneteller->display_name . "(" . $fortuneteller->name . ")" . "占い師",
                                $fortuneteller->display_name . "( " . $fortuneteller->name . " )" . "占い師",
                                $fortuneteller->display_name . "　（" . $fortuneteller->name . "）　" . "占い師",
                                $fortuneteller->display_name . "　（　" . $fortuneteller->name . "　）　" . "占い師",
                            ],
                            'link'  => url('fortune-teller/detail/' . $fortuneteller->slug)
                        ];
                    }
                    $history['teller'][$code] = $listTellerInfo;
                }
                if ($listTellerInfo != "") $content = str_replace($rootTags[$key], $listTellerInfo, $content);
            }
        }

        if (count($listLinks) > 0) {
            $patternHeading = "#<\s*?h2\b[^>]*>(.*?)</h2\b[^>]*>#s";
            preg_match_all($patternHeading, $content, $matchesHeading);
            $rootHeadingTags = $matchesHeading[0];
            $linkHeadingTags = $matchesHeading[1];

            foreach ($linkHeadingTags as $key => $item) {
                $headerContent = strip_tags($item);
                $headerContent = trim(str_replace("&nbsp;", " ", $headerContent));
                $headerContent = trim(str_replace("  ", " ", $headerContent));
                $headerContent = trim(str_replace("  ", " ", $headerContent));

                if ($headerContent != null && $headerContent != "" && !empty($headerContent)) {
                    foreach ($listLinks as $link) {
                        if (in_array($headerContent, $link['name'])) {
                            $rootText = str_replace($item, '<a href="' . $link['link'] . '">' . $item . '</a>', $rootHeadingTags[$key]);
                            $content = str_replace($rootHeadingTags[$key], $rootText, $content);
                        }
                    }
                } else {
                    $content = str_replace($rootHeadingTags[$key], '<p>&nbsp;</p>', $content);
                }
            }
        }

        $content = str_replace('<h2></h2>', '<p>&nbsp;</p>', $content);
        $content = str_replace('<h2>&nbsp;</h2>', '<p>&nbsp;</p>', $content);
        $content = str_replace('<h2>&nbsp;&nbsp;</h2>', '<p>&nbsp;</p>', $content);
        $content = str_replace('<h2>&nbsp;&nbsp;&nbsp;</h2>', '<p>&nbsp;</p>', $content);
        $content = str_replace('<h2>&nbsp;&nbsp;&nbsp;&nbsp;</h2>', '<p>&nbsp;</p>', $content);
        $content = str_replace('href="../', 'href="/', $content);

        return $content;
    }
}
