<?php

namespace App\Http\Controllers\Accounts;

use Illuminate\Http\Request;
use App\Models\Country;
use App\Models\AccountContact;
use App\Models\CompanyAddress;
use App\Models\Gender;
use App\Models\MaritalStatus;
use App\Models\BloodGroup;
use App\Models\CompanyEstablishmentType;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

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

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

            return view('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();
        $organization_types = CompanyEstablishmentType::select(['id','name'])->get();

        $company_address = \Session::get('company_data');
        $countryCode     = $company_address['country_code'] ?? 'us';
        // dd($company_address['country_code'] ?? 'us');

        return view('contacts.create', compact(
            'country',
            'countryCode',
            'genders',
            'maritalStatus',
            'company_address',
            'organization_types',
            '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(), [
            'phone_no' => [
                'required',
                function ($attribute, $value, $fail) use ($request) {
                    $existingContact = AccountContact::where('name', $request->name)
                        ->where('phone_no', $value)
                        ->first();
                    if ($existingContact) {
                        $fail('This Name and Phone No combination already exists.');
                    }
                }
            ],
            'name' => [
                'required',
                function ($attribute, $value, $fail) use ($request) {
                    $existingContact = AccountContact::where('phone_no', $request->phone_no)
                        ->where('name', $value)
                        ->first();
                    if ($existingContact) {
                        $fail('This Name and Phone No combination already exists.');
                    }
                }
            ],
        ], [
            'required' => 'The :attribute field is required.',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->errors()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->errors()->first());
        }

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

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

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

        return redirect()->route('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         = AccountContact::find($id);
        $country         = Country::select(['id','name'])->where('status', '1')->get();
        $company_id      = \Auth::user()->company_id ?? '';
        $company_address = \Session::get('company_data')['companies_addresses'];
        $countryCode     = $country_code->country_code ?? 'us';

        return view('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:account_contacts,email,'.$id,
        ]);

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

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

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

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

        $contact->update($data);

        return redirect()->route('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 = AccountContact::find($request->id);

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

        $contact->delete();

        $Redirect = '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 = AccountContact::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();

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