<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\Website\PageContent;
use App\Models\Website\Post;
use App\Models\Website\PublicContentCategory;
use App\Models\Website\TblPhotoGallery;
use App\Models\Website\TblVideoGallery;
use Illuminate\Http\Request;
use Validator;

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

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index(Request $request)
    {
        $Posts = Post::select(['id', 'title', 'status']);
        $sort_by    = $request->get('sortby') ?? 10;
        $sort_type  = $request->get('sorttype');
        $query      = $request->get('query');
        if (!empty($query) && !empty($sort_by) && $query != " ") {
            $Posts->where('title', 'like', '%' . $query . '%');
        }
        $Post = $Posts->orderBy('id', 'desc')->paginate($sort_by);
        if ($request->ajax()) {
            return view('website-setting.post.table', compact('Post'));
        } else {
            return view('website-setting.post.index', compact('Post'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('website-setting.post.create');
    }

    /**
     * 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',
                ''
            ]);
            if ($validator->fails()) {
                return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
            } else {

                if ($request->hasFile('image')) {
                    $url        = \Str::slug($request->title);
                    $path       = "upload/" . $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 = Post::create([
                    'title' => $request->title,
                    'company_id' => auth()->user()->company_id,
                    'slug' => \Str::slug($request->title),
                    'description' => $request->description,
                    'image' => $image,
                    'body' => $request->body,
                    'meta_title' => $request->meta_title,
                    'meta_key' => $request->meta_key,
                    'meta_url' => $request->meta_url,
                    'meta_description' => $request->meta_description,
                    'meta_key' => $request->meta_key,
                    'meta_key' => $request->meta_key,
                    'meta_key' => $request->meta_key,
                    'video_url' => $request->video_url,
                ]);
                //
                $Redirect = route('pages-setting.index');
                return response()->json([
                    'success' => true,
                    'message' => ['New Page successfully created'],
                    'data' => [
                        'redirect' => $Redirect,
                        'reload' => true,
                    ]
                ]);
            }
        }
    }

    public function edit($id, Request $request)
    {
        $Post = Post::where(['id' => $id])->first();
        //
        return view('website-setting.post.edit')->with(['Post' => $Post]);
    }


    public function update($id, Request $request)
    {
        $validator =  Validator::make($request->all(), [
            'title' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
        } else {
            $Post = Post::find($id);

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

                if ($response['status'] == true) {
                    $image = $response['file_name'];
                } else {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
            } else {
                $image = $Post->image;
            }
            $data = array(
                'title' => $request->title,
                'slug' => \Str::slug($request->title),
                'company_id' => auth()->user()->company_id,
                'description' => $request->description,
                'image' => $image,
                'body' => $request->body,
                'meta_title' => $request->meta_title,
                'meta_key' => $request->meta_key,
                'meta_url' => $request->meta_url,
                'meta_description' => $request->meta_description,
                'meta_key' => $request->meta_key,
                'meta_key' => $request->meta_key,
                'meta_key' => $request->meta_key,
                'video_url' => $request->video_url,
            );
            $Post->update($data);
            //
            $Redirect = '';
            return response()->json([
                'success' => true,
                'message' => ['Page successfully Update'],
                'data' => [
                    'redirect' => route('pages-setting.index'),
                    'reload' => false,
                ]
            ]);
        }
    }


    public function changestatus(Request $request)
    {
        if ($request->ajax()) {
            $data = array('status' => $request->status);
            $Update = Post::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Status successfully change'],
                    'data' => [
                        'redirect' => route('pages-setting.index'),
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function destroy(Request $request)
    {
        $Delete = Post::where(['id' => $request->id])->delete();
        $Redirect = route('pages-setting.index');
        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function show($id,Request $request)
    {
        $page = Post::find($id);
        $pageContent = PageContent::where('page_id',$id)->get();
        return view('website-setting.post.show',compact('page','pageContent','id'));
    }

    public function pageContent($id,Request $request)
    {
        $pageContent = PageContent::with(['getContentCategory','getGallery','getVideoGallery'])->where('page_id',$id)->get();
        return view('website-setting.post.page-content.table',compact('pageContent','id'));
    }

    public function pageContentCreate($id,Request $request)
    {
        return view('website-setting.post.page-content.create',compact('id'));
    }
    public function pageContentGet(Request $request)
    {
        echo '<option value=" ">Select Content Title</option>';
        if($request->content_type=='Content Category')
        {
            $category = PublicContentCategory::get(['id','name']);
            foreach($category as $row)
            {
                echo '<option value="'.$row->id.'">'.$row->name.'</option>';
            }
        }
        elseif($request->content_type=='Photo Gallery')
        {
            $category = TblPhotoGallery::get(['id','title']);
            foreach($category as $row)
            {
                echo '<option value="'.$row->id.'">'.$row->title.'</option>';
            }
        }
        elseif($request->content_type=='Video Gallery')
        {
            $category = TblVideoGallery::get(['id','title']);
            foreach($category as $row)
            {
                echo '<option value="'.$row->id.'">'.$row->title.'</option>';
            }
        }
    }


    public function pageContentStore(Request $request)
    {
        if ($request->isMethod('post')) {
            $validator =  Validator::make($request->all(), [
                'content_id'    => 'required',
                'content_type'  => 'required',
            ]);
            if ($validator->fails()) {
                return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
            } else {

                $Category = PageContent::create([
                    'page_id'       => $request->id,
                    'content_type'  => $request->content_type,
                    'priority'      => $request->priority,
                    'content_id'    => $request->content_id,
                ]);
                //
                $Redirect = route('pages-setting.index');
                return response()->json([
                    'success' => true,
                    'message' => ['New Page successfully created'],
                    'data' => [
                        'redirect' => $Redirect,
                        'reload' => true,
                    ]
                ]);
            }
        }
    }

    public function pageContentEdit($id,Request $request)
    {
        $pageContent = PageContent::find($id);

        if($pageContent->content_type=='Content Category')
        {
            $category = PublicContentCategory::get(['id','name as title']);
        }
        elseif($pageContent->content_type=='Photo Gallery')
        {
            $category = TblPhotoGallery::get(['id','title']);
        }
        elseif($pageContent->content_type=='Video Gallery')
        {
            $category = TblVideoGallery::get(['id','title']);
        }

        return view('website-setting.post.page-content.edit',compact('id','pageContent','category'));
    }

    public function pageContentUpdate($id,Request $request)
    {
        if ($request->isMethod('post')) {
            $validator =  Validator::make($request->all(), [
                'content_id'    => 'required',
                'content_type'  => 'required',
            ]);
            if ($validator->fails()) {
                return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
            } else {
                $pageContent = PageContent::find($id);
                $pageContent->update([
                    'content_type'  => $request->content_type,
                    'priority'      => $request->priority,
                    'content_id'    => $request->content_id,
                ]);
                //
                $Redirect = route('pages-setting.index');
                return response()->json([
                    'success' => true,
                    'message' => ['New Page successfully created'],
                    'data' => [
                        'redirect' => $Redirect,
                        'reload' => true,
                    ]
                ]);
            }
        }
    }

    public function pageContentChangeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data = array('status' => $request->status);
            $Update = PageContent::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Status successfully change'],
                    'data' => [
                        'redirect' => route('pages-setting.index'),
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function pageContentDelete($id,Request $request)
    {
        $Delete = PageContent::where(['id' => $id])->delete();
        $Redirect = route('pages-setting.index');
        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }
}
