<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\Draft;
use App\Models\Category;
use App\Models\LeadPost;
use App\Models\SubCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;

class PostController extends Controller
{

    public function trashpost_index(){
        $trashposts = DB::table('trashposts')->orderBy('created_at', 'desc')->paginate(20);
        return view('back.trashpost.index', compact('trashposts'));
    }
    public function trashpost_view($id){
        $trashpost = DB::table('trashposts')->where('id',$id)->first();
        return view('back.trashpost.view', compact('trashpost'));
    }
    
    public  function search(Request $request)
    {
        $query = $request->value;
        $post = Post::where('id', $query)->first();
        if(!empty($post)){
            $posts = Post::where('id', $query)->paginate(20);
        }else{
            $posts = Post::where('headline', 'LIKE', '%' . $query . '%')
                ->orWhere('content', 'LIKE', '%' . $query . '%')
                ->orWhere('id', 'LIKE' . $query )
                ->paginate(20);
        }
        $posts->appends($request->all());
        return view('back.blog.post.post_search', compact('posts', 'query'));
    }
    public function index()
    {
        $posts = Post::orderby('id','desc')->Paginate(20);
        return view('back.blog.post.index', compact('posts'));
    }



    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {   
        $categories = Category::orderBy('position','asc')->get();
        return view('back.blog.post.create', compact('categories'));
    }
    

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {   
        $request->validate([
            'headline' => 'required',
            'content' => 'required',
            'image' => 'required',
            'category_id' => 'required',
        ]);
        $date_time = date('YmdHis');

        if($request->btn_action == 'draft'){
            $post = new Draft;
            $post->user_id = Auth::user()->id;
            $post->headline = $request->headline;
            $post->intro = $request->intro;
            $post->slug = make_slug($request->headline);
            $post->content = $request->content;
            // if($request->hasfile('image')){
            //     $file = $request->file('image');
            //     $fileName = $file->getClientOriginalName();
            //     $fileExt = $file->getClientOriginalExtension();
            //     $fileOrgName = basename($fileName,".".$fileExt);
            //     $fileOrgName2 = make_slug($fileOrgName);
            //     $fileName = $fileOrgName2.'-'.$date_time.'.'.$fileExt;
            //     $f_image = '/blog/'.$fileName;
            //     $file->move(public_path('/blog/'), $fileName);
            //     $post->image = $f_image;
            // }

            if($request->hasfile('image')){
                $file = $request->file('image');
                $fileName = $file->getClientOriginalName();
                $fileExt = $file->getClientOriginalExtension();
                $fileName = $date_time.'.'.$fileExt;
                $f_image = '/blog/'.$fileName;
                $image_resize = Image::make($file->getRealPath());       
                $image_resize->resize(700, 450);
                $image_resize->save(public_path('/blog/' .$fileName));
                $post->image = $f_image;
            }
            $post->status = $request->status;
            $post->save();
            if($request->category_id) {
                $post->category()->attach($request->category_id);
            }
         

            Session::flash('success', 'Successfully drafted');
            return Redirect::route('post.index');
        }

        if($request->btn_action == 'create'){
            $post = new Post;
            $post->user_id = Auth::user()->id;
            $post->sticky = $request->sticky ? 1 : 0;
            $post->headline = $request->headline;
            $post->intro = $request->intro;
            $post->slug = make_slug($request->headline);
            $post->content = $request->content;
            
            if($request->hasfile('image')){
                $file = $request->file('image');
                $fileName = $file->getClientOriginalName();
                $fileExt = $file->getClientOriginalExtension();
                $fileName = $date_time.'.'.$fileExt;
                $f_image = '/blog/'.$fileName;
                $image_resize = Image::make($file->getRealPath());       
                $image_resize->resize(700, 450);
                $image_resize->save(public_path('/blog/' .$fileName));
                $post->image = $f_image;
            }
            $post->status = $request->status;
            $post->save();
            if ($request->category_id) {
                $post->Category()->attach($request->category_id);
            }
            

            $lead_post_position = LeadPost::where('position', $request->sticky_position)->first();
            $lead_post_item = LeadPost::where('post_id', $post->id)->first();
            if ($request->sticky) {
                if ($lead_post_item) {
                    $lead_post_item->delete();
                }
                if ($lead_post_position) {
                    $leadposts = LeadPost::orderBy('position', 'asc')->get();
                    foreach ($leadposts as $leadpost) {
                        if ($leadpost->position == $lead_post_position->position || $leadpost->position > $lead_post_position->position) {
                            $leadpost->position = $leadpost->position + 1;
                            $leadpost->save();
                        }
                    }
                }
            } else {
                if ($lead_post_item) {
                    $lead_post_item->delete();
                }
            }
            if (!empty($request->sticky_position)) {
                $lead_post = new LeadPost();
                $lead_post->position = $request->sticky_position;
                $lead_post->post_id = $post->id;
                $lead_post->save();
            }

            Session::flash('success', 'Successfully Created');
            return Redirect::route('post.index');
        }

        
    }

    

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function edit($id){
        $post = Post::find($id);
        $categories = Category::orderBy('position','asc')->get();
        return view('back.blog.post.edit', compact('post', 'categories'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'headline' => 'required',
            'content' => 'required',
            'category_id' => 'required'
        ]);
        $date_time = date('YmdHis');
        $post = Post::find($id);

        $lead_post_position = LeadPost::where('position', $request->sticky_position)->first();
        $lead_post_item = LeadPost::where('post_id', $post->id)->first();
        if ($request->sticky) {
            if ($lead_post_item) {
                $lead_post_item->delete();
            }
            if ($lead_post_position) {
                $leadposts = LeadPost::orderBy('position', 'asc')->get();
                foreach ($leadposts as $leadpost) {
                    if ($leadpost->position == $lead_post_position->position || $leadpost->position > $lead_post_position->position) {
                        $leadpost->position = $leadpost->position + 1;
                        $leadpost->save();
                    }
                }
            }
        } else {
            if ($lead_post_item) {
                $lead_post_item->delete();
            }
        }
        if (!empty($request->sticky_position)) {
            $lead_post = new LeadPost();
            $lead_post->position = $request->sticky_position;
            $lead_post->post_id = $post->id;
            $lead_post->save();
        }
        $post->sticky = $request->sticky ? 1 : 0;
        $post->user_id = Auth::user()->id;
        $post->headline = $request->headline;
        $post->slug = make_slug($request->headline);
        $post->content = $request->content;
        
        if($request->hasfile('image')){
            $file = $request->file('image');
            $fileName = $file->getClientOriginalName();
            $fileExt = $file->getClientOriginalExtension();
            $fileName = $date_time.'.'.$fileExt;
            $f_image = '/blog/'.$fileName;
            $image_resize = Image::make($file->getRealPath());       
            $image_resize->resize(700, 450);
            $image_resize->save(public_path('/blog/' .$fileName));
            $post->image = $f_image;
        }
        $post->status = $request->status;
        $post->Category()->detach();
       
        $post->save();
        if($request->category_id) {
            $post->Category()->sync($request->category_id);
        }
    
        
        Session::flash('success', 'Successfully Updated');
        return Redirect::to(route('post.index'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $post = Post::find($id);
        DB::table('trashposts')->insert(
            ['user_id' => $post->user_id,'deleted_by' => Auth::user()->id,'headline' => $post->headline,'slug' => $post->slug,'intro' => $post->intro,'content' => $post->content,'image' => $post->image,'status' => $post->status,'view_count' => $post->view_count,'created_at' => $post->created_at,'updated_at' => $post->updated_at]
        );
        $post->category()->detach();
        $post->delete();
        Session::flash('success', 'Successfully Deleted');
        return Redirect::back();
    }

    public function post_filter(Request $request){
        $category_id = $request->category_id;

        if($category_id != null){
            $posts = Category::find($category_id)->posts()->where('post_status', 1)->orderBy('id', 'desc')->paginate(20);
            $posts->appends($request->all());
        }else if($request->sort_by == 'asc'){
            $posts = Post::where('post_status', 1)->orderBy('id', 'asc')->paginate(20);
            $posts->appends($request->all());
        }
        else if($request->sort_by == 'desc'){
            $posts = Post::where('post_status', 1)->orderBy('id', 'desc')->paginate(20);
            $posts->appends($request->all());
        }
        else{
            $posts = Post::orderby('id', 'desc')->paginate(20);
            $posts->appends($request->all());
        }
        return view('back.post.post_filter', compact('posts'));
    }

    public function changePublicationStatus(Request $request){
        $post = Post::find($request->id);
        $post->status = $request->status;
        $post->save();
        return response()->json(['success'=>'Status successfully changed.']);
    }
    public function categorySubCategoyAJAX($category_id){
        $sub_category  = SubCategory::where('category_id',$category_id)->get();
        return Response::json($sub_category);
    }
}
