<?php

namespace App\Http\Controllers\Enquiries;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\EnquiryCategory;

class EnquiryCategoriesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:enquiry-category-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (!$this->modulePermissionCheck('ENQUIRY')) {
            abort(404);
        }

        $data = EnquiryCategory::select([
                    'enquiry_categories.id',
                    'enquiry_categories.category_name',
                    'enquiry_categories.default',
                    'enquiry_categories.status',
                    'enquiry_categories.priority',
                    \DB::raw('COUNT(enquiry_category_extra_fields.id) as field_count'),
                ])
                ->leftJoin('enquiry_category_extra_fields', 'enquiry_category_extra_fields.enquiry_category_id', 'enquiry_categories.id');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query)
                {
                    return $query->where('enquiry_categories.category_name', 'like', '%'.$search_query.'%')
                        ->orWhere('companies.name', 'like', '%'.$search_query.'%');
                })
                ->groupBy('enquiry_categories.id')
                ->paginate($sort_by);

            return view('enquiry-categories.table', compact('data'));
        }
        else
        {
            $data = $data->groupBy('enquiry_categories.id')
                ->paginate(10);

            return view('enquiry-categories.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = EnquiryCategory::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('enquiry-categories.create', compact('priority'));
        // return view('enquiry-categories.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(), [
            'category_name' => 'required|unique:enquiry_categories',
        ]);

        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'
        ]);

        $data['company_id'] = \Auth::user()->company_id > 0 ? \Auth::user()->company_id : 1;

        $default_check = EnquiryCategory::where(['default' => 1,'status' => 1])->first();

        if (!$default_check) {
            $data['default'] = 1;
        }

        $category = EnquiryCategory::create($data);

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

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $category = EnquiryCategory::find($id);

        return view('enquiry-categories.edit',compact('category'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'category_name' => 'required|unique:enquiry_categories,category_name,'.$id
        ]);

        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'
        ]);

        $category = EnquiryCategory::find($id);

        if (!$category) {
            return redirect()->route('enquiry-categories.index')
                ->with('error','Enquiry category not found!');
        }

        $category->update($data);

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

        return redirect()->route('enquiry-categories.index')
            ->with('success','Enquiry category updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $about = EnquiryCategory::find($request->id);

        if ($about->default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $about->delete();

        $Redirect = 'enquiry-categories';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }

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

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Enquiry Category status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }

    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('default' => $request->status );
            $count  = EnquiryCategory::where(['default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Enquiry Category!'],
                    'data'    => []
                ]);
            }

            $Update = EnquiryCategory::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Enquiry Category default status successfully changed.'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
}
