<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\Website\PublicContentCategory;
use Illuminate\Http\Request;
use Validator;

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

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


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


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $validator = \Validator::make($request->all(), ['name' => 'required|unique:public_content_category']);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except(['_token']);

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

            if ($response['status'] == true) {
                $files = $response['file_name'];
            } else {
                return response()->json([
                    'success' => false,
                    'message' => [$response['message']],
                    'data'    => []
                ]);
            }
        } else {
            $files = '';
        }
        $data['image'] = $files;
        $data['company_id'] = auth()->user()->company_id;
        $data = PublicContentCategory::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'content category created successfully',
                'data' => $data
            ]);
        }

        return redirect()->route('content-category.index')
            ->with('success', 'content category created successfully');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id, Request $request)
    {
        $Category = PublicContentCategory::find($id);
        return view('website-setting.category.edit')->with(['Category' => $Category]);
    }



    public function show($id, Request $request)
    {
        $category = PublicContentCategory::find($id);
        return view('website-setting.category.show',compact('id','category'));
    }

    /**
     * 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(), ['name' => 'required']);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except(['_token', '_method']);
        $categorys = PublicContentCategory::find($id);

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

            if ($response['status'] == true) {
                $files = $response['file_name'];
            } else {
                return response()->json([
                    'success' => false,
                    'message' => $response['message'],
                    'data'    => []
                ]);
            }
        } else {
            $files = $categorys->image;
        }
        $data['image'] = $files;
        $data['company_id'] = auth()->user()->company_id;
        $data = PublicContentCategory::whereId($id)->update($data);
        $data = PublicContentCategory::find($id);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Category updated successfully',
                'data' => $data
            ]);
        }
        return redirect()->route('content-category.index')
            ->with('success', 'Category updated successfully');
    }

    /**
     * change service 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 = PublicContentCategory::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Category successfully change'],
                    'data' => [
                        'redirect' => '',
                        '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 = PublicContentCategory::where(['id' => $request->id])->delete();
        $Redirect = '/content-category';
        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }
}
