<?php

namespace App\Http\Controllers\Main;

use App\Article;
use App\Http\Controllers\Controller;
use App\Like;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ArticleController extends Controller
{
    public function store(Request $request)
    {

        $validate = Validator::make($request->all(), [
            "body" => ["required", "string", "max:1000"]
        ]);

        if ($validate->fails()) {
            return response()->json($validate->messages())->setStatusCode(400);
        }

        Article::create([
            "user_id" => Auth::id(),
            "body" => $request->body
        ]);

        return response()->json([
            "user" => [
                "id" => Auth::id(),
                "name" => Auth::user()->name,
                "surname" => Auth::user()->surname,
                "avatar_url" => Auth::user()->avatar_url
            ],
            "created_at" => date('d.m.Y')
        ]);

    }

    public function destroy(Request $request)
    {
        $article = Article::find($request->id);

        if (Auth::id() != $article->user_id) {
            return abort(403);
        }

        $article->delete();

        return redirect()->back();
    }

    public function like(Request $request)
    {
        $article = Article::find($request->id);
        if (!$article) return response()->json(["status" => false], 404);

        $like = Like::where('user_id', Auth::id())->where('post_id', $request->id)->where('type', 'article')->first();

        if ($like) {
            $like->status = ($like->status == 0) ? 1 : 0;
            $like->save();
            return response()->json(["status" => true, "action" => ($like->status == 1) ? "on" : "off"]);
        }

        Like::create([
            "user_id" => Auth::id(),
            "post_id" => $request->id,
            "type" => "article",
            "status" => 1,
        ]);

        return response()->json(["status" => true, "action" => "on"]);
    }
}
