<?php

namespace App\Http\Controllers\Enquiries;

use App\Models\Enquiry;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\EnquiryCategory;
use App\Models\ContactMetaData;
use App\Models\EnquiryCategoryExtraField;

class EnquiryCategoryExtraFieldsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:enquiry-category-fields-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $id)
    {
        $category = EnquiryCategory::find($id);

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

        $data = EnquiryCategoryExtraField::select([
                    'enquiry_category_extra_fields.id',
                    'enquiry_category_extra_fields.field',
                    'enquiry_category_extra_fields.type',
                    'enquiry_category_extra_fields.select_options',
                    'enquiry_category_extra_fields.status',
                    'enquiry_category_extra_fields.is_menditory',
                    'enquiry_category_extra_fields.is_readonly',
                    'enquiry_categories.category_name'
                ])
                ->leftjoin('enquiry_categories', 'enquiry_category_extra_fields.enquiry_category_id', 'enquiry_categories.id')
                ->when(!empty($id), function ($query) use ($id) {
                                return $query->where('enquiry_category_extra_fields.enquiry_category_id', $id);
                            })
                ->paginate(10);

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

            $data = EnquiryCategoryExtraField::select([
                        'enquiry_category_extra_fields.id',
                        'enquiry_category_extra_fields.field',
                        'enquiry_category_extra_fields.type',
                        'enquiry_category_extra_fields.select_options',
                        'enquiry_category_extra_fields.status',
                        'enquiry_category_extra_fields.is_menditory',
                        'enquiry_category_extra_fields.is_readonly',
                        'enquiry_categories.category_name'
                    ])
                    ->leftjoin('enquiry_categories', 'enquiry_category_extra_fields.enquiry_category_id', 'enquiry_categories.id')
                    ->when(!empty($search_query), function ($query) use ($search_query) {
                                return $query->where('field', 'like', '%'.$search_query.'%');
                            })
                    ->when(!empty($id), function ($query) use ($id) {
                                return $query->where('enquiry_category_extra_fields.enquiry_category_id', $id);
                            })
                    ->paginate($sort_by);

            return view('enquiry-category-fields.table', compact('data','id'));
        }
        else
        {
            return view('enquiry-category-fields.index', compact('data','id','category'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        return view('enquiry-category-fields.create', compact('id'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'field'               => 'required',
            'length'              => 'required',
            'type'                => 'required',
            'select_options'      => 'required_if:type,radio,checkbox,selection',
        ]);

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

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

        $data['status'] = 1;
        $data['enquiry_category_id'] = $id;

        EnquiryCategoryExtraField::create($data);

        return redirect()->back()
            ->with('success','Enquiry Category Field 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)
    {
        $field = EnquiryCategoryExtraField::find($id);

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

    /**
     * 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(), [
            'field'               => 'required',
            'length'              => 'required',
            'type'                => 'required',
            'select_options'      => 'required_if:type,radio,checkbox,selection',
        ]);

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

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

        $field = EnquiryCategoryExtraField::find($id);

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

        $field->update($data);

        return redirect()->back()
            ->with('success','Enquiry Category Field updated successfully');
    }

    public function destroy(Request $request)
    {
        $field = EnquiryCategoryExtraField::find($request->id);

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

        $field->delete();

        $Redirect = 'enquiry-category-fields';

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

    public function getFields(Request $request)
    {
        $fields = EnquiryCategoryExtraField::where('enquiry_category_id',$request->id)->where('status', 1)->orderBy('priority', 'ASC')->get();
        $enquiry_id = $request->enquiry ?? 0;
        $existingField = [];

        if ($enquiry_id > 0) {
            $enquiry = Enquiry::select('enquiries.*','account_contacts.name as contact_name')
                        ->leftjoin('account_contacts','account_contacts.id','enquiries.contact_id')->where('enquiries.id', $enquiry_id)
                        ->first();

            $existingField = ContactMetaData::where([
                    'contact_id' => $enquiry->contact_id,
                    'enquiry_id' => $enquiry_id,
                ])
                ->get()
                ->pluck('value', 'enquiry_category_fields_id');

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

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

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

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

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

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

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