<?php

namespace App\Http\Controllers\Admin;

use App\Comment;
use App\CommentDetail;
use App\Http\Controllers\Controller;
use App\Keyword;
use App\Rank;
use App\TopicKeyword;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use App\Topic;
use App\Http\Resources\Admin\TopicResource;
use Validator;

/**
 * Class TopicController
 *
 * @package App\Http\Controllers
 */
class TopicController extends Controller
{
    const ITEM_PER_PAGE = 100;

    public function index(Request $request)
    {
        $searchParams = $request->all();
        $list = Topic::notDeleted();
        $limit = Arr::get($searchParams, 'limit', static::ITEM_PER_PAGE);
        $keyword = Arr::get($searchParams, 'keyword', '');
        $categoryId = Arr::get($searchParams, 'category', '');
        $status = Arr::get($searchParams, 'status', '');

        if (!empty($keyword)) {
            $list->where('title', 'LIKE', '%' . $keyword . '%');
        }
        if ($categoryId != '') {
            $list->where('category_id', $categoryId);
        }
        if ($status != '') {
            $list->where('is_activated', $status);
        }
        $list->orderBy('id', 'DESC');

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

    public function showDeleted(Request $request) {
        $searchParams = $request->all();
        $list = Topic::isDeleted();
        $limit = Arr::get($searchParams, 'limit', static::ITEM_PER_PAGE);
        $keyword = Arr::get($searchParams, 'keyword', '');
        $status = Arr::get($searchParams, 'status', '');

        if (!empty($keyword)) {
            $list->where('title', 'LIKE', '%' . $keyword . '%');
        }
        if ($status != '') {
            $list->where('is_activated', $status);
        }
        $list->orderBy('updated_at', 'DESC');

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

    public function show($id = 0)
    {
        $topic = Topic::with('rank', 'keyword_list', 'firstComment')->notDeleted()->where('id', $id)->first();
        if (!isset($topic)) return response()->json(['errors' => 'Topic is not valid'], 403);

        return response()->json(['data' => $topic]);
        /*return new TopicResource($topic);*/
    }

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

        $params = $request->all();
        $thumbnail = 'noimg@2x.png';
        if ($params['thumbnail'] != "") {
            $thumbnail = TopicResource::createThumb($params['thumbnail']);
        }

        $publishDate = ($params['publishDate'] != "") ? $params['publishDate'] : date('Y-m-d');
        $rank = Rank::where('created_date', $publishDate)->first();
        if (!isset($rank)) {
            $checkMax = Rank::orderBy('rank_number', 'DESC')->first();
            $rank_number = isset($checkMax) ? $checkMax->rank_number : 0;
            $rank_number += 1;
            $rank = Rank::create([
                'created_date' => $publishDate,
                'rank_number'  => $rank_number,
                'total_post'   => 1,
                'created_at'   => date('Y-m-d H:i:s'),
                'updated_at'   => date('Y-m-d H:i:s')
            ]);
        }

        $topic = Topic::create([
            'code'             => TopicResource::generateCode(),
            'title'            => $params['title'],
            'thumbnail'        => $thumbnail,
            'author'           => (!$params['is_anonymous']) ? $params['author'] : '',
            'rank_id'          => $rank->id,
            'category_id'      => ($params['category_id'] != "") ? $params['category_id'] : null,
            'seo_robots'       => $params['seo_robots'],
            'seo_title'        => $params['seo_title'],
            'seo_description'  => $params['seo_description'],
            'seo_keywords'     => $params['seo_keywords'],
            'is_allow_comment' => $params['is_allow_comment'],
            'is_activated'     => $params['is_activated'],
            'created_at'       => date('Y-m-d H:i:s'),
            'updated_at'       => date('Y-m-d H:i:s')
        ]);

        $commentData = [
            'topic_id'         => $topic->id,
            'content'          => $params['content'],
            'author'           => (!$params['is_anonymous']) ? $params['author'] : '',
            'is_anonymous'     => $params['is_anonymous'],
            'is_show_id'       => $params['is_show_id'],
            'is_allow_comment' => $params['is_allow_comment'],
            'created_at'       => date('Y-m-d H:i:s'),
            'updated_at'       => date('Y-m-d H:i:s')
        ];

        if ($thumbnail != 'noimg@2x.png') $commentData['image'] = $thumbnail;
        $comment = Comment::create($commentData);
        if ($params['is_show_id'] == true) {
            $comment->idx = $comment->id;
        } else {
            $comment->idx = 1;
        }
        $comment->save();

        foreach ($params['urls'] as $item) {
            $cmtData = [
                'comment_id'  => $comment->id,
                'content'     => $item['text'],
                'current_img' => -1,
                'is_url'      => $item['is_url'],
                'created_at'  => date('Y-m-d H:i:s'),
                'updated_at'  => date('Y-m-d H:i:s')
            ];
            if ($item['is_url']) {
                $cmtData['title'] = $item['title'];
                $cmtData['domain'] = $item['domain'];
                $cmtData['description'] = $item['description'];
                $cmtData['current_img'] = $item['current_img'];
                $thumbnailItem = 'noimg@2x.png';
                if ($item['current_img'] > -1 && $item['thumbnail'] != "") {
                    $cmtData['current_img'] = $item['current_img'];
                    $thumbnailItem = TopicResource::createThumb($item['thumbnail']);
                }
                $cmtData['thumbnail'] = $thumbnailItem;
            }
            CommentDetail::create($cmtData);
        }

        if (isset($params['keywords']) && $params['keywords'] != '') {
            $listKeywords = explode("#", $params['keywords']);
            $listKeywordsDetail = [];
            foreach ($listKeywords as $keyword) {
                $keyword = trim($keyword);
                if ($keyword != "" && $keyword != null) {
                    $cKeyword = Keyword::notDeleted()->where('name', $keyword)->first();
                    if (!isset($cKeyword)) {
                        $cKeyword = Keyword::create([
                            'name'         => $keyword,
                            'is_activated' => 1,
                            'is_deleted'   => 0,
                            'created_at'   => date('Y-m-d H:i:s'),
                            'updated_at'   => date('Y-m-d H:i:s')
                        ]);
                    }
                    $listKeywordsDetail[] = ['topic_id' => $topic->id, 'keyword_id' => $cKeyword->id, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')];
                }
            }
            if (count($listKeywordsDetail) > 0) TopicKeyword::insert($listKeywordsDetail);
        }

        return new TopicResource($topic);
    }

    public function update($id = 0, Request $request)
    {
        $validator = Validator::make($request->all(), [
                'title'       => ['required'],
                'content'     => ['required'],
                'urls'        => ['required'],
                'category_id' => ['required'],
            ]
        );
        if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
        $topic = Topic::notDeleted()->where('id', $id)->first();
        $comment = Comment::notDeleted()->where('topic_id', $id)->orderBy('id')->first();
        if (!isset($topic) || !isset($comment)) return response()->json(['errors' => 'Topic is not valid'], 403);

        $params = $request->all();
        if ($params['thumbnail'] != "" && strpos($params['thumbnail'], env('APP_URL')) !== true) {
            $thumbnail = TopicResource::createThumb($params['thumbnail']);
        } else {
            $thumbnail = $topic->thumbnail;
        }

        $rankId = $topic->rank_id;
        if ($params['publishDate'] != "") {
            $publishDate = $params['publishDate'];
            $rank = Rank::where('created_date', $publishDate)->first();
            if (!isset($rank)) {
                $checkMax = Rank::orderBy('rank_number', 'DESC')->first();
                $rank_number = isset($checkMax) ? $checkMax->rank_number : 0;
                $rank_number += 1;
                $rank = Rank::create([
                    'created_date' => $publishDate,
                    'rank_number'  => $rank_number,
                    'total_post'   => 1,
                    'created_at'   => date('Y-m-d H:i:s'),
                    'updated_at'   => date('Y-m-d H:i:s')
                ]);
            }
            $rankId = $rank->id;
        }

        $topic->update([
            'title'            => $params['title'],
            'thumbnail'        => $thumbnail,
            'author'           => (!$params['is_anonymous']) ? $params['author'] : '',
            'rank_id'          => $rankId,
            'category_id'      => $params['category_id'],
            'seo_robots'       => $params['seo_robots'],
            'seo_title'        => $params['seo_title'],
            'seo_description'  => $params['seo_description'],
            'seo_keywords'     => $params['seo_keywords'],
            'is_allow_comment' => $params['is_allow_comment'],
            'is_activated'     => $params['is_activated'],
            'created_at'       => date('Y-m-d H:i:s'),
            'updated_at'       => date('Y-m-d H:i:s')
        ]);

        $comment->update([
            'idx'              => ($params['is_show_id'] == true) ? $comment->id : 1,
            'topic_id'         => $topic->id,
            'content'          => $params['content'],
            'author'           => (!$params['is_anonymous']) ? $params['author'] : '',
            'image'            => $thumbnail,
            'is_anonymous'     => $params['is_anonymous'],
            'is_show_id'       => $params['is_show_id'],
            'is_allow_comment' => $params['is_allow_comment'],
            'created_at'       => date('Y-m-d H:i:s'),
            'updated_at'       => date('Y-m-d H:i:s')
        ]);

        CommentDetail::where('comment_id', $comment->id)->delete();
        foreach ($params['urls'] as $item) {
            $cmtData = [
                'comment_id'  => $comment->id,
                'content'     => $item['text'],
                'current_img' => -1,
                'is_url'      => $item['is_url'],
                'created_at'  => date('Y-m-d H:i:s'),
                'updated_at'  => date('Y-m-d H:i:s')
            ];
            if ($item['is_url']) {
                $cmtData['title'] = $item['title'];
                $cmtData['domain'] = $item['domain'];
                $cmtData['description'] = $item['description'];
                $cmtData['current_img'] = $item['current_img'];

                $cmtData['thumbnail'] = 'noimg@2x.png';
                if ($item['current_img'] > -1 && $item['thumbnail'] != "") {
                    $cmtData['current_img'] = $item['current_img'];
                    if (strpos($params['thumbnail'], env('APP_URL')) !== true) {
                        $cmtData['thumbnail'] = TopicResource::createThumb($item['thumbnail']);
                    } else {
                        $cmtData['thumbnail'] = basename($params['thumbnail']);
                    }
                }
            }
            CommentDetail::create($cmtData);
        }

        if (isset($params['keywords']) && $params['keywords'] != '') {
            TopicKeyword::where('topic_id', $topic->id)->delete();
            $listKeywords = explode("#", $params['keywords']);
            $listKeywordsDetail = [];
            foreach ($listKeywords as $keyword) {
                $keyword = trim($keyword);
                if ($keyword != "") {
                    $cKeyword = Keyword::notDeleted()->where('name', $keyword)->first();
                    if (!isset($cKeyword)) {
                        $cKeyword = Keyword::create([
                            'name'         => $keyword,
                            'is_activated' => 1,
                            'is_deleted'   => 0,
                            'created_at'   => date('Y-m-d H:i:s'),
                            'updated_at'   => date('Y-m-d H:i:s')
                        ]);
                    }
                    $listKeywordsDetail[] = ['topic_id' => $topic->id, 'keyword_id' => $cKeyword->id, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')];
                }
            }
            if (count($listKeywordsDetail) > 0) TopicKeyword::insert($listKeywordsDetail);
        }

        return new TopicResource($topic);
    }

    public function restore($id = 0) {
        $topic = Topic::isDeleted()->where('id', $id)->first();
        if (!isset($topic) || $topic == null) response()->json(['error' => 'Ehhh! Can not restore this topic'], 403);

        try {
            $topic->update(['is_deleted' => false]);
        } catch (\Exception $ex) {
            response()->json(['error' => $ex->getMessage()], 403);
        }

        return response()->json(null, 204);
    }

    public function multipleRestore(Request $request) {
        $validator = Validator::make($request->all(), ['ids' => 'required']);
        if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
        $listIds = $request->get('ids', []);
        $topics = Topic::isDeleted()->whereIn('id', $listIds)->get();
        if ($topics->count() <= 0) response()->json(['error' => 'Topic is not valid.'], 403);
        try {
            Topic::isDeleted()->whereIn('id', $listIds)->update(['is_deleted' => false]);
        } catch (\Exception $ex) {
            response()->json(['error' => $ex->getMessage()], 403);
        }

        return response()->json(null, 204);
    }

    public function actualDestroy($id = 0) {
        $topic = Topic::isDeleted()->where('id', $id)->first();
        if (!isset($topic) || $topic == null) response()->json(['error' => 'Ehhh! Can not delete this topic'], 403);

        try {
            $comments = Comment::select('id')->where('topic_id', $topic->id)->get();
            foreach ($comments as $comment) {
                CommentDetail::where('comment_id', $comment->id)->delete();
            }
            Comment::where('topic_id', $topic->id)->delete();
            TopicKeyword::where('topic_id', $topic->id)->delete();
            $topic->delete();
        } catch (\Exception $ex) {
            response()->json(['error' => $ex->getMessage()], 403);
        }

        return response()->json(null, 204);
    }

    public function actualDestroyMultiple(Request $request) {
        $validator = Validator::make($request->all(), ['ids' => 'required']);
        if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
        $listIds = $request->get('ids', []);
        $topics = Topic::isDeleted()->whereIn('id', $listIds)->get();
        if ($topics->count() <= 0) response()->json(['error' => 'Topic is not valid.'], 403);
        try {
            foreach ($topics as $topic) {
                $comments = Comment::select('id')->where('topic_id', $topic->id)->get();
                foreach ($comments as $comment) {
                    CommentDetail::where('comment_id', $comment->id)->delete();
                }
                Comment::where('topic_id', $topic->id)->delete();
                TopicKeyword::where('topic_id', $topic->id)->delete();
                $topic->delete();
            }
        } catch (\Exception $ex) {
            response()->json(['error' => $ex->getMessage()], 403);
        }

        return response()->json(null, 204);
    }

    public function destroy($id = 0)
    {
        $topic = Topic::notDeleted()->where('id', $id)->first();
        if (!isset($topic)) response()->json(['error' => 'Ehhh! Can not delete this topic'], 403);

        try {
            $topic->update(['is_deleted' => true]);
        } catch (\Exception $ex) {
            response()->json(['error' => $ex->getMessage()], 403);
        }

        return response()->json(null, 204);
    }

    public function multipleDestroy(Request $request)
    {
        $validator = Validator::make($request->all(), ['ids' => 'required']);
        if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
        $listIds = $request->get('ids', []);
        $topics = Topic::notDeleted()->whereIn('id', $listIds)->get();
        if ($topics->count() <= 0) response()->json(['error' => 'Topic is not valid.'], 403);
        try {
            Topic::notDeleted()->whereIn('id', $listIds)->update(['is_deleted' => true]);
        } catch (\Exception $ex) {
            response()->json(['error' => $ex->getMessage()], 403);
        }

        return response()->json(null, 204);
    }

    public function multiplePublish(Request $request)
    {
        $validator = Validator::make($request->all(), ['ids' => 'required']);
        if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
        $listIds = $request->get('ids', []);
        $topics = Topic::notDeleted()->whereIn('id', $listIds)->get();
        if ($topics->count() <= 0) response()->json(['error' => 'Topic is not valid.'], 403);
        try {
            Topic::notDeleted()->whereIn('id', $listIds)->update(['is_activated' => true]);
        } catch (\Exception $ex) {
            response()->json(['error' => $ex->getMessage()], 403);
        }

        return response()->json(null, 204);
    }

    public function multipleUnPublish(Request $request)
    {
        $validator = Validator::make($request->all(), ['ids' => 'required']);
        if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
        $listIds = $request->get('ids', []);
        $topics = Topic::notDeleted()->whereIn('id', $listIds)->get();
        if ($topics->count() <= 0) response()->json(['error' => 'Topic is not valid.'], 403);
        try {
            Topic::notDeleted()->whereIn('id', $listIds)->update(['is_activated' => false]);
        } catch (\Exception $ex) {
            response()->json(['error' => $ex->getMessage()], 403);
        }

        return response()->json(null, 204);
    }
}
