<?php

namespace App\Http\Controllers;

use App\Comment;
use App\CommentDetail;
use App\Http\Resources\CommentResource;
use App\Http\Resources\TopicResource;
use App\Quote;
use App\Rank;
use App\Topic;
use http\Env\Response;
use Illuminate\Http\Request;
use function GuzzleHttp\Psr7\str;
use Validator;

class CommentController extends Controller
{
    public function topic($code = 0)
    {
        $topic = Topic::select('id', 'code')
            ->published()
            ->where('code', $code)
            ->first();
        if (!isset($topic)) return response()->json(['status' => 'error', 'message' => 'Topic is not valid.'], 403);

        $comments = Comment::published()
            ->where('topic_id', $topic->id)
            ->orderBy('id')
            ->paginate(50);

        return CommentResource::collection($comments);
    }

    public function like($id = 0)
    {
        $comment = Comment::published()
            ->where('id', $id)
            ->first();
        if (!isset($comment)) return response()->json(['status' => 'error', 'message' => 'Comment is not valid.'], 403);
        $comment->like += 1;
        $comment->save();

        return response()->json(['status' => 'success'], 200);
    }

    public function dislike($id = 0)
    {
        $comment = Comment::published()
            ->where('id', $id)
            ->first();
        if (!isset($comment)) return response()->json(['status' => 'error', 'message' => 'Comment is not valid.'], 403);
        $comment->dislike += 1;
        $comment->save();

        return response()->json(['status' => 'success'], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
                'code'    => ['required'],
                'content' => ['required']
            ]
        );
        if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
        $params = $request->all();

        $topic = Topic::select('id', 'code', 'total_comment')
            ->published()
            ->where('code', $params['code'])
            ->first();
        if (!isset($topic)) return response()->json(['status' => 'error', 'message' => 'Topic is not valid.'], 403);

        $commentData = [
            'topic_id'         => $topic->id,
            /*'parent_id'        => 0,*/
            'content'          => $params['content'],
            'like'             => 0,
            'dislike'          => 0,
            'author'           => (!$params['is_anonymous']) ? $params['author'] : '',
            'is_anonymous'     => $params['is_anonymous'],
            'is_show_id'       => $params['is_show_id'],
            'is_allow_comment' => true,
            'created_at'       => date('Y-m-d H:i:s'),
            'updated_at'       => date('Y-m-d H:i:s')
        ];
        if (isset($params['has_thumbnail']) && $params['has_thumbnail'] != false && $params['thumbnail'] != "") {
            $commentData['image'] = CommentResource::saveImage($params['thumbnail']);
        }
        $comment = Comment::create($commentData);
        if ($params['is_show_id'] == true) {
            $comment->idx = $comment->id;
        } else {
            $lastIndex = Comment::published()->where('topic_id', $topic->id)->count();
            $comment->idx = ($lastIndex == 0) ? 1 : $lastIndex;
        }
        $comment->save();

        $rows = preg_split('/\r\n|\r|\n/', $params['content']);
        $insertCommentDetail = [];
        $checkQuoteExist = [];

        foreach ($rows as $row) {
            if (!empty($row) && $row != "") {
                $quotesData = trim($row);
                $quotesData = str_replace("\r\n", "", $quotesData);
                $quotesData = str_replace("\r", "", $quotesData);
                $quotesData = str_replace("\n", "", $quotesData);
                if (preg_match('#^>>#i', $quotesData) === 1) {
                    $quotesId = str_replace(">>", "", $quotesData);
                    $commentQuote = Comment::published()->where('topic_id', $topic->id)->where('idx', $quotesId)->first();
                    if (isset($commentQuote) && !in_array($quotesId, $checkQuoteExist)) {
                        Quote::create([
                            'parent_id'  => $commentQuote->id,
                            'comment_id' => $comment->id,
                            'content'    => $quotesData,
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                        $checkQuoteExist[] = $quotesId;
                    }
                } else {
                    $cmtData = [
                        'comment_id'  => $comment->id,
                        'content'     => $row,
                        'title'       => '',
                        'domain'      => '',
                        'description' => '',
                        'thumbnail'   => 'noimg@2x.png',
                        'current_img' => -1,
                        'is_url'      => 0,
                        'created_at'  => date('Y-m-d H:i:s'),
                        'updated_at'  => date('Y-m-d H:i:s')
                    ];

                    if (preg_match('#^https?://#i', $row) === 1) {
                        $meta = CommentResource::getMetaInfo($row);
                        if (count($meta) > 0) {
                            $cmtData['is_url'] = 1;
                            if (isset($meta['domain']) && $meta['domain'] != "") $cmtData['domain'] = $meta['domain'];
                            if (isset($meta['title']) && $meta['title'] != "") $cmtData['title'] = $meta['title'];
                            $thumb = '';
                            if (isset($meta['metaTags']) && is_array($meta['metaTags']) && count($meta['metaTags']) > 0) {
                                if (isset($meta['metaTags']['description']) && $meta['metaTags']['description'] != "") {
                                    $cmtData['description'] = $meta['metaTags']['description'];
                                } elseif (isset($meta['metaTags']['twitter_description']) && $meta['metaTags']['twitter_description'] != "") {
                                    $cmtData['description'] = $meta['metaTags']['twitter_description'];
                                }
                                if (isset($meta['metaTags']['twitter_image']) && $meta['metaTags']['twitter_image'] != "") {
                                    $thumb = $meta['metaTags']['twitter_image'];
                                }
                            }
                            if ($thumb == '' && isset($meta['metaTags']['images']) && is_array($meta['metaTags']['images']) && count($meta['metaTags']['images'])) {
                                foreach ($meta['metaTags']['images'] as $img) {
                                    if ($img['data_src'] != "") {
                                        $thumb = $img['data_src'];
                                    } elseif ($img['src_set'] != "") {
                                        $thumb = $img['src_set'];
                                    } elseif ($img['src'] != "") {
                                        $thumb = $img['src'];
                                    }
                                    if ($thumb != '') break;
                                }
                            }

                            if ($thumb != '' && preg_match('#^https?://#i', $thumb) === 1) {
                                $cmtData['thumbnail'] = CommentResource::createThumb($thumb);
                                $cmtData['current_img'] = 0;
                            }
                        }
                    }
                    $insertCommentDetail[] = $cmtData;
                }
            }
        }
        if (count($insertCommentDetail) > 0) CommentDetail::insert($insertCommentDetail);
        $topic->total_comment += 1;
        $topic->save();

        return new CommentResource($comment);
    }

    public function storeSub($code = 0, Request $request)
    {
        $validator = Validator::make($request->all(), [
                'content' => ['required']
            ]
        );
        if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
        $params = $request->all();

        $topic = Topic::select('id', 'code', 'total_comment')
            ->published()
            ->where('code', $code)
            ->first();
        if (!isset($topic)) return response()->json(['data' => ['status' => 'error', 'message' => 'Topic is not valid.']], 403);

        $commentData = [
            'topic_id'         => $topic->id,
            'content'          => $params['content'],
            'like'             => 0,
            'dislike'          => 0,
            'author'           => (!$params['is_anonymous']) ? $params['author'] : '',
            'is_anonymous'     => $params['is_anonymous'],
            'is_show_id'       => $params['is_show_id'],
            'is_allow_comment' => true,
            'created_at'       => date('Y-m-d H:i:s'),
            'updated_at'       => date('Y-m-d H:i:s')
        ];
        if (isset($params['has_thumbnail']) && $params['has_thumbnail'] != false && $params['thumbnail'] != "") {
            $commentData['image'] = CommentResource::saveImage($params['thumbnail']);
        }
        $comment = Comment::create($commentData);
        if ($params['is_show_id'] == true) {
            $comment->idx = $comment->id;
        } else {
            $lastIndex = Comment::published()->where('topic_id', $topic->id)->count();
            $comment->idx = ($lastIndex == 0) ? 1 : $lastIndex;
        }
        $comment->save();

        $rows = preg_split('/\r\n|\r|\n/', $params['content']);
        $insertCommentDetail = [];
        $checkQuoteExist = [];

        foreach ($rows as $row) {
            if (!empty($row) && $row != "") {
                $quotesData = trim($row);
                $quotesData = str_replace("\r\n", "", $quotesData);
                $quotesData = str_replace("\r", "", $quotesData);
                $quotesData = str_replace("\n", "", $quotesData);

                if (preg_match('#^>>#i', $quotesData) === 1) {
                    $quotesId = str_replace(">>", "", $quotesData);
                    $commentQuote = Comment::published()->where('topic_id', $topic->id)->where('idx', $quotesId)->first();
                    if (isset($commentQuote) && !in_array($quotesId, $checkQuoteExist)) {
                        Quote::create([
                            'parent_id'  => $commentQuote->id,
                            'comment_id' => $comment->id,
                            'content'    => $quotesData,
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                        $checkQuoteExist[] = $quotesId;
                    }
                } else {
                    $cmtData = [
                        'comment_id'  => $comment->id,
                        'content'     => $row,
                        'title'       => '',
                        'domain'      => '',
                        'description' => '',
                        'thumbnail'   => 'noimg@2x.png',
                        'current_img' => -1,
                        'is_url'      => 0,
                        'created_at'  => date('Y-m-d H:i:s'),
                        'updated_at'  => date('Y-m-d H:i:s')
                    ];

                    if (preg_match('#^https?://#i', $row) === 1) {
                        $meta = CommentResource::getMetaInfo($row);
                        if (count($meta) > 0) {
                            $cmtData['is_url'] = 1;
                            if (isset($meta['domain']) && $meta['domain'] != "") $cmtData['domain'] = $meta['domain'];
                            if (isset($meta['title']) && $meta['title'] != "") $cmtData['title'] = $meta['title'];
                            $thumb = '';
                            if (isset($meta['metaTags']) && is_array($meta['metaTags']) && count($meta['metaTags']) > 0) {
                                if (isset($meta['metaTags']['description']) && $meta['metaTags']['description'] != "") {
                                    $cmtData['description'] = $meta['metaTags']['description'];
                                } elseif (isset($meta['metaTags']['twitter_description']) && $meta['metaTags']['twitter_description'] != "") {
                                    $cmtData['description'] = $meta['metaTags']['twitter_description'];
                                }
                                if (isset($meta['metaTags']['twitter_image']) && $meta['metaTags']['twitter_image'] != "") {
                                    $thumb = $meta['metaTags']['twitter_image'];
                                }
                            }
                            if ($thumb == '' && isset($meta['metaTags']['images']) && is_array($meta['metaTags']['images']) && count($meta['metaTags']['images'])) {
                                foreach ($meta['metaTags']['images'] as $img) {
                                    if ($img['data_src'] != "") {
                                        $thumb = $img['data_src'];
                                    } elseif ($img['src_set'] != "") {
                                        $thumb = $img['src_set'];
                                    } elseif ($img['src'] != "") {
                                        $thumb = $img['src'];
                                    }
                                    if ($thumb != '') break;
                                }
                            }

                            if ($thumb != '' && preg_match('#^https?://#i', $thumb) === 1) {
                                $cmtData['thumbnail'] = CommentResource::createThumb($thumb);
                                $cmtData['current_img'] = 0;
                            }
                        }
                    }
                    $insertCommentDetail[] = $cmtData;
                }
            }
        }
        if (count($insertCommentDetail) > 0) CommentDetail::insert($insertCommentDetail);
        $topic->total_comment += 1;
        $topic->save();
        $rsComment = Comment::with('detail', 'quote')->where('id', $comment->id)->first();

        return response()->json(['data' => $rsComment], 200); /*return new CommentResource($comment);*/
    }

    public function getPaginate($code = 0, $page = 1)
    {
        $page = (int)$page;
        $topic = Topic::select('id', 'code')
            ->published()
            ->where('code', $code)
            ->first();

        $rsData = [
            'first'        => 1,
            'prev'         => ($page > 1) ? $page - 1 : null,
            'current_page' => $page,
            'next'         => null,
            'last'         => null,
            'total'        => null,
            'list'         => []
        ];
        if (isset($topic)) {
            $countComment = Comment::published()
                ->where('topic_id', $topic->id)
                ->count();

            $totalPage = floor(($countComment / 500));
            if (($countComment % 500) != 0) {
                $totalPage += 1;
            }

            $rsData['total'] = $countComment;
            $rsData['last'] = $totalPage;
            $rsData['next'] = ($page < $totalPage) ? $page + 1 : null;

            if ($totalPage <= 10) {
                for ($i = 1; $i <= $totalPage; $i++) {
                    $rsData['list'][] = $i;
                }
            } else {
                if ($page <= 4) {
                    if ($page - 3 > 0) $rsData['list'][] = $page - 3;
                    if ($page - 2 > 0) $rsData['list'][] = $page - 2;
                    if ($page - 1 > 0) $rsData['list'][] = $page - 1;
                    $rsData['list'][] = $page;
                    $rsData['list'][] = $page + 1;
                    $rsData['list'][] = $page + 2;
                    $rsData['list'][] = '...';
                    $rsData['list'][] = $totalPage - 1;
                    $rsData['list'][] = $totalPage;
                } else {
                    if ($page < ($totalPage - 4)) {
                        $rsData['list'][] = 1;
                        $rsData['list'][] = 2;
                        $rsData['list'][] = '...';
                        $rsData['list'][] = $page - 1;
                        $rsData['list'][] = $page;
                        $rsData['list'][] = $page + 1;
                        $rsData['list'][] = $page + 2;
                        $rsData['list'][] = '...';
                        $rsData['list'][] = $totalPage - 1;
                        $rsData['list'][] = $totalPage;
                    } else {
                        $rsData['list'][] = 1;
                        $rsData['list'][] = 2;
                        $rsData['list'][] = '...';
                        $rsData['list'][] = $page - 2;
                        $rsData['list'][] = $page - 1;
                        $rsData['list'][] = $page;
                        for ($i = $page + 1; $i <= $totalPage; $i++) {
                            $rsData['list'][] = $i;
                        }
                    }
                }
            }
        }

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

    public function show($code = 0, $idx = 0)
    {
        $topic = Topic::select('id', 'code')
            ->published()
            ->where('code', $code)
            ->first();
        if (!isset($topic)) return response()->json(['data' => ['status' => 'error', 'message' => 'Topic is not valid.']], 403);

        $comment = Comment::with('detail')->published()
            ->where('topic_id', $topic->id)
            ->where('idx', $idx)
            ->first();
        if (!isset($comment)) return response()->json(['data' => ['status' => 'error', 'message' => 'Comment is not valid.']], 403);

        return new CommentResource($comment);
    }

    public function getSubComment($code = 0, $idx = 0)
    {
        $topic = Topic::select('id', 'code')
            ->published()
            ->where('code', $code)
            ->first();
        if (!isset($topic)) return response()->json(['data' => ['status' => 'error', 'message' => 'Topic is not valid.']], 403);

        $comment = Comment::published()
            ->where('topic_id', $topic->id)
            ->where('idx', $idx)
            ->first();
        if (!isset($comment)) return response()->json(['data' => ['status' => 'error', 'message' => 'Comment is not valid.']], 403);
        $quotes = Quote::with('comment')->where('parent_id', $comment->id)->orderBy('id')->paginate(200);

        return response()->json($quotes, 200);
    }
}
