<?php

    namespace App\Http\Controllers\CRM;

    use App\Http\Controllers\Controller;
    use App\Model\crm\CRMLeadModel;
    use App\Model\crm\CRMTaskModel;
    use App\Model\crm\LeadSource;
    use App\Model\people\CustomerModel;
    use App\Model\ProvinceModel;
    use Auth;
    use Carbon\Carbon;
    use DataTables;
    use DB;
    use Fun;
    use Hash;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Crypt;
    use Validator;

    class LeadController extends Controller
    {

        public function __construct()
        {
            Fun::lang();
        }

        public function index()
        {
            $province = ProvinceModel::pluck('province_km', 'province_id');
            return view('crm.lead.index', compact('province'));
        }

        public function get_prospects(Request $request)
        {
            $data = CRMLeadModel::
            leftjoin('nso007_crm_task', 'nso007_crm_task.lead_id', 'nso007_crm_leads.id')
                ->join(DB::raw('(Select max(id) as id from nso007_crm_task group by lead_id,agent_id) c1'), function ($join) {
                    // join to get latest record group by
                    $join->on('nso007_crm_task.id', '=', 'c1.id');
                })
                ->selectRaw('
                        nso007_crm_leads.id as lead_id,
                        nso007_crm_leads.name,
                        users.name as agent_name,
                        nso007_crm_leads.contact,
                        nso007_crm_leads.address,
                        nso007_crm_leads.note,
                        nso007_crm_leads.sex,
                        nso007_crm_leads.other,
                        nso007_crm_leads.convert_status,
                        nso007_crm_leads.email,
                        nso007_crm_leads.agent_id,
                        nso007_crm_leads.known_product_by,
                        nso007_crm_leads.contact_by,
                        nso007_crm_task.date as date_follow_up,
                        lead_source,
                        nso007_crm_leads.date,
                        nso007_crm_task.task_type,
                        nso007_crm_task.complete_status,
                        nso007_crm_task.note as task_note
                        ')
                ->leftjoin('users', 'users.id', 'nso007_crm_leads.agent_id')
                ->where(function ($q) use ($request) {
                    if ($request['fol_from_date']) {
                        $q->whereDate('nso007_crm_task.date', '>=', sDate($request['fol_from_date']));
                    }
                    if ($request['fol_to_date']) {
                        $q->whereDate('nso007_crm_task.date', '<', sDate($request['fol_to_date']));
                    }
                    if ($request['from_date']) {
                        $q->whereDate('nso007_crm_leads.date', '>=', sDate($request['from_date']) . ' 00:00:00');
                    }
                    if ($request['to_date']) {
                        $q->whereDate('nso007_crm_leads.date', '<', sDate($request['to_date']) . ' 23:59:59');
                    }
                    if (count($request->agent??[])) {
                        $q->whereIn('nso007_crm_leads.agent_id', $request->agent);
                    }
                    if ($request->contact_by) {
                        $q->where('nso007_crm_leads.contact_by', $request->contact_by);
                    }
                    if ($request->last_name) {
                        $q->where('nso007_crm_leads.name', 'like', '%' . $request->last_name . '%');
                    }
                    if ($request->contact) {
                        $q->where('nso007_crm_leads.contact', 'like', '%' . $request->contact . '%');
                    }
                    if ($request->address) {
                        $q->where('nso007_crm_leads.address', 'like', '%' . $request->address . '%');
                    }
                    if ($request->note) {
                        $q->where('nso007_crm_leads.note', 'like', '%' . $request->note . '%');
                    }
                    if ($request->other) {
                        $q->where('nso007_crm_leads.other', 'like', '%' . $request->other . '%');
                    }

                    if (count($request->deal_status??[])) {
                        $q->whereIn('nso007_crm_leads.convert_status', $request->deal_status);
                    }
                    if ($request->type) {
                        $q->where('task_type', $request->type);
                    }
                    if (count($request->lead_source??[])) {
                        $q->whereIn('lead_source', $request->lead_source);
                    }
                    $q->where('nso007_crm_leads.delete_status', $request->delete_status);
                })
                ->groupBy('nso007_crm_task.lead_id')
                ->orderBy('nso007_crm_leads.date', 'desc');
            $count = $data->get()->count();
            return DataTables::of($data->take(20))
                ->with([
                    "recordsTotal" => $count,
                    "recordsFiltered" => $count,
                ])
                ->editColumn('date', function ($data) use ($request) {
                    return date('d-m-Y h:i', strtotime($data->date));
                })
                ->editColumn('date_follow_up', function ($data) use ($request) {
                    return date('d-m-Y', strtotime($data->date_follow_up));
                })
                ->editColumn('convert_status', function ($data) {
                    if ($data->convert_status != 0)
                        return bgDealStatus($data->convert_status);
                })
                ->editColumn('sex', function ($data) {
                    if ($data->sex)
                        return __('administrator.' . $data->sex);
                })
                ->addColumn('action', function ($lead) {
                        $btn = '<a href="' . route("prospect.show", $lead->lead_id) . '"><i href="javascript:;" class="fa fa-eye btn btn-sm btn-success" title="View"></i></a> ';

                            if ($lead->convert_status != 1) {
                                $btn .= ' <i
                                 data-href = "' . route("task.create") . '?lead_id=' . $lead->lead_id . '" data-email="' . $lead->email . '"
                                class="fa fa-tasks btn btn-sm btn-primary" title="Task"></i>
                                <a href= "' . route("prospect.edit", $lead->lead_id) . '" class="fa fa-pencil btn btn-sm btn-warning" title="Edit"></a>';
                            } else {
                                $customer = CustomerModel::where('lead_id', $lead->lead_id)->first();
                                $customer = $customer ? $customer->id : '';
                                $btn .= ' <a href="' . route("pos.create") . '?postype=rldf8e7sdf&sale_req=kl98sdf77&lead=1&hellowajitnomotocambo=hibbbyerequestbyeloveyou&customer=' . (Crypt::encrypt($customer)) . '"><i href="javascript:;" class="fa fa-shopping-cart btn btn-sm btn-info" title="POS"></i></a> ';
                            }

                        if ($lead->convert_status != 1) {
                            if ((Auth::user()->can('Prospect Delete'))) { //&& date('Y-m-d',strtotime($lead->date)) === date('Y-m-d')
                                $btn .= ' <i data-url = "' . route("prospect.destroy", $lead->lead_id) . '" class="fa fa-trash btn btn-sm btn-danger" title="Delete"></i>';
                            }
                        }
                        return $btn;

                })
                ->editColumn('task_type', function ($data) use ($request) {
                    if ($data->task_type) {
                        if ($data->complete_status) {
                            $task_type = 'success';
                        } else {
                            $task_type = 'warning';
                        }
                        return '<span class="label label-' . $task_type . '">' . __('administrator.' . $data->task_type) . ' </span>';
                    }
                })
                ->editColumn('lead_source', function ($data) {
                    if ($data->lead_source)
                        return leadSource($data->lead_source);
                })
                ->addIndexColumn()
                ->rawColumns(['action', 'convert_status', 'illness','task_type'])
                ->make(true);
        }

        public function create()
        {
            $province = ProvinceModel::pluck('province_km', 'province_id');
            return view('crm.lead.create', compact('province'));
        }

        public function edit($id)
        {
            $province = ProvinceModel::pluck('province_km', 'province_id');
            $lead = CRMLeadModel::find($id);
            return view('crm.lead.edit', compact('province', 'lead'));
        }

        function translate($key)
        {
            return __('administrator.' . $key) . ' ' . __('administrator.field is required.');
        }

        public function store(Request $request)
        {
            $this->validate($request,[
                'task_type'=>'required',
                'subject'=>'required',
                'place'=>'required',
                'date_follow_up'=>'required',
            ]);
            $this->validate_lead($request);
            $lead = $this->create_lead($request, null);


            if($request->task_type || $request->subject || $request->place || $request->date_follow_up){
                $task = new CRMTaskModel;
                $task->lead_id = $lead->id;
                $task->agent_id = $request->agent_id;
                $task->branch_id = $lead->branch_id;
                $task->task_type = $request->task_type;
                $task->subject = $request->subject;
                $task->where = $request->place;
                $task->date = date('Y-m-d', strtotime($request->date_follow_up));
                $task->save();
            }
            session()->put('success', 'Record was Create successful');
            return response()->json(['status' => 'ok', 'route' => route('prospect.index')]);
        }

        public function show($id)
        {
            $lead = CRMLeadModel::find($id);
            $task = CRMTaskModel::where('lead_id', $id)->orderBy('date', 'DESC')->get();
            return view('crm.lead.show', compact('lead', 'task'));
        }

        public function update(Request $request, $id)
        {

            $this->validate_lead($request);
            $this->create_lead($request, $id);
            return response()->json(['status' => 'ok', 'route' => route('prospect.index')]);
        }

        public function destroy($id, Request $request)
        {
            $this->validate($request, [
                'delete_reason' => 'required|max:200'
            ]);
            CRMLeadModel::findOrFail($id)->update(['delete_status' => 1, 'delete_reason' => $request->delete_reason, 'deleted_by' => Auth::user()->id, 'deleted_at' => date('Y-m-d h:i:s')]);
            CustomerModel::where('lead_id', $id)->update(['member_type_id' => 5]);
            return response()->json(['status' => 'success']);
        }

        public function closeDeal(Request $request, $id)
        {
            $lead = CRMLeadModel::find($id);
            $lead->update(['convert_status' => $request->result, 'close_deal_note' => $request->note]);

            $arr = [];
            $arr['branch_id'] = Auth::user()->branch_id;
            $arr['user_id'] = Auth::user()->id;
            $arr['name'] = $lead->name;
            $arr['phone'] = $lead->phone;
            $arr['sex'] = $lead->contact;
            CustomerModel::updateOrCreate([
                'lead_id'=>$lead->id
            ],$arr);

            return response()->json([200]);
        }

        public function upcoming_task(Request $request)
        {
            if ($request->ajax()) {
                $lead_id = $request->lead_id;
                $agent_id = $request->agent_id;
                $task_type = $request->task_type;
                $subject = $request->subject;
                $note = $request->note;
                $branch_id = $request->branch_id;
                $from_date = $request->from_date ? sDate($request->from_date) : null;
                $to_date = $request->to_date ? sDate($request->to_date) : null;
                $data = CRMTaskModel::join('nso007_crm_leads', 'nso007_crm_leads.id', 'nso007_crm_task.lead_id')
                    ->join(DB::raw('(Select max(id) as id from nso007_crm_task group by lead_id,agent_id) c1'), function ($join) {
                        // join to get latest record groupby
                        $join->on('nso007_crm_task.id', '=', 'c1.id');
                    })
                    ->selectRaw('nso007_crm_task.*,nso007_crm_leads.contact,nso007_crm_leads.name,nso007_crm_leads.agent_id as user_id')
                    ->where('nso007_crm_leads.convert_status', '!=', 1)
                    ->where('nso007_crm_leads.convert_status', '!=', 2)
                    ->where('nso007_crm_leads.delete_status', 0)
                    ->where(function ($q) {
                        $q->where('nso007_crm_leads.agent_id', auth()->id());
                    })
                    ->where(function ($q) use ($from_date, $to_date, $request) {
                        if ($from_date && $to_date) {
                            if ($from_date) {
                                $q->where('nso007_crm_task.date', '>=', $from_date);
                            }
                            if ($to_date) {
                                $q->where('nso007_crm_task.date', '<=', $to_date);
                            }
                        } else {
                            $q->where('nso007_crm_task.date', Carbon::today());
                        }
                    })
                    ->where(function ($q) use ($lead_id) {
                        if ($lead_id) {
                            $q->where('lead_id', $lead_id);
                        }
                    })
                    ->where(function ($q) use ($branch_id) {
                        if ($branch_id) {
                            $q->where('nso007_crm_leads.branch_id', $branch_id);
                        }
                    })
                    ->where(function ($q) use ($agent_id) {
                        if ($agent_id) {
                            $q->where('nso007_crm_leads.agent_id', $agent_id);
                        }
                    })
                    ->where(function ($q) use ($task_type) {
                        if ($task_type) {
                            $q->where('task_type', $task_type);
                        }
                    })
                    ->where(function ($q) use ($subject) {
                        if ($subject) {
                            $q->where('nso007_crm_task.subject', 'like', '%' . $subject . '%');
                        }
                    })
                    ->where(function ($q) use ($note) {
                        if ($note) {
                            $q->where('nso007_crm_task.note', 'like', '%' . $note . '%');
                        }
                    })
                    ->orderBy('id', 'desc');
                $count_filter = $data->get()->count();

                return DataTables::of($data->take(20))
                    ->with([
                        "recordsTotal" => $count_filter,
                        "recordsFiltered" => $count_filter,
                    ])
                    ->editColumn('agent_id', function ($data) {
                        $user = findUser($data->user_id);
                        return $user ? $user->name : '';
                    })
                    ->editColumn('partner_id', function ($data) {
                        return findBranch($data->partner_id)->name ?? '';
                    })
                    ->editColumn('task_type', function ($data) {
                        if ($data->task_type)
                            return __('administrator.' . $data->task_type);
                    })
                    ->editColumn('subject', function ($data) {
                        return $data->subject;
                    })
                    ->editColumn('where', function ($data) {
                        return $data->where;
                    })
                    ->editColumn('date', function ($data) {
                        return myDate($data->date);
                    })
                    ->editColumn('note', function ($data) {
                        return '<textarea rows="3" class="no-bg no-border">' . $data->note . '</textarea>';

                    })
                    ->addColumn('action', function ($lead) {
                        $btn = '<a href="' . route("prospect.show", $lead->lead_id) . '"><i href="javascript:;" class="fa fa-eye btn btn-sm btn-success" title="View"></i></a>';
                        return $btn;
                    })
                    ->addIndexColumn()
                    ->rawColumns(['lead_contact', 'action', 'note', 'convert_status'])
                    ->make(true);
            }
            return view('crm.upcoming-task.index');
        }

        public function search_lead(Request $request)

        {
            $key = $request->term['term'];
            $customer = CRMLeadModel::where(function ($q) use ($key) {
                if ($key) {
                    $q->where('name', 'like', '%' . $key . '%');
                    $q->orwhere('contact', 'like', '%' . $key . '%');
                    $q->orwhere('email', 'like', '%' . $key . '%');
                }
            })
                ->where('agent_id', auth()->id())
                ->limit(30)
                ->pluck('name', 'id')
                ->prepend('Please Select', '');
            $arr = [];

            foreach ($customer as $key => $row) {
                $arr[] = ['id' => $key, 'text' => $row];
            }
            return \Response::json($arr);

        }

        public function report(Request $request)
        {

            if ($request->ajax()) {
                $illness = $request->illness;
                $data = CRMLeadModel::
                leftjoin('nso007_crm_task', 'nso007_crm_task.lead_id', 'nso007_crm_leads.id')
                    ->join(DB::raw('(Select max(id) as id from nso007_crm_task group by lead_id,agent_id) c1'), function ($join) {
                        // join to get latest record groupby
                        $join->on('nso007_crm_task.id', '=', 'c1.id');
                    })
                    ->where(function ($q) {
                        $mybranch = myBranch();
                        if (if_main($mybranch) || Auth::user()->can('CRM Leader')) {
                            $q->whereIn('nso007_crm_leads.branch_id', getRelatedBranchId($mybranch));
                        } else {
                            $q->where('nso007_crm_task.agent_id', Auth::user()->id);
                        }
                    })
                    ->where('nso007_crm_leads.delete_status', 0)
                    ->where(function ($q) use ($request, $illness) {
                        if ($request->branch_id) {
                            $q->where('nso007_crm_leads.branch_id', $request->branch_id);
                        }

                        if ($request->lead_id) {
                            $q->where('nso007_crm_leads.id', $request->lead_id);
                        }
                        if ($request->agent_id) {
                            $q->where('nso007_crm_leads.agent_id', $request->agent_id);
                        }
                        if ($request->sex) {
                            $q->where('nso007_crm_leads.sex', $request->sex);
                        }

                        if ($request->convert_status) {
                            $q->where('nso007_crm_leads.convert_status', $request->convert_status);
                        }
                        if ($request->province) {
                            $q->where('nso007_crm_leads.province', $request->province);
                        }
                        if ($request->lead_source) {
                            $q->where('nso007_crm_leads.lead_source', $request->lead_source);
                        }
                        if ($request->type) {
                            $q->where('task_type', $request->type);
                        }

                        if ($request->impression) {
                            $q->where('nso007_crm_leads.impression', $request->impression);
                        }
                        if ($request->status_of_prospect) {
                            $q->where('status_of_prospect', $request->status_of_prospect);
                        }
                        if ($request->prospect_subject) {
                            $q->where('prospect_subject', $request->prospect_subject);
                        }
                        if ($request->search_contact) {
                            $q->where('nso007_crm_leads.contact', 'like', '%' . $request->search_contact . '%');
                        }
                        if ($request->search_address) {
                            $q->where('nso007_crm_leads.address', 'like', '%' . $request->search_address . '%');
                        }
                        if ($request->note) {
                            $q->where('nso007_crm_leads.note', 'like', '%' . $request->note . '%');
                        }
                        if ($illness) {
                            $q->where('illness', 'like', '%"' . $illness . '"%');
                        }
                    })
                    ->where(function ($q) use ($request) {
                        if ($request->r_start_date) {
                            $q->whereDate('nso007_crm_leads.date', '>=', date('Y-m-d', strtotime($request->r_start_date)));
                        }
                        if ($request->r_end_date) {
                            $q->whereDate('nso007_crm_leads.date', '<=', date('Y-m-d', strtotime($request->r_end_date)));
                        }
                    })
                    ->where(function ($q) use ($request) {
                        if ($request->f_start_date) {
                            $q->whereDate('nso007_crm_task.date', '>=', date('Y-m-d', strtotime($request->f_start_date)));
                        }
                        if ($request->f_end_date) {
                            $q->whereDate('nso007_crm_task.date', '<=', date('Y-m-d', strtotime($request->f_end_date)));
                        }
                    })
                    ->selectRaw('
                            nso007_crm_leads.name,
                            nso007_crm_leads.family_name,
                            nso007_crm_leads.contact,
                            nso007_crm_leads.address,
                            nso007_crm_leads.job,
                            nso007_crm_leads.workplace,
                            nso007_crm_leads.sex,
                            nso007_crm_leads.date as register_date,
                            nso007_crm_leads.convert_status,
                            nso007_crm_leads.email,
                            nso007_crm_leads.agent_id,
                            nso007_crm_leads.illness,
                            nso007_crm_leads.province,
                            nso007_crm_task.date as date_follow_up,
                            nso007_crm_task.complete_status,
                            nso007_crm_task.lead_id,
                            nso007_crm_leads.id,
                            nso007_crm_leads.note,
                            nso007_crm_leads.impression,
                            nso007_crm_leads.contact_by,
                            nso007_crm_leads.status_of_prospect,
                            nso007_crm_leads.prospect_subject,
                            nso007_crm_task.task_type,
                            lead_source')
                    ->groupBy('nso007_crm_task.lead_id')
                    ->orderBy('nso007_crm_leads.id', 'desc');
                $count = $data->get()->count();
                return DataTables::of($data->take(20))
                    ->with([
                        "recordsTotal" => $count,
                        "recordsFiltered" => $count,
                    ])
                    ->editColumn('date_follow_up', function ($data) {
                        return myDate($data->date_follow_up);
                    })
                    ->editColumn('register_date', function ($data) {
                        return date('d-m-Y', strtotime($data->register_date));
                    })

                    ->editColumn('sex', function ($data) {
                        return __('administrator.' . $data->sex);
                    })
                    ->editColumn('lead_source', function ($data) {
                        $source = LeadSource::find($data->lead_source);
                        return $source ? $source->source_name : '';
                    })
                    ->editColumn('convert_status', function ($data) use ($request) {
                        if ($data->convert_status == 1) {
                            $status = 'success';
                        } else {
                            if ($data->convert_status != 0) {
                                $status = 'danger';
                            } else {
                                $status = 'warning';
                            }
                        }
                        if ($data->convert_status) {
                            $deal = getDealResult($data->convert_status);
                        } else {
                            $deal = __('administrator.pending');
                        }
                        return '<span class="label label-' . $status . '">' . $deal . ' </span>';
                    })
                    ->editColumn('task_type', function ($data) use ($request) {
                        if ($data->task_type) {
                            if ($data->complete_status) {
                                $task_type = 'success';
                            } else {
                                $task_type = 'warning';
                            }
                            return '<span class="label label-' . $task_type . '">' . __('administrator.' . $data->task_type) . ' </span>';
                        }
                    })
                    ->editColumn('impression', function ($data) {
                        if ($data->impression)
                            return getImpression($data->impression ?: 'arigato') ?: $data->impression;
                    })
                    ->editColumn('status_of_prospect', function ($data) use ($request) {
                        if ($data->status_of_prospect)
                            return getStatusOfProspect($data->status_of_prospect);
                    })
                    ->editColumn('prospect_subject', function ($data) use ($request) {
                        if ($data->prospect_subject)
                            return getProspectSubject($data->prospect_subject);
                    })
                    ->editColumn('province', function ($data) use ($request) {
                        $province = ProvinceModel::where('province_id', $data->province)->first();
                        if ($province) {
                            if (if_kh()) {
                                $province = $province->province_km;
                            } else {
                                $province = $province->province_en;
                            }
                        } else {
                            $province = '';
                        }
                        return $province;
                    })
                    ->addColumn('agent_name', function ($data) use ($request) {
                        return findUser($data->agent_id)->name ?? '';
                    })
                    ->editColumn('impression', function ($data) use ($request) {
                        return ImpressionModel::find($data->impression)->name ?? '';
                    })
                    ->addColumn('illness', function ($data) {
                        if ($data->illness) {
                            return getCustomerIllnessJson($data->illness);
                        }
                    })
                    ->addIndexColumn()
                    ->rawColumns(['action', 'convert_status', 'task_type', 'agent_name', 'illness'])
                    ->make(true);
            }
            return view('crm.lead.report');
        }

        public function validate_lead($request)
        {
            return $this->validate($request, [
                'date' => 'required',
                'name' => 'required',
                'product_id.*' => 'required|exists:nso007_products,id',
                'usage.*' => 'required',
            ]);
        }

        public function create_lead($request, $id)
        {

            $data = $request->all();
            $data['branch_id'] = myBranch() ? myBranch()->id : '';
            $data['agent_id'] = auth()->id();
            $data['convert_status'] = $request->convert_status ?? 0;
            $data['date'] = sDate($request->date, 1);
            return CRMLeadModel::updateOrCreate(['id' => $id], $data);
        }

    }
