<?php

namespace App\Http\Controllers\Enquiries;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ContactMetaData;
use App\Models\Enquiry;
use App\Models\EnquiryCategoryExtraField;
use App\Models\EnquiryCategory;
use App\Models\EnquiryQuality;
use App\Models\EnquirySource;
use App\Models\EnquiryStatus;
use App\Models\EnquiryType;
use App\Models\CompanyAddress;
use App\Models\EnquiryAttachment;
use App\Models\DocumentAndAttachment;
use App\Models\EnquiryContact;

class EnquiriesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:enquiry-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (!$this->modulePermissionCheck('ENQUIRY')) {
            abort(404);
        }

        $data = Enquiry::select([
                    'enquiries.id',
                    'enquiries.enquiry_date',
                    'enquiry_categories.category_name',
                    'enquiry_qualities.enquiry_quality_name',
                    'enquiry_sources.enquiry_source_name',
                    'enquiry_types.enquiry_type_name',
                    'enquiry_qualities.color as qualities_color',
                    'enquiry_qualities.bg_color as qualities_bg_color',
                    'enquiry_statuses.enquiry_status_name',
                    'enquiry_statuses.color',
                    'enquiry_statuses.bg_color',
                    'enquiry_contacts.name',
                    'enquiry_contacts.email',
                    'enquiry_contacts.phone_no',
                    'enquiry_contacts.organization',
                    'enquiry_contacts.whatsapp_no',
                ])
                ->leftjoin('enquiry_categories','enquiry_categories.id','enquiries.enquiry_category_id')
                ->leftjoin('enquiry_qualities','enquiry_qualities.id','enquiries.enquiry_quality_id')
                ->leftjoin('enquiry_sources','enquiry_sources.id','enquiries.enquiry_source_id')
                ->leftjoin('enquiry_types','enquiry_types.id','enquiries.enquiry_type_id')
                ->leftjoin('enquiry_statuses','enquiry_statuses.id','enquiries.enquiry_status_id')
                ->leftjoin('enquiry_contacts','enquiry_contacts.id','enquiries.contact_id');

        if ($request->ajax()) {
            $sort_by             = $request->get('sortby') ?? 10;
            $sort_type           = $request->get('sorttype');
            $search_query        = $request->get('query');
            $search_type         = $request->get('search_type');
            $enquiry_category_id = $request->get('enquiry_category_id') ?? '';
            $enquiry_quality_id  = $request->get('enquiry_quality_id') ?? '';
            $enquiry_source_id   = $request->get('enquiry_source_id') ?? '';
            $enquiry_type_id     = $request->get('enquiry_type_id') ?? '';
            $enquiry_status_id   = $request->get('enquiry_status_id') ?? '';

            $data = $data
                ->when(!empty($enquiry_category_id), function ($query) use ($enquiry_category_id) {
                    return $query->where('enquiries.enquiry_category_id', $enquiry_category_id);
                })
                ->when(!empty($enquiry_quality_id), function ($query) use ($enquiry_quality_id) {
                    return $query->where('enquiries.enquiry_quality_id', $enquiry_quality_id);
                })
                ->when(!empty($enquiry_source_id), function ($query) use ($enquiry_source_id) {
                    return $query->where('enquiries.enquiry_source_id', $enquiry_source_id);
                })
                ->when(!empty($enquiry_type_id), function ($query) use ($enquiry_type_id) {
                    return $query->where('enquiries.enquiry_type_id', $enquiry_type_id);
                })
                ->when(!empty($enquiry_status_id), function ($query) use ($enquiry_status_id) {
                    return $query->where('enquiries.enquiry_status_id', $enquiry_status_id);
                })
                ->when(!empty($search_query) && !empty($search_type),
                function ($query) use ($search_query, $search_type) {
                    if ($search_type == 'name') {
                        $query->where('enquiry_contacts.name', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'organization') {
                        $query->where('enquiry_contacts.organization', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'phone_no') {
                        $query->where('enquiry_contacts.phone_no', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'enquiry_type_name') {
                        $query->where('enquiry_types.enquiry_type_name', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'category_name') {
                        $query->where('enquiry_categories.category_name', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'enquiry_source_name') {
                        $query->where('enquiry_sources.enquiry_source_name', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'enquiry_quality_name') {
                        $query->where('enquiry_qualities.enquiry_quality_name', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'enquiry_status_name') {
                        $query->where('enquiry_statuses.enquiry_status_name', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'whatsapp_no') {
                        $query->where('enquiry_contacts.whatsapp_no', 'like', '%'.$search_query.'%');
                    }
                })
                ->orderBy('enquiries.enquiry_date','DESC')
                ->orderBy('enquiries.id','DESC')
                ->paginate($sort_by);

            return view('enquiries.table', compact('data'));
        }
        else
        {
            $data = $data->orderBy('enquiries.enquiry_date','DESC')
                ->orderBy('enquiries.id','DESC')
                ->paginate(10);

            return view('enquiries.index', compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories = EnquiryCategory::where('status', 1)->get();
        $qualities  = EnquiryQuality::where('status', 1)->orderBy('enquiry_quality_priority', 'ASC')->get();
        $sources    = EnquirySource::where('status', 1)->orderBy('enquiry_source_priority', 'ASC')->get();
        $statuses   = EnquiryStatus::where('status', 1)->orderBy('enquiry_status_priority', 'ASC')->get();
        $types      = EnquiryType::where('status', 1)->orderBy('enquiry_type_priority', 'ASC')->get();

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

        return view('enquiries.create', compact('categories','qualities','sources','statuses','types','countryCode'));
    }

    /**
     * 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_date'           => 'required',
            'contact_id'             => 'required',
            'enquiry_category_id'    => 'required',
            'enquiry_type_id'        => 'required',
            'enquiry_source_id'      => 'required',
            'enquiry_status_id'      => 'required',
            'enquiry_quality_id'     => '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());
        }

        $enquiry['contact_id']          = $request->contact_id ?? '';
        $enquiry['enquiry_details']     = $request->enquiry_details ?? '';
        $enquiry['enquiry_type_id']     = $request->enquiry_type_id ?? '';
        $enquiry['enquiry_source_id']   = $request->enquiry_source_id ?? '';
        $enquiry['enquiry_category_id'] = $request->enquiry_category_id ?? '';
        $enquiry['enquiry_status_id']   = $request->enquiry_status_id ?? '';
        $enquiry['enquiry_quality_id']  = $request->enquiry_quality_id ?? '';
        $enquiry['user_id']             = \Auth::user()->id;
        $enquiry['company_id']          = \Auth::user()->company_id;
        $enquiry_date                   = \DateTime::createFromFormat('m-d-Y', $request->enquiry_date);
        $enquiry['enquiry_date']           = date('Y-m-d', $enquiry_date->getTimestamp());

        $enquiry    = Enquiry::create($enquiry);
        $enquiry_id = $this->generateCode($enquiry->id, 'ENQ');

        $enquiry->update(['enquiry_id' => $enquiry_id]);

        $data = $request->except([
            '_token',
            '_method',
            'attachments',
            'contact_id',
            'enquiry_date',
            'enquiry_details',
            'enquiry_type_id',
            'enquiry_source_id',
            'enquiry_category_id',
            'enquiry_status_id',
            'enquiry_quality_id'
        ]);

        foreach($data as $key => $value) {
            $field = [
                "contact_id"                 => $request->contact_id,
                "enquiry_id"                 => $enquiry->id,
                "enquiry_category_fields_id" => $key,
                "value"                      => $value
            ];
            ContactMetaData::create($field);
        }

        $files        = $request->file('attachments');
        $contact      = EnquiryContact::select('name','id')->where('id',$request->contact_id)->first();
        $contact_name = $contact->name ?? '';
        $contact_id = $contact->id ?? '';

        if ($files) {
            $path = 'uploads/' . $contact_id . '-' . $contact_name . '/attachments/' . date('Y') . '/' . date('M');
            foreach($files as $key => $file) {
                $extension = $file->getClientOriginalExtension();
                $name      = basename($file->getClientOriginalName(), '.'.$extension);
                $filename  = 'attachment-'.$key.time() . '.' . $extension;
                $file->move($path, $filename);

                $attachment = DocumentAndAttachment::create([
                    'attachment_name'  => $path . '/' . $filename,
                    'attachment_title' => $name
                ]);

                EnquiryAttachment::create([
                    'enquiry_id'     => $enquiry->id,
                    'attachments_id' => $attachment->id
                ]);
            }
        }
        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Enquiry has been created successfully',
            ]);

        }
        return redirect()->route('enquiries.index')
            ->with('success','Enquiry has been created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $enquiry = Enquiry::select([
                    'enquiries.id',
                    'enquiries.enquiry_date',
                    'enquiry_categories.category_name',
                    'enquiry_qualities.enquiry_quality_name',
                    'enquiry_sources.enquiry_source_name',
                    'enquiry_types.enquiry_type_name',
                    'enquiry_statuses.enquiry_status_name',
                    'enquiry_statuses.color',
                    'enquiry_statuses.bg_color',
                    'enquiries.contact_id',
                    'enquiry_contacts.name',
                    'enquiry_contacts.email',
                    'enquiry_contacts.phone_no',
                    'enquiry_contacts.address',
                    'enquiry_contacts.contact_person',
                    'enquiry_contacts.organization',
                    'enquiry_contacts.whatsapp_no',
                    'enquiry_contacts.alternative_no',
                    'enquiry_contacts.website_url',
                ])
                ->leftjoin('enquiry_categories','enquiry_categories.id','enquiries.enquiry_category_id')
                ->leftjoin('enquiry_qualities','enquiry_qualities.id','enquiries.enquiry_quality_id')
                ->leftjoin('enquiry_sources','enquiry_sources.id','enquiries.enquiry_source_id')
                ->leftjoin('enquiry_types','enquiry_types.id','enquiries.enquiry_type_id')
                ->leftjoin('enquiry_statuses','enquiry_statuses.id','enquiries.enquiry_status_id')
                ->leftjoin('enquiry_contacts','enquiry_contacts.id','enquiries.contact_id')
                ->where('enquiries.id', $id)
                ->first();

        $attachments = DocumentAndAttachment::select([
                    'document_and_attachments.attachment_name',
                    'document_and_attachments.attachment_title'
                ])
                ->leftjoin('enquiry_attachments', 'enquiry_attachments.attachments_id', 'document_and_attachments.id')
                ->where('enquiry_attachments.enquiry_id', $id)
                ->get();

        $extraField = ContactMetaData::select([
                    'contact_meta_data.value',
                    'enquiry_category_extra_fields.field',
                ])
                ->leftjoin('enquiry_category_extra_fields','enquiry_category_extra_fields.id','contact_meta_data.enquiry_category_fields_id')
                ->where([
                    'contact_meta_data.contact_id' => $enquiry->contact_id,
                    'contact_meta_data.enquiry_id' => $enquiry->id,
                ])
                ->get();

        return view('enquiries.show', compact('enquiry','extraField','attachments'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $enquiry = Enquiry::select('enquiries.*','enquiry_contacts.name as contact_name')
                        ->leftjoin('enquiry_contacts','enquiry_contacts.id','enquiries.contact_id')->where('enquiries.id', $id)
                        ->first();

        if (!$enquiry) {
            return redirect()->back()->with('error', 'Enquiry not found!');
        }

        $enquiry->enquiry_date = date('d-m-Y', strtotime($enquiry->enquiry_date));

        $categories = EnquiryCategory::where('status', 1)->get();
        $qualities  = EnquiryQuality::where('status', 1)->orderBy('enquiry_quality_priority', 'ASC')->get();
        $sources    = EnquirySource::where('status', 1)->orderBy('enquiry_source_priority', 'ASC')->get();
        $statuses   = EnquiryStatus::where('status', 1)->orderBy('enquiry_status_priority', 'ASC')->get();
        $types      = EnquiryType::where('status', 1)->orderBy('enquiry_type_priority', 'ASC')->get();

        $company_address = \Session::get('company_data')['companies_addresses'];
        $countryCode = $country_code->country_code ?? 'us';
        $attachments = DocumentAndAttachment::select([
                    'document_and_attachments.id',
                    'document_and_attachments.attachment_name',
                    'document_and_attachments.attachment_title'
                ])
                ->leftjoin('enquiry_attachments', 'enquiry_attachments.attachments_id', 'document_and_attachments.id')
                ->where('enquiry_attachments.enquiry_id', $id)
                ->get();

        return view('enquiries.edit', compact('id','categories','qualities','sources','statuses','types','enquiry','countryCode','attachments'));
    }

    /**
     * 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_date' => 'required'
        ]);

        if ($validator->fails()) {
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }
        $enquiry = Enquiry::findOrFail($id);

        if (!$enquiry) {
            return redirect()->back()->with('error', 'Enquiry not found!');
        }

        $old_enquiry_category_id      = $enquiry->enquiry_category_id;
        $enquiry_date                 = \DateTime::createFromFormat('m-d-Y', $request->enquiry_date);
        $enquiry->enquiry_date        = date('Y-m-d', $enquiry_date->getTimestamp());
        $enquiry->enquiry_details     = $request->enquiry_details;
        $enquiry->enquiry_type_id     = $request->enquiry_type_id;
        $enquiry->enquiry_source_id   = $request->enquiry_source_id;
        $enquiry->enquiry_category_id = $request->enquiry_category_id;
        $enquiry->enquiry_status_id   = $request->enquiry_status_id;
        $enquiry->enquiry_quality_id  = $request->enquiry_quality_id;
        $enquiry->save();

        $data = $request->except([
            '_token',
            '_method',
            'contact_id',
            'attachments',
            'enquiry_date',
            'enquiry_details',
            'enquiry_type_id',
            'enquiry_source_id',
            'enquiry_category_id',
            'enquiry_status_id',
            'enquiry_quality_id'
        ]);

        if ($old_enquiry_category_id != $request->enquiry_category_id) {
            ContactMetaData::where([
                'contact_id'                 => $enquiry->contact_id,
                'enquiry_id'                 => $id,
                'enquiry_category_fields_id' => $old_enquiry_category_id
            ])->delete();
        }

        foreach($data as $key => $value) {
            $existingField = ContactMetaData::where([
                'contact_id'                 => $enquiry->contact_id,
                'enquiry_id'                 => $id,
                'enquiry_category_fields_id' => $key
            ])->first();

            if ($existingField) {
                $existingField->update([
                    'value' => $value
                ]);
            } else {
                $field = [
                    "contact_id"                 => $enquiry->contact_id,
                    "enquiry_id"                 => $id,
                    "enquiry_category_fields_id" => $key,
                    "value"                      => $value
                ];
                ContactMetaData::create($field);
            }
        }

        $files        = $request->file('attachments');
        $contact      = EnquiryContact::select('name','id')->where('id',$enquiry->contact_id)->first();
        $contact_name = $contact->name;
        $contact_id = $contact->id;

        if ($files) {
            $path = 'uploads/' . $contact_id . '-' . $contact_name . '/attachments/' . date('Y') . '/' . date('M');
            foreach($files as $key => $file) {
                $extension = $file->getClientOriginalExtension();
                $name      = basename($file->getClientOriginalName(), '.'.$extension);
                $filename  = 'attachment-'.$key.time() . '.' . $extension;
                $file->move($path, $filename);

                $attachment = DocumentAndAttachment::create([
                    'attachment_name'  => $path . '/' . $filename,
                    'attachment_title' => $name
                ]);

                EnquiryAttachment::create([
                    'enquiry_id'     => $enquiry->id,
                    'attachments_id' => $attachment->id
                ]);
            }
        }

        return redirect()->route('enquiries.index')
            ->with('success','Enquiry has been updated successfully.');
    }

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

        if (!$enquiry) {
            return redirect()->route('enquiries.index')->with('error','Enquiry not found!');
        }
        ContactMetaData::where(['enquiry_id' => $request->id])->delete();

        $attachments = EnquiryAttachment::select(['attachments_id'])->where(['enquiry_id' => $request->id])->get();
        foreach ($attachments as $key => $value) {
            DocumentAndAttachment::where(['id' => $value->attachments_id])->delete();
        }
        EnquiryAttachment::where(['enquiry_id' => $request->id])->delete();
        $enquiry->delete();

        $Redirect = 'enquiries';

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

    public function destroyAttachment(Request $request)
    {
        EnquiryAttachment::where('attachments_id', $request->id)->delete();
        DocumentAndAttachment::where('id', $request->id)->delete();

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