<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\Website\Blog;
use Illuminate\Http\Request;
use App\Models\BlogCategory;
use App\Models\GlobalTag;
use Illuminate\Support\Facades\Validator;

class BlogsController extends Controller
{
    function __construct()
    {
        // $this->middleware('permission:website-blogs-list|website-blogs-create|website-blogs-edit|website-blogs-delete', ['only' => ['index','store','list']]);
    }

    public function index(Request $request)
    {
        $Blogs =Blog::select([
            'blogs.id',
            'blogs.title',
            'blogs.image',
            'blogs.status',
            'blog_categories.name as category_name'
        ])
        ->leftJoin('blog_categories','blog_categories.id' ,'blogs.category_id');
        ;

            $sort_by        = $request->get('sortby') ?? 10;
            $sort_type      = $request->get('sorttype');
            $query          = $request->get('query');
            if(!empty($query) && !empty($sort_by) && $query!=" ")
            {
              $Blogs->where('blogs.title', 'like', '%'.$query.'%');
            }
            $Blog =$Blogs->orderBy('blogs.id','desc')->paginate($sort_by);
        if ($request->ajax()) {
          return view('website-setting.Blogs.table', compact('Blog'));
        }
        else
        {
            return view('website-setting.Blogs.index',compact('Blog'));
        }

    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories = BlogCategory::where('status',1)->get();
        $tags = GlobalTag::where('status',1)->get();

        return view('website-setting.Blogs.create', compact('categories', 'tags'));
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if($request->isMethod('post'))
        {
           // return $request;
            $validator =  Validator::make($request->all(),[
                'title'       => 'required',
                'image'       => 'required',
                'category_id' => 'required',
                'description' => 'required'
            ]);
            if($validator->fails())
            {
                return response()->json(['success'=>false,'message'=>$validator->errors()->all()]);
            }
            else{

                if ($request->hasFile('image')) {
                    $url        =\Str::slug($request->title);
                    $path       ="upload/Blogs/".$url.'/'.date('Y').'/'.date('m');
                    $response = uploadImage($path,$request->image);

                    if ($response['status'] == true)
                    {
                        $image = $response['file_name'];
                    }
                    else
                    {
                        return response()->json([
                            'success' => false,
                            'message' => $response['message'],
                            'data'    => []
                        ]);
                    }
                }
                else
                {
                    $image='';
                }

                $Category =Blog::create([
                                'title'       => $request->title,
                                'description' => $request->description,
                                'slug'        => $url,
                                'company_id'  => auth()->user()->company_id,
                                'category_id' => $request->category_id,
                                'tags'        => $request->tags?implode(', ', $request->tags):'',
                                'image'       => $image,
                            ]);
                //
                $Redirect = '/blogs/';
                return response()->json([
                    'success'=>true,
                    'message'=>['Blog successfully created'],
                    'data'=>$Category
                ]);
            }
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id,Request $request)
    {
        $Blog =Blog::where(['id'=>$id])->first();
        $categories = BlogCategory::where('status',1)->get();
        $tags = GlobalTag::where('status',1)->get();
        //
        return view('website-setting.Blogs.edit')->with([
            'Blog'=>$Blog,
            'tags' => $tags,
            'categories' => $categories
        ]);
    }


     /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id,Request $request)
    {

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update($id,Request $request)
    {
        $validator =  Validator::make($request->all(),[
            'title'            => 'required',
            'category_id'      =>  'required'
        ]);
        if($validator->fails())
        {
            return response()->json(['success'=>false,'message'=>$validator->errors()->all()]);
        }
        else{
            $SocialBlog=Blog::find($id);
            $url        =\Str::slug($request->title);
            if ($request->hasFile('image')) {
                $path       ="upload/Blogs/".$url.'/'.date('Y').'/'.date('m');
                $response = uploadImage($path,$request->image);

                if ($response['status'] == true)
                {
                    $image = $response['file_name'];
                }
                else
                {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
            }
            else
            {
                $image=$SocialBlog->image;
            }

            $data = array(
                            'title'       => $request->title,
                            'description' => $request->description,
                            'slug'        => $url,
                            'image'       => $image,
                            'category_id' => $request->category_id,
                            'tags'        => $request->tags?implode(', ', $request->tags):'',
                            'company_id'  => auth()->user()->company_id,
                    );
            $SocialBlog->update($data);
            $data=Blog::find($id);
            //
            $Redirect = '';
            return response()->json([
                'success'=>true,
                'message'=>['Blog successfully Update'],
                'data'=>$data
            ]);
        }
    }




    /**
     * change Blog status.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function changestatus(Request $request)
    {
        if ($request->ajax())
        {
            $data = array('status' => $request->status );
            $Update =Blog::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Status successfully change'],
                    'data'=>[
                        'redirect'=>'/Blogs/',
                        'reload'=>true,
                    ]
                ]);
            }
            else{
                return response()->json([
                    'success'=>false,
                    'message'=>['Error for change status'],
                    'data'=>[
                        'redirect'=>'',
                    ]
                ]);
            }
        }
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $Delete =Blog::where(['id'=>$request->id])->delete();
        $Redirect = '/Blogs';
        return response()->json([
            'success'=>true,
            'message'=>['Deleted successfully'],
            'data'=>[
            'redirect'=>$Redirect,
            ]
        ]);
    }
}
