<?php

namespace App\Http\Controllers\Enquiries;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\EnquiryStatus;

class EnquiryStatusController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:enquiry-status-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = EnquiryStatus::select([
            'id',
            'code',
            'enquiry_status_name',
            'enquiry_status_description',
            'enquiry_status_priority',
            'bg_color',
            'color',
            'default',
            'status',
            'hide',
        ]);

        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_status_name', 'like', '%'.$search_query.'%')
                            ->orWhere('enquiry_status_priority', 'like', '%'.$search_query.'%')
                            ->orWhere('color', 'like', '%'.$search_query.'%');
                    })
                    ->paginate($sort_by);

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = EnquiryStatus::max('enquiry_status_priority');
        $priority = $priority != '' ? $priority : 0;
        return view('enquiry-statuses.create',compact('priority'));
    }

    /**
     * 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(), [
            'enquiry_status_name'        => 'required|unique:enquiry_statuses',
            'enquiry_status_priority'    => 'required',
            'bg_color'                   => 'required',
            'color'                      => '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'
        ]);

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

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

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

        $status = EnquiryStatus::create($data);

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

        return redirect()->route('enquiry-statuses.index')
            ->with('success','Enquiry status 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)
    {
        $status = EnquiryStatus::find($id);

        return view('enquiry-statuses.edit',compact('status'));
    }

    /**
     * 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(), [
            'enquiry_status_name'        => 'required|unique:enquiry_statuses,enquiry_status_name,'.$id,
            'enquiry_status_priority'    => 'required',
            'bg_color'                   => 'required',
            'color'                      => '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'
        ]);

        $status = EnquiryStatus::find($id);

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

        $status->update($data);

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

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

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

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

        $data->delete();

        $Redirect = 'enquiry-statuses';

        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 = EnquiryStatus::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Enquiry Status 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  = EnquiryStatus::where(['default' => $request->status])->count();

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

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

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

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

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