<?php

namespace App\Http\Controllers\CRMAgency;

use App\ClientModel;
use App\Models\CRMLeadModel;
use App\Models\CRMLeadSourceModel;
use DB;
use App\Models\CRMTaskModel;
use App\CustomerModel;
use App\User;
use App\Fun\Fun;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Yajra\DataTables\DataTables;

class LeadAgentController extends Controller
{
    public function index()
    {
        $u_id = Auth::user()->id;
        $agent = User::select(DB::raw('CONCAT(user_firstname," ",user_lastname) AS name'), 'id')
            ->where(function ($q) use ($u_id) {
                if (!Auth::user()->role == 'Administrator') {
                    $q->where('id', $u_id);
                    $q->orwhere('leader_id', $u_id);
                }
            })->pluck('name', 'id');
        return view('CRMAgent.lead.index', compact('agent'));
    }

    public function create()
    {

        $lead_source = CRMLeadSourceModel::pluck('source_name', 'id');
        $u_id = Auth::user()->id;
        $agent = User::select(DB::raw('CONCAT(user_firstname," ",user_lastname) AS name'), 'id')
            ->where(function ($q) use ($u_id) {
                if (Auth::user()->role != 'Administrator') {
                    $q->where('id', $u_id);
                    $q->orwhere('leader_id', $u_id);
                }
            })
            ->pluck('name', 'id');

        return view('CRMAgent.lead.create', compact('lead_source', 'agent'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'sex' => 'required',
            'date' => 'required',
            'lead_source' => 'required',
            'family_name' => 'required',
            'name' => 'required',
            'contact' => 'required|unique:nso007_crm_leads,contact,',
            'address' => 'required',
            'job' => 'required',
            'workplace' => 'required',
            'agent' => 'required',
        ]);
        $addlead = new CRMLeadModel();
        if(isset($request->contact)){
            $phone="";$phone_insert="";
            preg_match_all('!\d+!', $request->contact, $phone);
            foreach($phone[0] as $key=>$value)
            {
                if($key==0) $phone_insert.=$value;
                else $phone_insert.="-".$value;
            }

            $addlead->contact       =  $phone_insert;
        }
        $addlead->agent_id = $request->agent;
        $addlead->sex = $request->sex;
        $addlead->date = date('Y-m-d', strtotime($request->date));
        $addlead->lead_source = $request->lead_source;
        $addlead->family_name = $request->family_name;
        $addlead->name = $request->name;
        $addlead->email = $request->email;
        $addlead->address = $request->address;
        $addlead->job = $request->job;
        $addlead->workplace = $request->workplace;
        if ($addlead->save()) {
            return redirect()->route('lead-agency.index')->with('success', 'Lead has been created....');
        } else {
            return redirect()->route('lead-agency.index')->with('danger', 'Failed create lead !!!');
        }

    }

    public function show($id)
    {

        $lead = CRMLeadModel::find($id);
        $meeting = CRMTaskModel::where('lead_id', $lead->id)->where('delete_status', 0)->where('task_type', 'Meeting')->get();
        $call_log = CRMTaskModel::where('lead_id', $lead->id)->where('delete_status', 0)->where('task_type', 'Call_log')->get();
        $appointment = CRMTaskModel::where('lead_id', $lead->id)->where('delete_status', 0)->where('task_type', 'Appointment')->get();
        return view('CRMAgent.lead.show', compact('meeting', 'lead', 'call_log', 'appointment'));
    }

    public function edit($id)
    {
        $u_id = Auth::user()->id;
        $agent = User::select(DB::raw('CONCAT(user_firstname," ",user_lastname) AS name'), 'id')
            ->where(function ($q) use ($u_id) {
                if (Auth::user()->role != 'Administrator') {
                    $q->where('id', $u_id);
                    $q->orwhere('leader_id', $u_id);
                }
            })->pluck('name', 'id')->prepend('Please Select', '');
        $lead_source = CRMLeadSourceModel::pluck('source_name', 'id');

        $lead = CRMLeadModel::find($id);

        return view('CRMAgent.lead.edit', compact('agent', 'lead_source', 'lead'));
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'agent_id' => 'required',
            'date' => 'required',
            'lead_source' => 'required',
            'family_name' => 'required',
            'name' => 'required',
            'contact' => 'required|unique:nso007_crm_leads,contact,' . $id,
            'email' => 'required|unique:nso007_crm_leads,email,' . $id,
            'address' => 'required',
            'job' => 'required',
            'workplace' => 'required',
        ]);
        $addlead = CRMLeadModel::find($id);
        if(isset($request->contact)){
            $phone="";$phone_insert="";
            preg_match_all('!\d+!', $request->contact, $phone);
            foreach($phone[0] as $key=>$value)
            {
                if($key==0) $phone_insert.=$value;
                else $phone_insert.="-".$value;
            }

            $addlead->contact       =  $phone_insert;
        }
        $addlead->agent_id = $request->agent_id;
        $addlead->date = date('Y-m-d', strtotime($request->date));;
        $addlead->lead_source = $request->lead_source;
        $addlead->family_name = $request->family_name;
        $addlead->name = $request->name;
        $addlead->email = $request->email;
        $addlead->address = $request->address;
        $addlead->job = $request->job;
        $addlead->workplace = $request->workplace;
        if ($addlead->update()) {
            return redirect()->route('lead-agency.index')->with('success', 'Lead has been update....');
        } else {
            return redirect()->route('lead-agency.index')->with('danger', 'Failed update lead !!!');
        }
    }

    public function destroy($id)
    {

    }

    public function datable_lead(Request $request)
    {
        $agent_s = isset($_GET['agent_id']) ? $_GET['agent_id'] : '0';
        $date_s = $_GET['date'] ? date('Y-m-d', strtotime($_GET['date'])) : '0';
        $u_id = Auth::user()->id;

        $search = $request->input('search.value');

        $count_filter = CRMLeadModel::selectRaw('nso007_crm_leads.id')
            ->join('users', 'users.id', 'nso007_crm_leads.agent_id')
            ->where(function ($q) use ($u_id) {
                if (Auth::user()->role != 'Administrator') {
                    $q->orwhere('users.id', $u_id);
                    $q->orwhere('users.leader_id', $u_id);
                }
            })
            ->where(function ($q) use ($agent_s) {
                if ($agent_s != 0) {
                    $q->where('nso007_crm_leads.agent_id', $agent_s);
                }
            })
            ->where(function ($q) use ($date_s) {
                if ($date_s != 0) {
                    $q->where('nso007_crm_leads.date', $date_s);
                }
            })
            ->where('nso007_crm_leads.delete_status', 0)
            ->where(function ($query) use ($search) {
                $query->orWhere('nso007_crm_leads.date', 'LIKE', '%' . $search . '%');
                $query->orWhere('nso007_crm_leads.name', 'LIKE', '%' . $search . '%');
                $query->orWhere('nso007_crm_leads.family_name', 'LIKE', '%' . $search . '%');
                $query->orWhere('nso007_crm_leads.sex', 'LIKE', '%' . $search . '%');
                $query->orWhere('nso007_crm_leads.contact', 'LIKE', '%' . $search . '%');
                $query->orWhere('nso007_crm_leads.address', 'LIKE', '%' . $search . '%');
            })
            ->count();

        $count_total = CRMLeadModel::selectRaw('nso007_crm_leads.id')
            ->join('users', 'users.id', 'nso007_crm_leads.agent_id')
            ->where(function ($q) use ($u_id) {
                if (Auth::user()->role != 'Administrator') {
                    $q->orwhere('users.id', $u_id);
                    $q->orwhere('users.leader_id', $u_id);
                }
            })
            ->where('nso007_crm_leads.delete_status', 0)->count();
        $data = CRMLeadModel::selectRaw('nso007_crm_leads.id as lead_id,nso007_crm_leads.name,CONCAT(user_firstname," ",user_lastname) AS agent_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,nso007_crm_leads.convert_status')
            ->join('users', 'users.id', 'nso007_crm_leads.agent_id')
            ->where(function ($q) use ($u_id) {
                if (Auth::user()->role != 'Administrator') {
                    $q->orwhere('users.id', $u_id);
                    $q->orwhere('users.leader_id', $u_id);
                }
            })
            ->where(function ($q) use ($agent_s) {
                if ($agent_s != 0) {
                    $q->where('nso007_crm_leads.agent_id', $agent_s);
                }
            })
            ->where(function ($q) use ($date_s) {
                if ($date_s != 0) {
                    $q->where('nso007_crm_leads.date', $date_s);
                }
            })
            ->where('nso007_crm_leads.delete_status', 0)->take(20);
        if ($request->isMethod('get')) {
            return DataTables::of($data)
                ->with([
                    "recordsTotal" => $count_total,
                    "recordsFiltered" => $count_filter,
                ])
                ->editColumn('date', function ($data) {
                    return date('d-m-Y', strtotime($data->date));
                })
                ->editColumn('convert_status', function ($data) {
                    $check_language = Fun::lang();
                    if ($check_language == 'km') {
                        $close = 'បិទបញ្ចប់';
                        $fail = 'បរាជ័យ';
                        $pending = 'រង់ចាំ';
                        $success = 'ជោគជ័យ';
                    } else {
                        $close = 'Closed Deal';
                        $fail = 'Failed';
                        $pending = 'Pending';
                        $success = 'Successful';
                    }
                    return $data->convert_status == 1 ? '<span class="label label-success">' . $success . '</span>' : ($data->convert_status == 2 ? '<span class="label label-danger">' . $fail . '</span>' : '<span class="label label-warning">' . $pending . '</span>');
                })
                ->addColumn('action', function ($lead) {
                    $check_language = Fun::lang();
                    if ($check_language == 'km') {
                        $delete = 'លុប';
                        $edit = "កែសម្រួល";
                        $task = "ភារកិច្ច";
                        $show = "បង្ហាញ";
                        $act = "សកម្មភាព";
                        $con = "បិទបញ្ចប់ទៅជាអតិថិជន";
                        $con_a = "បិទបញ្ចប់ទៅជាភ្នាក់ងារ";
                    } else {
                        $delete = 'Delete';
                        $edit = "Edit";
                        $task = "Task";
                        $show = "View";
                        $act = "Action";
                        $con = "Close Deal To Client";
                        $con_a = "Close Deal To Agent";
                    }
                    $del = '';
                    $count = CRMTaskModel::where('delete_status', 0)->where('lead_id', $lead->lead_id)->get();
                    if ($lead->convert_status == 0) {
                        $del .= '<li><a href="' . route("agent-task-agency.create", $lead->lead_id) . '" title="Create"><span class="">' . $task . '</span></a> </li>';
                        if ($count->count() == 0) {
                            $del .= '<li><a class=" delete_products cursor" data-toggle="modal" data-id="' . $lead->lead_id . '" > ' . $delete . ' </a></li><li><a href="' . route("lead-agency.edit", $lead->lead_id) . '" title="Edit"><span class="">' . $edit . '</span></a></li>';
                        } else {
                            $del .= '<li><a href="' . route("lead-agency.convert-lead", $lead->lead_id) . '" title="Convert Lead"><span class="">' . $con . '</span></a></li>';
                            $del .= '<li><a href="' . route("lead-agency.convert-lead-to-agent-agency", $lead->lead_id) . '" title="Convert Lead To Agent"><span class="">' . $con_a . '</span></a></li>';
                        }
                    }
                    return '
                          <ul>
                          <li class="dropdown">
                            <a href="#" class="dropdown-toggle button_primary" data-toggle="dropdown">' . $act . ' <span class="caret"></span></a>
                            <ul class="dropdown-menu rainbow" role="menu">
                              <li><a href="' . route("lead-agency.show", $lead->lead_id) . '" title="Show"><span class="">' . $show . '</span></a></li>
                              ' . $del . '
                            </ul>
                          </li>
                          </ul>';
                })
                ->addIndexColumn()
                ->rawColumns(['action' => 'action', 'convert_status' => 'convert_status'])
                ->make(true);
        }
    }

    public function delete_lead(Request $request)
    {
        $st = CRMLeadModel::find($request->id);
        $st->delete_status = 1;
        $st->update();
    }

    public function convert_lead($lead)
    {

        $lead = CRMLeadModel::find($lead);
        $meeting = CRMTaskModel::where('lead_id', $lead->id)->where('delete_status', 0)->where('task_type', 'Meeting')->get();
        $call_log = CRMTaskModel::where('lead_id', $lead->id)->where('delete_status', 0)->where('task_type', 'Call_log')->get();
        $appointment = CRMTaskModel::where('lead_id', $lead->id)->where('delete_status', 0)->where('task_type', 'Appointment')->get();
        return view('CRMAgent.lead.convert-lead', compact('meeting', 'lead', 'call_log', 'appointment'));
    }

    public function save_customer(Request $request)
    {
        $customer = new ClientModel();
        $lead = CRMLeadModel::find($request->lead_id);
        if ($request->close_deal == 1) {
            $customer->client_fullname = $lead->family_name . ' ' . $lead->name;
            $customer->client_firstname = $lead->family_name;
            $customer->client_lastname = $lead->name;
            $customer->client_gender = $lead->sex;
            $customer->client_phone1 = $lead->contact;
            $customer->client_address = $lead->address;
            $customer->client_job = $request->job;
            $customer->client_status = 2;
            $customer->status_delete = 1;
            $customer->status = 1;
            $customer->client_workplace = $request->workplace;
            $customer->client_img = "none";
            $customer->client_pos = 0;
            $customer->client_contract = 0;
            if ($customer->save()) {
                CRMTaskModel::where('lead_id', $request->lead_id)->update(array('convert_status' => 1));
                $lead->convert_status = 1;
                $lead->close_deal_note = $request->close_deal_note;
                $lead->update();
                return redirect()->route('lead-agency.show', $request->lead_id)->with('success', 'Lead converted successfully...');
            } else {
                return redirect()->route('lead-agency.show', $request->lead_id)->with('danger', 'Lead can not convert..!');
            }
        }
        if ($request->close_deal == 2) {
            $lead = CRMLeadModel::find($request->lead_id);
            CRMTaskModel::where('lead_id', $request->lead_id)->update(array('convert_status' => 2));
            $lead->convert_status = 2;
            $lead->close_deal_note = $request->close_deal_note;
            $lead->update();
            return redirect()->route('lead-agency.show', $request->lead_id)->with('danger', 'Close Deal Failed...');
        }

    }

    public function convert_lead_to_agent($lead)
    {
        $lead = CRMLeadModel::find($lead);
        $meeting = CRMTaskModel::where('lead_id', $lead->id)->where('delete_status', 0)->where('task_type', 'Meeting')->get();
        $call_log = CRMTaskModel::where('lead_id', $lead->id)->where('delete_status', 0)->where('task_type', 'Call_log')->get();
        $appointment = CRMTaskModel::where('lead_id', $lead->id)->where('delete_status', 0)->where('task_type', 'Appointment')->get();
        return view('CRMAgent.lead.convert-lead-to-agent', compact('meeting', 'lead', 'call_log', 'appointment'));
    }

    public function save_agent(Request $request ,$Digit = 9)
    {
        if ($request->close_deal == 1) {
            $agent = new User();
            $max = User::where('user_status', 2)->max('user_code') + 1;
            $increas = $max + 0;
            (string) $increas;
            while (strlen($increas) < $Digit) {
                $increas = "0" . $increas;
            }
            $agent->parent_id = $request->agent_id;
            $agent->agency_type = 1;
            $agent->user_code = $increas;
            $agent->branch_id = 1;
            $agent->user_firstname = $request->family_name;
            $agent->user_lastname = $request->lead;
            $agent->user_gender = $request->sex;
            $agent->email = $request->email;
            $agent->user_phone = $request->contact;
            $agent->address = $request->address;
            $agent->user_status = 2;
            $agent->user_activity = 0;
            $agent->role = "Agencies";
            $agent->avatar = "default.png";
            if ($agent->save()) {
                $lead = CRMLeadModel::find($request->lead_id);
                CRMTaskModel::where('lead_id', $request->lead_id)->update(array('convert_status' => 1));
                $lead->convert_status = 1;
                $lead->close_deal_note = $request->close_deal_note;
                $lead->update();
                return redirect()->route('lead-agency.show', $request->lead_id)->with('success', 'Lead converted successfully...');
            } else {
                return redirect()->route('lead-agency.show', $request->lead_id)->with('danger', 'Lead can not convert..!');
            }
        }
        if ($request->close_deal == 2) {
            $lead = CRMLeadModel::find($request->lead_id);
            CRMTaskModel::where('lead_id', $request->lead_id)->update(array('convert_status' => 2));
            $lead->convert_status = 2;
            $lead->close_deal_note = $request->close_deal_note;
            $lead->update();
            return redirect()->route('lead-agency.show', $request->lead_id)->with('danger', 'Close Deal Failed...');
        }

    }

    public function lead_report()
    {
        $u_id = Auth::user()->id;
        $agent = User::select(DB::raw('CONCAT(user_firstname," ",user_lastname) AS name'), 'id')
            ->where(function ($q) use ($u_id) {
                if (!Auth::user()->role == 'Administrator') {
                    $q->where('id', $u_id);
                    $q->orwhere('leader_id', $u_id);
                }
            })->pluck('name', 'id');
        return view('CRMAgent.report.lead-report', compact('agent'));
    }

    public function datatable_lead_report(Request $request)
    {
        $search = $request->input('search.value');
        $agent_s = isset($_GET['agent_id']) ? $_GET['agent_id'] : '0';
        $date_s = $_GET['date'] ? date('Y-m-d', strtotime($_GET['date'])) : '0';
        $u_id = Auth::user()->id;
        $count_filter = CRMLeadModel::selectRaw('nso007_crm_leads.id')
            ->join('users', 'users.id', 'nso007_crm_leads.agent_id')
            ->where(function ($q) use ($u_id) {
                if (!Auth::user()->role == 'Administrator') {
                    $q->orwhere('users.id', $u_id);
                    $q->orwhere('users.leader_id', $u_id);
                }
            })
            ->where(function ($q) use ($agent_s) {
                if ($agent_s != 0) {
                    $q->where('nso007_crm_leads.agent_id', $agent_s);
                }
            })
            ->where(function ($q) use ($date_s) {
                if ($date_s != 0) {
                    $q->where('nso007_crm_leads.date', $date_s);
                }
            })
            ->where('nso007_crm_leads.delete_status', 0)
            ->where(function ($query) use ($search) {
                $query->orWhere('nso007_crm_leads.date', 'LIKE', '%' . $search . '%');
                $query->orWhere('nso007_crm_leads.name', 'LIKE', '%' . $search . '%');
                $query->orWhere('nso007_crm_leads.contact', 'LIKE', '%' . $search . '%');
            })
            ->count();

        $count_total = CRMLeadModel::selectRaw('nso007_crm_leads.id')
            ->join('users', 'users.id', 'nso007_crm_leads.agent_id')
            ->where(function ($q) use ($u_id) {
                if (!Auth::user()->role == 'Administrator') {
                    $q->orwhere('users.id', $u_id);
                    $q->orwhere('users.leader_id', $u_id);
                }
            })
            ->where('nso007_crm_leads.delete_status', 0)->count();
        $data = CRMLeadModel::selectRaw('nso007_crm_leads.id as lead_id,nso007_crm_leads.name,CONCAT(user_firstname," ",user_lastname) AS agent_name,
            nso007_crm_leads.family_name,nso007_crm_leads.contact,
            nso007_crm_leads.date,nso007_crm_leads.convert_status')
            ->join('users', 'users.id', 'nso007_crm_leads.agent_id')
            ->where(function ($q) use ($u_id) {
                if (!Auth::user()->role == 'Administrator') {
                    $q->where('users.id', $u_id);
                    $q->orwhere('users.leader_id', $u_id);
                }
            })
            ->where(function ($q) use ($agent_s) {
                if ($agent_s != 0) {
                    $q->where('nso007_crm_leads.agent_id', $agent_s);
                }
            })
            ->where(function ($q) use ($date_s) {
                if ($date_s != 0) {
                    $q->where('nso007_crm_leads.date', $date_s);
                }
            })
            ->where('nso007_crm_leads.delete_status', 0)->take(10);
        if ($request->isMethod('get')) {
            return DataTables::of($data)
                ->with([
                    "recordsTotal" => $count_total,
                    "recordsFiltered" => $count_filter,
                ])
                ->editColumn('date', function ($data) {
                    return date('d-m-Y', strtotime($data->date));
                })
                ->addColumn('total_call', function ($lead) {
                    $check_language = Fun::lang();
                    if ($check_language == 'km') {
                        $done = 'រួចររាល់​​​';
                    } else {
                        $done = 'Done';
                    }
                    $total_call = CRMTaskModel::where('lead_id', $lead->lead_id)->where('task_type', 'Call_log')->get()->count();
                    $done_call = CRMTaskModel::where('lead_id', $lead->lead_id)->where('task_type', 'Call_log')->where('complete_status', '1')->get()->count();
                    return $total_call . ($done_call > 0 ? ' <span class="label label-success">' . $done_call . ' ' . $done . '</span>' : '');
                })
                ->addColumn('total_appointment', function ($lead) {
                    $check_language = Fun::lang();
                    if ($check_language == 'km') {
                        $done = 'រួចររាល់​​​';
                    } else {
                        $done = 'Done';
                    }
                    $total_appointment = CRMTaskModel::where('lead_id', $lead->lead_id)->where('task_type', 'Appointment')->get()->count();
                    $done_appointment = CRMTaskModel::where('lead_id', $lead->lead_id)->where('task_type', 'Appointment')->where('complete_status', '1')->get()->count();
                    return $total_appointment . ($done_appointment > 0 ? ' <span class="label label-success">' . $done_appointment . ' ' . $done . '</span>' : '');
                })
                ->addColumn('total_meeting', function ($lead) {
                    $check_language = Fun::lang();
                    if ($check_language == 'km') {
                        $done = 'រួចររាល់​​​';
                    } else {
                        $done = 'Done';
                    }
                    $total_meeting = CRMTaskModel::where('lead_id', $lead->lead_id)->where('task_type', 'Meeting')->get()->count();
                    $done_meeting = CRMTaskModel::where('lead_id', $lead->lead_id)->where('task_type', 'Meeting')->where('complete_status', '1')->get()->count();
                    return $total_meeting . ($done_meeting > 0 ? ' <span class="label label-success">' . $done_meeting . ' ' . $done . '</span>' : '');
                })
                ->addColumn('close_deal', function ($lead) {
                    $check_language = Fun::lang();
                    if ($check_language == 'km') {
                        $close = 'បិទបញ្ចប់';
                        $fail = 'បរាជ័យ';
                        $pending = 'រង់ចាំ';
                        $success = 'ជោគជ័យ';
                    } else {
                        $close = 'Closed Deal';
                        $fail = 'Failed';
                        $pending = 'Pending';
                        $success = 'Successful';
                    }
                    return $lead->convert_status == 1 ? '<span class="label label-success">' . $success . '</span>' : ($lead->convert_status == 2 ? '<span class="label label-danger">' . $fail . '</span>' : '<span class="label label-warning">' . $pending . '</span>');
                })
                ->addIndexColumn()
                ->rawColumns(['convert_status' => 'convert_status', 'close_deal' => 'close_deal', 'total_meeting' => 'total_meeting', 'total_appointment' => 'total_appointment', 'total_call' => 'total_call'])
                ->make(true);
        }

    }

    public function view_lead_report($id)
    {
        $lead = CRMLeadModel::find($id);
        $meeting = CRMTaskModel::where('lead_id', $lead->id)->where('delete_status', 0)->where('task_type', 'Meeting')->get();
        $call_log = CRMTaskModel::where('lead_id', $lead->id)->where('delete_status', 0)->where('task_type', 'Call_log')->get();
        $appointment = CRMTaskModel::where('lead_id', $lead->id)->where('delete_status', 0)->where('task_type', 'Appointment')->get();
        return view('CRMAgent.report.show', compact('meeting', 'lead', 'call_log', 'appointment'));
    }

    public function dashboard()
    {
        return view('CRMAgent.dashboard-crm');
    }
}
