<?php

namespace App\Http\Controllers;

use App\Models\Message;
use App\Models\MessageComment;
use App\Http\Requests\StoremessageRequest;
use App\Http\Requests\StoreMessageCommentRequest;
use App\Http\Requests\UpdatemessageRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class MessageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $message = Message::all();
        return $message;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoremessageRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $preview = "";
        if ($request->preview == "preview") {
            $preview = str_replace("\n", "", $request->content);
            $preview = str_replace(" ", "", $preview);
            $preview = strip_tags($preview);
            $preview = mb_substr($preview, 0, 55) . "...";
        }
        $path = $request->file('thumbnail')->store('public');
        $url = Storage::url($path);
        $message_comment = Message::create([
            'title' => $request->title,
            'content' => $request->content,
            'author_id' => $request->User()->id,
            'preview' => $preview,
            'tag' => $request->tag,
            'thumbnail' => $url,
            'created_at' => now(),
        ]);
        return $message_comment;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreMessageCommentRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function storeComment(StoreMessageCommentRequest $request)
    {
        //
        $message_comment = MessageComment::Create([
            'content' => $request->content,
            'author_id' => $request->User()->id,
            'message_id' => $request->message_id,
        ]);
        return $message_comment;
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\message  $message
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request, message $message)
    {
        //
        $message = Message::where('id', '=', $request->id)->get()[0];
        $comment = MessageComment::where('message_id', '=', $request->id)->get();
        $response = [
            'blog' => $message,
            'comments' => $comment,
        ];

        return response($response, 201);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\message  $message
     * @return \Illuminate\Http\Response
     */
    public function edit(message $message)
    {
        //

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdatemessageRequest  $request
     * @param  \App\Models\message  $message
     * @return \Illuminate\Http\Response
     */
    public function update(UpdatemessageRequest $request, message $message)
    {
        //
        $preview = "";
        if ($request->preview == "preview") {
            $preview = str_replace("\n", "", $request->content);
            $preview = str_replace(" ", "", $preview);
            $preview = strip_tags($preview);
            $preview = mb_substr($preview, 0, 55) . "...";
        }
        if (is_string($request->thumbnail)) {
            $url = $request->thumbnail;
        } else {
            $thumbnail = Message::where('id', $request->id)->get()[0]->thumbnail;
            $path = $request->file('thumbnail')->store('public');
            $url = Storage::url($path);
            File::delete(ltrim($thumbnail,"/"));
        }

        $message = Message::where('id', $request->id)
            ->where('author_id', $request->User()->id)
            ->update([
                'title' => $request->title,
                'content' => $request->content,
                'preview' => $preview,
                'tag' => $request->tag,
                'thumbnail' => $url,
                'updated_at' => now(),
            ]);
        if ($message == 0) {
            abort(403, '你沒有編輯此貼文的權限!');
        }
        return $message;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\message  $message
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, Message $message)
    {
        $thumbnail = Message::where('id', $request->id)->get()[0]->thumbnail;
        if ($request->user()->tokenCan('Admin')) {
            $message = Message::where('id', $request->id)->delete();
        } else if ($request->user()->tokenCan('User')) {
            $message = Message::where('id', $request->id)
                ->where('author_id', $request->User()->id)->delete();
        } else {
            abort(403, '你沒有刪除此貼文的權限!');
        }
        
        if ($message > 0 && !str_contains($thumbnail, 'http')) {
            File::delete(ltrim($thumbnail,"/"));
        }

        return $message;
    }

    public function count()
    {
        $count = DB::select('SELECT [messages].[id],Count([message_comments].[id]) AS count FROM [laravel].[dbo].[messages]
        LEFT JOIN [message_comments] ON [message_comments].[message_id] = [messages].[id]
        GROUP BY [messages].[id]');
        return $count;
    }
    public function recent()
    {
        //
        $message = Message::all()->sortByDesc('created_at')->take(4);
        $categories = [
            ['category' => '台灣小吃', 'icon' => 'SlackIcon'],
            ['category' => '美食', 'icon' => 'CoffeeIcon'],
            ['category' => '熱炒店', 'icon' => 'SunIcon'],
            ['category' => '吃到飽', 'icon' => 'ThumbsUpIcon'],
        ];
        $response = [
            'recentPosts' => $message,
            'categories' => $categories,
        ];
        return $response;
    }
}
