<?php

namespace App\Http\Controllers;

use App\Models\Blog;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;

class BlogController extends Controller
{

    public function addBlog(Request $request){
        if(Auth::check()){
            try {
                $blog = new Blog();
                $blog->published_by = Auth::user()->id;
                $blog->language = $request->input('language');
                $blog->title = $request->input('title');
                $blog->body = $request->input('body');
                $blog->published = "1";
                $blog->created_at = now();
                $blog->updated_at = now();
                $blog->save();
                return ['messageStatus' => 'success', 'errorMessage' => ''];
            } catch (\Illuminate\Database\QueryException $e) {
                return ['messageStatus' => 'danger', 'errorMessage' => __("controller_messages.BlogController.error_occurred", ["error" => $e->getMessage()])];
            }
        }
        abort(404);
    }

    public function editBlog(Request $request){
        if(Auth::check()){
            try {
                $blog = Blog::find($request->input('id'));
                $blog->title = $request->input('title');
                $blog->body = $request->input('body');
                $blog->language = $request->input('language');
                $blog->published = $request->input('published');
                $blog->published_by = Auth::user()->id;
                $blog->save();
                return ['messageStatus' => 'success', 'errorMessage' => ''];
            } catch (\Illuminate\Database\QueryException $e) {
                return ['messageStatus' => 'failure', 'errorMessage' => __("controller_messages.BlogController.error_occurred", ["error" => $e->getMessage()])];
            }
        }
        abort(404);
    }

    public function deleteBlog(Request $request){
        if(Auth::check()){
            try {
                $blog = Blog::find($request->input('id'));
                if ($blog) {
                    $blog->delete();
                }
                return ['messageStatus' => 'success', 'errorMessage' => ''];
            } catch(\Exception $e){
                return ['messageStatus' => 'failure', 'errorMessage' => __("controller_messages.BlogController.error_occurred", ["error" => $e->getMessage()])];
            }
        }
        abort(404);
    }


    public static function blogPaginated(){
        return Blog::where('language', App::getLocale())->where('published', 1)->orderBy('id', 'desc')->paginate(5);
    }

    public static function blogPaginatedEdit(){
        return Blog::orderBy('id', 'desc')->paginate(5);
    }
}
