<?php

namespace App\Http\Controllers\Enquiries;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Country;
use App\Models\EnquiryContact;
use App\Models\CompanyAddress;
use App\Models\Gender;
use App\Models\MaritalStatus;
use App\Models\BloodGroup;

class EnquiryContactsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:enquiry-contacts-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = EnquiryContact::select([
                    'enquiry_contacts.id',
                    'enquiry_contacts.name',
                    'enquiry_contacts.phone_no',
                    'enquiry_contacts.whatsapp_no',
                    'enquiry_contacts.email',
                    'enquiry_contacts.organization',
                    'enquiry_contacts.alternative_no',
                    'countries.name as country',
                    'states.name as state',
                    'cities.name as city',
                ])
                ->leftjoin('countries', 'countries.id', 'enquiry_contacts.country_id')
                ->leftjoin('states', 'states.id', 'enquiry_contacts.state_id')
                ->leftjoin('cities', 'cities.id', 'enquiry_contacts.city_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_contacts.name', 'like', '%'.$search_query.'%')
                            ->orWhere('enquiry_contacts.email', 'like', '%'.$search_query.'%')
                            ->orWhere('enquiry_contacts.phone_no', 'like', '%'.$search_query.'%');
                        })
                    ->paginate($sort_by);

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $genders         = Gender::select(['id','name'])->get();
        $maritalStatus   = MaritalStatus::select(['id','name'])->get();
        $bloodGroup      = BloodGroup::select(['id','group'])->get();
        $country         = Country::select(['id','name'])->where('status', '1')->get();

        $company_address = \Session::get('company_data')['companies_addresses'];
        $countryCode     = $company_address->country_code ?? 'us';

        $countryCode = $company_address->country_code ?? 'us';

        return view('enquiry-contacts.create', compact(
            'country',
            'countryCode',
            'company_address',
            'genders',
            'maritalStatus',
            'bloodGroup'
        ));
    }

    /**
     * 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',
            'phone_no' => 'required|unique:enquiry_contacts',
        ]);

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

        $contact = EnquiryContact::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Contact has been created successfully.',
                'data'    => $contact
            ]);
        }

        return redirect()->route('enquiry-contacts.index')
            ->with('success','Contact has been 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)
    {
        $genders         = Gender::select(['id','name'])->get();
        $maritalStatus   = MaritalStatus::select(['id','name'])->get();
        $bloodGroup      = BloodGroup::select(['id','group'])->get();
        $contact         = EnquiryContact::find($id);
        $country         = Country::select(['id','name'])->where('status', '1')->get();
        $company_address = \Session::get('company_data')['companies_addresses'];
        $countryCode     = $country_code->country_code ?? 'us';

        return view('enquiry-contacts.edit', compact(
            'contact',
            'country',
            'countryCode',
            'genders',
            'maritalStatus',
            'bloodGroup'
        ));
    }

    /**
     * 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(), [
            'name'     => 'required',
            'phone_no' => 'required|unique:enquiry_contacts,email,'.$id,
        ]);

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

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

        $contact = EnquiryContact::find($id);

        if (!$contact) {
            return redirect()->route('enquiry-contacts.index')
                ->with('error','Contact not found!');
        }

        $contact->update($data);

        return redirect()->route('enquiry-contacts.index')
            ->with('success','Contact has been updated successfully');
    }

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

        if (!$contact) {
            return redirect()->route('enquiry-contacts.index')
                ->with('error','Contact not found!');
        }

        $contact->delete();

        $Redirect = 'enquiry-contacts';

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

    public function getContacts(Request $request)
    {
        $data = [];

        if($request->has('q')){
            $search = $request->q;
            $data = EnquiryContact::select("id","name")
                    ->where('name','LIKE',"%$search%")
                    ->orWhere('email','LIKE',"%$search%")
                    ->orWhere('phone_no','LIKE',"%$search%")
                    ->orWhere('whatsapp_no','LIKE',"%$search%")
                    ->orWhere('alternative_no','LIKE',"%$search%")
                    ->get();
        }

        return response()->json($data);
    }

    public function createModel(Request $request)
    {
        $country = Country::select(['id','name'])->get();

        $company_address = \Session::get('company_data')['companies_addresses'];
        $countryCode = $country_code->country_code ?? 'us';

        return view('enquiry-contacts.create-model', compact('country','company_address'));
    }
}
