<?php

namespace App\Http\Controllers\Enquiries;

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

class EnquirySourcesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:enquiry-sources-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = EnquirySource::select([
                    'enquiry_sources.id',
                    'enquiry_sources.enquiry_source_code',
                    'enquiry_sources.enquiry_source_name',
                    'enquiry_sources.enquiry_source_priority',
                    'enquiry_sources.default',
                    'enquiry_sources.status',
                ]);

        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_sources.enquiry_source_name', 'like', '%'.$search_query.'%')
                                ->orWhere('enquiry_sources.enquiry_source_code', 'like', '%'.$search_query.'%');
                        })
                        ->paginate($sort_by);

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = EnquirySource::max('enquiry_source_priority');
        $priority = $priority != '' ? $priority : 0;
        return view('enquiry-sources.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_source_name'        => 'required|unique:enquiry_sources',
            'enquiry_source_code'        => 'required',
            'enquiry_source_priority'    => '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['enquiry_source_code'] = strtoupper($data['enquiry_source_code']);
        $data['company_id']          = \Auth::user()->company_id;

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

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

        $source = EnquirySource::create($data);

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

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

        return view('enquiry-sources.edit',compact('source'));
    }

    /**
     * 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_source_name'        => 'required|unique:enquiry_sources,enquiry_source_name,'.$id,
            'enquiry_source_code'        => 'required',
            'enquiry_source_priority'    => '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['enquiry_source_code'] = strtoupper($data['enquiry_source_code']);

        $source = EnquirySource::find($id);

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

        $source->update($data);

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

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

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

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

        $data->delete();

        $Redirect = 'enquiry-sources';

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

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

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

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

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