<?php

namespace App\Http\Controllers\Admin\Project;
use App\CallLogs;
use App\Comments;
use App\ConsumerApplication;
use App\ConsumerApplicationElement;
use App\ConsumerApplicationFiles;
use App\CoronaHotspot;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Controllers\Controller;
use App\ProjectLead\ProjectLeadActions;
use App\ProjectLead\ProjectLeadFiles;
use App\ProjectLead\ProjectLeadStatus;
use App\ProjectLead\ProjectLeadLogs;
use App\ProjectLead\ProjectLeadMails;
use App\ProjectLead\ProjectLeads;
use App\Merchant;
use App\MerchantCategory;
use App\MerchantFiles;
use App\Slack;
use App\StateModel;
use App\User;
use Carbon\Carbon;
use Hashids\Hashids;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;

class ProjectLeadManagement extends Controller
{

    private $leadsStatus;
    private $request;

    public function __construct(Request $request)
    {

        $this->leadsStatus = [
            ['id' => 1, 'name' => 'Not interested'],
            ['id' => 2, 'name' => 'Leads sent to Merchants'],
            ['id' => 3, 'name' => 'Call disconnected'],
            ['id' => 4, 'name' => 'Call rescheduled'],
            ['id' => 5, 'name' => 'False Lead'],
            ['id' => 6, 'name' => 'Language Barrier'],
            ['id' => 7, 'name' => 'Not doable'],
            ['id' => 8, 'name' => 'WIP'],
            ['id' => 9, 'name' => 'Re-targeting']
        ];

        $this->request = $request;
    }

    public function insertStatus()
    {
        ProjectLeadStatus::insert($this->leadsStatus);
    }

    public function index()
    {

        $data['from_date'] = $this->request->has('from_date') ? $this->request->get('from_date').' 00:00:00' : Carbon::now()->subDays(30)->toDateTimeString();
        $data['to_date'] = $this->request->has('to_date') ? $this->request->get('to_date').' 23:59:59' : Carbon::now()->endOfDay()->toDateTimeString();
        $data['f_sector_id'] = $this->request->get('f_sector_id');
        $data['f_status_id'] = $this->request->get('f_status_id');
        $data['f_state_id'] = $this->request->get('f_state_id');
        $data['f_user_id'] = $this->request->get('f_user_id');
        $data['action_date'] = $this->request->get('action_date');
        $data['search_keyword'] = $this->request->get('search_keyword');

        $data['categories'] = MerchantCategory::whereIn('id', [38,39])->get();
        $data['leadsStatus'] = ProjectLeadStatus::get();
        $data['users'] = User::where('user_type', '>', 4)->get(['id', 'name']);
        $leads = ProjectLeads::with('sector', 'user', 'currentStatus', 'leadStatus', 'logs.user', 'logs.leadStatus')->whereNull('deleted_at');

        if ($data['from_date'] && $data['to_date']) {
            $leads = $leads->where('created_at', '>=', $data['from_date'])->where('created_at', '<=', $data['to_date']);
        }
        if ($data['f_sector_id']) {
            $leads = $leads->where('sector_id', $data['f_sector_id']);
        }
        if ($data['action_date']) {
            $leads = $leads->where('action_date', $data['action_date']);
        }
        if ($data['f_user_id']) {
            $leads = $leads->where('user_id', $data['f_user_id']);
        }
        if ($data['f_status_id']) {
            $leads = $leads->where('status', $data['f_status_id']);
        }
        if ($data['f_state_id']) {
            $leads = $leads->where('state_id', $data['f_state_id']);
        }
        if ($data['search_keyword']) {
            $leads = $leads->where('firm', 'like', '%'.$data['search_keyword'].'%');
        }

        $data['leads'] = $leads->orderBy('created_at','desc')->paginate(10);

        foreach($data['leads'] as $key=>$lead) {
            $contact = json_decode($lead->contacts);
            if (isset($contact) && !empty($contact)){
                foreach ($contact as $contact_var) {
                    if (isset($contact_var->email_of_contact) && !empty($contact_var->email_of_contact)) {
                        $contact_var->email_of_contact = wall_decrypt($contact_var->email_of_contact);
                    }
                    if (isset($contact_var->phone_of_contact) && !empty($contact_var->phone_of_contact)) {
                        $contact_var->phone_of_contact = wall_decrypt($contact_var->phone_of_contact);
                    }
                }
                $data['leads'][$key]['contacts'] = json_encode($contact);
            }
        }

        $data['states'] = StateModel::get();
        $data['dashboard'] = $this->getDashboardItems($data);
        $data['users'] = User::where('user_type', '>', 4)->get();


        $data['from_date'] = $this->request->has('from_date') ? $this->request->get('from_date') : Carbon::now()->subDays(30)->toDateString();
        $data['to_date'] = $this->request->has('to_date') ? $this->request->get('to_date') : Carbon::now()->endOfDay()->toDateString();
        $data['corona_pincodes'] = CoronaHotspot::get(['pincode']);
        return view('admin.project-leads.index', $data);
    }

    public function edit($id)
    {

        $data['categories'] = MerchantCategory::whereIn('id', [38,39])->get();
        $data['leadsStatus'] = ProjectLeadStatus::get();
        $data['users'] = User::where('user_type', '>', 4)->get(['id', 'name']);
        $data['lead'] = ProjectLeads::with('leadActions', 'sector', 'user', 'currentStatus', 'leadStatus', 'logs.user', 'logs.leadStatus', 'leadMails.user')->where('id', $id)->whereNull('deleted_at')->first();

        if (isset($data['lead']->contacts) && $data['lead']->contacts) {
            $contact = json_decode($data['lead']->contacts);
            if (isset($contact) && !empty($contact)) {
                foreach ($contact as $contact_var) {
                    if (isset($contact_var->email_of_contact) && !empty($contact_var->email_of_contact)) {
                        $contact_var->email_of_contact = wall_decrypt($contact_var->email_of_contact);
                    }
                    if (isset($contact_var->phone_of_contact) && !empty($contact_var->phone_of_contact)) {
                        $contact_var->phone_of_contact = wall_decrypt($contact_var->phone_of_contact);
                    }
                }
                $data['lead']['contacts'] = json_encode($contact);
            }
        }

        $data['states'] = StateModel::get();
        $data['advisors'] = User::where('user_type','>=',5)->whereNull('deleted_at')->get(['id','name']);
        $data['comments'] = Comments::with('user')->where('application_id', $id)->where('type','pr_lead')->get();
        $data['files'] = ProjectLeadFiles::where('lead_id', $id)->get();
        $callsLogs = CallLogs::where('_id', $id)->where('id_type','pr_lead_id')->get();
        foreach ($callsLogs as $indexCall => $callData) {
            $data['files'][] = $callData;
        }
        $data['contentData'] = $this->introductionContent($data['lead']);
        return view('admin.project-leads.lead-edit', $data);
    }

    public function getDashboardItems($data)
    {
        $leads = DB::table('project_leads as leads')->leftJoin('project_lead_status as lead_status', 'lead_status.id', '=', 'leads.status');
        if ($data['from_date'] && $data['to_date']) {
            $leads = $leads->where('leads.created_at', '>=', $data['from_date'])->where('leads.created_at', '<=', $data['to_date']);
        }
        if ($data['f_sector_id']) {
            $leads = $leads->where('leads.sector_id', $data['f_sector_id']);
        }
        if ($data['action_date']) {
            $leads = $leads->where('leads.action_date', $data['action_date']);
        }
        if ($data['f_user_id']) {
            $leads = $leads->where('leads.user_id', $data['f_user_id']);
        }
        if ($data['f_status_id']) {
            $leads = $leads->where('leads.status', $data['f_status_id']);
        }
        if ($data['f_state_id']) {
            $leads = $leads->where('leads.state_id', $data['f_state_id']);
        }
        $leads = $leads->groupBy('leads.status')->select('leads.status as id', 'lead_status.status', DB::raw('COUNT(*) as leads'))->get();

        return $leads;
    }

    public function uploadDocuments($id)
    {
        if ($this->request->has('documents') && count(array_diff($this->request->get('documents'), [null]))) {
            (new ConsumerApplicationController())->uploadConsumerDocuments($this->request, $id, 'lead_type');
        }
        return redirect()->back();
    }

    public function setLeadNextAction()
    {
        $status = 'FAIL';
        $message = 'Can\'t set lead next action date, Please try again later';

        if ($this->request->get('lead_id')) {
            $leads = ProjectLeads::find($this->request->get('lead_id'));
            $leads->action_date = $this->request->get('action_date');
            $leads->save();

            if ($leads->id) {
                $leadLog = new ProjectLeadActions();
                $leadLog->lead_id = $this->request->get('lead_id');
                $leadLog->lead_status = $leads->status;
                $leadLog->user_id = $this->request->get('user_id');
                $leadLog->action_date = $this->request->get('action_date');
                $leadLog->created_at = Carbon::now()->toDateTimeString();
                $leadLog->comment = $this->request->get('comment');
                $leadLog->save();

                $status = 'OK';
                $message = 'Lead next action date changed successfully';
            }
        }
        return response()->json(['status' => $status, 'message' => $message]);
    }

    public function getContactDetails($contacts, $_contact){
        $contacts = json_decode($contacts);
        if($contacts) {
            foreach ($contacts as $contact) {
                if ($contact->name_of_contact == $_contact->name_of_contact && $contact->designation_of_contact == $_contact->designation_of_contact) {
                    $mContact = new \stdClass();
                    $mContact->email_of_contact = $contact->email_of_contact;
                    $mContact->phone_of_contact = $contact->phone_of_contact;
                    $mContact->name_of_contact = $_contact->name_of_contact;
                    $mContact->designation_of_contact = $_contact->designation_of_contact;
                    return $mContact;
                }
            }
        }
        return false;
    }

    public function saveLead()
    {

        if ($this->request->has('lead_id') && $this->request->get('lead_id')) {
            $leads = ProjectLeads::find($this->request->get('lead_id'));
        } else {
            $leads = new ProjectLeads();
        }

        $mobile_number = '';
        $name = '';
        $contacts = $leads->contacts;
        $leads->fill($this->request->input());
        $leads->created_at = Carbon::now()->toDateTimeString();
        $_contacts = array_filter(json_decode($this->request->get('contacts'), 1)) ? $this->request->get('contacts') : '';
        $_contacts = $_contacts ? json_decode($_contacts) : '';
        if($_contacts) {
            foreach ($_contacts as $index => $contact) {

                if (isset($contact->email_of_contact) && !empty($contact->email_of_contact)) {
                    $encrypted_contact = wall_encrypt($contact->email_of_contact);
                    $_contacts[$index]->email_of_contact = $encrypted_contact;
                }
                if (isset($contact->phone_of_contact) && !empty($contact->phone_of_contact)) {
                    $encrypted_contact = wall_encrypt($contact->phone_of_contact);
                    $_contacts[$index]->phone_of_contact = $encrypted_contact;
                    $mobile_number = $contact->phone_of_contact;
                    $name = isset($contact->email_of_contact) ? $contact->email_of_contact : 'User';
                }
            }
        }

        if($_contacts) {
            foreach ($_contacts as $index => $contact) {
                if ($contact) {
                    if (!isset($contact->email_of_contact)) {
                        if ($mContact = $this->getContactDetails($contacts, $contact)) {
                            $_contacts[$index] = $mContact;
                        }
                    }
                }
            }
            $leads->contacts = json_encode($_contacts);
        }
        $leads->save();

        if ($leads->id && !$this->request->get('lead_id')) {
            $leadLog = new ProjectLeadLogs();
            $leadLog->lead_id = $leads->id;
            $leadLog->lead_status = $this->request->get('status');
            $leadLog->user_id = $this->request->get('user_id');
            $leadLog->created_at = Carbon::now()->toDateTimeString();
            $leadLog->comment = $this->request->get('comment');
            $leadLog->save();

            \Session::flash('success', 'Lead successfully created');
        } else {
            \Session::flash('success', 'Lead updated successfully');
        }
        return redirect()->back();
    }

    public function changeLeadStatus()
    {

        $status = 'FAIL';
        $message = 'Can\'t change lead status, Please try again later';

        if ($this->request->get('lead_id')) {
            $leads = ProjectLeads::find($this->request->get('lead_id'));
            $leads->status = $this->request->get('status');
            if ($this->request->get('action_date')) {
                $leads->action_date = $this->request->get('action_date');
            }
            $leads->save();

            if ($leads->id) {
                $leadLog = new ProjectLeadLogs();
                $leadLog->lead_id = $this->request->get('lead_id');
                $leadLog->lead_status = $this->request->get('status');
                $leadLog->user_id = $this->request->get('user_id');
                $leadLog->created_at = Carbon::now()->toDateTimeString();
                $leadLog->comment = $this->request->get('comment');
                $leadLog->save();


                if ($this->request->get('action_date')) {
                    $leadLog = new ProjectLeadActions();
                    $leadLog->lead_id = $this->request->get('lead_id');
                    $leadLog->lead_status = $leads->status;
                    $leadLog->user_id = $this->request->get('user_id');
                    $leadLog->action_date = $this->request->get('action_date');
                    $leadLog->created_at = Carbon::now()->toDateTimeString();
                    $leadLog->comment = '';
                    $leadLog->save();
                }


                $status = 'OK';
                $message = 'Lead status changed successfully';
            }
        }
        return response()->json(['status' => $status, 'message' => $message]);
    }

    public function sendEmail()
    {
        if ($this->request->get('subject') && $this->request->get('message') && $this->request->get('lead_id')) {


            $leadMails = new ProjectLeadMails();
            $leadMails->lead_id = $this->request->get('lead_id');
            $leadMails->user_id = Auth::user()->id;
            $leadMails->subject = $this->request->get('subject');
            $leadMails->message = $this->request->get('message');
            $leadMails->save();

            $hash = new Hashids('Creditfair by CS', 20);
            $hashedID = strtoupper($hash->encode($this->request->get('lead_id')));
            $hashedID = $hashedID . $leadMails->id;

        $filePath = [];

        $auth = Auth::user();

        $leadSector = ProjectLeads::where('id', $this->request->get('lead_id'))->where('sector_id', 38)->first(['id']);
        if (isset($leadSector->id)){
            $from_email = 'education@creditfair.in';
        }else{
            $from_email = 'fertility@creditfair.in';
        }

        Mail::send('emails.reminders.basic_reminder',
            ['body' => $this->request->get('message'), 'isBD' => true, 'footer_email' =>  $auth->email, 'footer_phone_number' => $auth->mobile_number, 'footer_name' => ucfirst($auth->name)]
            , function ($message) use ($hashedID, $leadMails, $from_email) {
                $message->from($from_email);
                $message->to(explode(',',str_replace(' ','',$this->request->get('to'))))->subject($this->request->get('subject')); //.' #CF-'.$hashedID
                //$message->to('sunil@creditfair.in')->subject($this->request->get('subject').' #CF-'.$hashedID);
                if($this->request->get('cc')) {
                    $message->cc(explode(',',str_replace(' ','',$this->request->get('cc'))));
                }
                if($this->request->file('files')) {
                    $files = $this->request->allFiles();
                    foreach ($files['files'] as $file) {
                        $destinationPathInvoice = $file;
                        $as = $destinationPathInvoice->getClientOriginalName();
                        $filePath[] = $this->uploadToS3($as, $this->request->get('lead_id'), $file);
                        $path = $destinationPathInvoice->getRealPath();
                        $mime = $destinationPathInvoice->getClientMimeType();

                            $fileData = [
                                'path' => $path,
                                'mime' => [
                                    'as' => $as,
                                    'mime' => $mime
                                ]];

                            $message->attach($fileData['path'], $fileData['mime']);
                        }
                    }
                });

            $leadMailsUpdate = ProjectLeadMails::find($leadMails->id);
            $leadMailsUpdate->fill([
                'hash_id' => $hashedID,
                'attachment_url' => implode(',', $filePath),
                'created_at' => Carbon::now()->toDateTimeString(),
                'is_attachment' => $this->request->file('files') ? 1 : 0
            ]);
            $leadMailsUpdate->save();


            \Session::flash('success', 'Email sent successfully auto generated Id ' . $hashedID);
            return redirect()->back();
        } else {
            \Session::flash('error', 'Can\'t send email, Please check input parameters');
            return redirect()->back();
        }
    }

    public function uploadToS3($as, $lead_id, $file)
    {
        $s3 = Storage::disk('s3');
        $path = 'project_leads/' . $lead_id . '/' . $as;
        $s3->put($path, $file);
        return $path;
    }

    public function copyApplication($id)
    {

        $lead_data = ProjectLeads::where('id', $id)->first(['firm','sector_id','address','state_id','city','pincode','contacts','status','user_id']);
        $lead_contacts_details = json_decode($lead_data->contacts, true);
        $contact_of_person = $lead_contacts_details[0];
        $state = StateModel::where('id', $lead_data->state_id)->first();
        $lead_files = ProjectLeadFiles::where('lead_id', $id)->get();
        $lead_comments = ProjectLeadLogs::where('lead_id', $id)->whereNotNull('comment')->get();
        $_comments = Comments::where('application_id', $id)->where('type','pr_lead')->get();
        $flag = 0;
        $result = [];
        $response = [];

            if(true) {
                /*$application_id = ConsumerApplication::insertGetId([
                'purpose' => $lead_data->sector_id,
                'name' => $lead_data->firm,
                'mobile_number' => $contact_of_person['phone_of_contact'],
                'email' => $contact_of_person['email_of_contact'] ,
                'current_address_line_1' => $lead_data->address,
                'state' => 'incomplete form',
                'current_address_state' => $state->name,
                'current_address_city' =>$lead_data->city ,
                'current_address_pincode' =>$lead_data->pincode ,
                'created_at' => Carbon::now()->toDateTimeString()
            ]);*/

            $application_id = (new ConsumerApplicationController())->store(new Request([
                'purpose' => $lead_data->sector_id,
                'name' => $lead_data->firm,
                'mobile_number' => wall_decrypt($contact_of_person['phone_of_contact']),
                'email' => wall_decrypt($contact_of_person['email_of_contact']),
                'current_address_line_1' => $lead_data->address,
                'project_lead' => true,
                'current_address_state' => isset($state->name) ? $state->name : '',
                'current_address_city' =>isset($lead_data->city) ? $lead_data->city : '' ,
                'current_address_pincode' => isset($lead_data->pincode) ? $lead_data->pincode : '',
                'leadData' => ['mobile_number' => wall_decrypt($contact_of_person['phone_of_contact']), 'email' => wall_decrypt($contact_of_person['email_of_contact']), 'name' => $lead_data->firm],
                'dob'=> Carbon::createFromFormat('d/m/Y', wall_decrypt($contact_of_person['dob_of_contact']))->format('Y-m-d')
            ]));

            $hasElement = ConsumerApplicationElement::where('application_id', $application_id)->first(['id']);

            $elementData = [
                'application_id' => $application_id,
                'reference_name_1' => trim($contact_of_person['name_of_contact']),
                'reference_contact_1' => trim($contact_of_person['phone_of_contact']),
                'designation' => trim($contact_of_person['designation_of_contact']),
                'created_at' => Carbon::now()->toDateTimeString()
            ];

            if (!isset($hasElement->id)) {
                ConsumerApplicationElement::insert($elementData);
            }else{
                unset($elementData['application_id']);
                unset($elementData['created_at']);
                ConsumerApplicationElement::where('application_id', $application_id)->update($elementData);
            }

            $flag = 1;
            ProjectLeads::where('id',$id)->update(['application_id' => $application_id]);

            foreach ($lead_files as $key=>$value){

                    $result[] = [
                        'consumer_application_id' => $application_id,
                        'bank_name' => $value['bank_name'],
                        'password' => $value['password'],
                        'file_type' => $value['file_type'],
                        'file_path' => $value['file_path'],
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'created_by' => Auth::user()->id,
                        'accountUID' => $value['accountUID'],
                        'statemenfilettype' => $value['statemenfilettype'],
                        'statementtype' => $value['statementtype'],
                        'accounttype' => $value['accounttype'],
                    ];
            }

            if($result) {
                    ConsumerApplicationFiles::insert($result);
                }
            foreach($lead_comments as $key=>$value){

                $response [] = [
                    'application_id' => $application_id,
                    'user_id' => $value['user_id'],
                    'comment' => $value['comment'],
                    'type' => 'consumer',
                    'show_consumer' => 0,
                    'show_merchant' => 0,
                    'created_at' => Carbon::now()->toDateTimeString(),
                    'updated_at' => Carbon::now()->toDateTimeString()
                ];
            }

            if($_comments) {
                foreach ($_comments as $key => $_value) {

                    $response [] = [
                        'application_id' => $application_id,
                        'user_id' => $_value['user_id'],
                        'comment' => $_value['comment'],
                        'type' => 'consumer',
                        'show_consumer' => 0,
                        'show_merchant' => 0,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString()
                    ];
                }
            }

            if($response)
                Comments::insert($response);
            }

        if($flag == 1){
            \Session::flash('success', 'Application replicated successfully');
        } else {
            \Session::flash('error', 'Something went wrong, can\'t replicate application');
        }

        return redirect()->to('admin/project-leads');

    }

    public function introductionContent($lead){

        $names = [];
        if(isset($lead->contacts) && $lead->contacts){
            foreach(json_decode($lead->contacts) as $contact) {
                if (isset($contact->email_of_contact) && $contact->email_of_contact && $contact->name_of_contact) {
                    $names[] = $contact->name_of_contact;
                }
            }
        }

        $body_specific = '';
        $body_generic = '';
        $subject = '';


        switch ($lead->sector_id){
            case 4:
                $body_specific = 'Dear '.implode(', ', $names).',<br/><br/>

Thanks for connecting with us on LinkedIn! We wanted to reach out to you and your team at '.$lead->firm.' as our digital consumer lending NBFC, Credit Fair, is partnering with leading Education Institutions like Career Point, Miles Education, E-Class by Sundaram & Bansal Classes to boost their admissions over 25% by providing 0% interest EMI options to students or parents.<br/><br/>

We create value for our brand partners by<br/><br/>
<ul>
<li>Offering customised loan products from Rs 10k to Rs 10 lakhs</li>
<li>Taking over the responsibility for fee collections while you get the funds straight away</li>
<li>Doubling your lead to enrolment conversion with our higher approval rate</li>
<li>Generating new leads</li>
<li>Reducing turnaround time on decisions to 5 minutes with Auto Approvals on our Mobile App</li>
<li>Industry leading time to disbursements of less than 24 hours</li>
</ul>

These will help '.$lead->firm.' boost cash flows, increase revenues and remove financial barriers for students.<br/><br/>

About Us: Our team has processed applications worth over Rs 2,000 cr annually and won a Banking Technology Award for Best Mobile Initiative. We have extensive experience in credit, investment banking and vendor management and have graduated from London Business School, Northwestern University (USA), SAIC (USA) besides attaining the CFA charter.<br/><br/>

We would request your time as per your convenience to help take this further.<br/><br/>

Look forward to speaking with you!<br/><br/>';


                $body_generic = 'Hello,<br/><br/>

We wanted to reach out to you and your team at '.$lead->firm.' as our digital consumer lending NBFC, Credit Fair, is partnering with leading Institutions like Career Point, Miles Education, Arihant Academy & Bansal Learning to boost their admission  up to 25% by providing 0% interest EMI options to their students.<br/><br/>

We create value for our brand partners by<br/><br/>
<ul>
<li>Offering customised loan products from Rs 10k to Rs 10 lakhs</li>
<li>Taking over the responsibility for fee collections while you get the funds straight away</li>
<li>Doubling your lead to enrolment conversion with our higher approval rate</li>
<li>Generating new leads</li>
<li>Reducing turnaround time on decisions to 5 minutes with Auto Approvals on our Mobile App</li>
<li>Industry leading time to disbursements of less than 24 hour</li>
</ul>

These will help to increase '.$lead->firm.' revenues and remove financial barriers for students.<br/><br/>

<i>AboutUs:</i> Our team has processed applications worth over Rs 2,000 cr annually and won a Banking Technology Award for Best Mobile Initiative. We have extensive experience in credit, investment banking and vendor management and have graduated from London Business School, Northwestern University (USA), SAIC (USA) besides attaining the CFA charter. We would request your time as per your convenience to help take this further.<br/><br/>

Look forward to speaking with you!<br/><br/>';

                $subject = '0% EMI Options for '.$lead->firm.'’s Students';
                break;

            case 25:
            case 20:
            case 21:
            case 16:

                $body_specific = 'Dear '.implode(', ', $names).',<br/><br/>

Thanks for connecting with us on LinkedIn! We wanted to reach out to you and your team at '.$lead->firm.' as our digital consumer lending NBFC, Credit Fair, is partnering with leading healthcare institutions such as Indira IVF, Partha Dental & VLCC Healthcare to boost their occupancy up to 25% by providing 0% interest EMI options to their patients.<br/><br/>

We create value for our brand partners by<br/><br/>
<ul>
<li>Offering customised loan products from Rs 10k to Rs 10 lakhs</li>
<li>Taking over the responsibility for fee collections while you get the funds straight away</li>
<li>Doubling your lead to enrolment conversion with our higher approval rate</li>
<li>Generating new leads</li>
<li>Reducing turnaround time on decisions to 5 minutes with Auto Approvals on our Mobile App</li>
<li>Industry leading time to disbursements of less than 24 hours</li>
</ul>

These will help '.$lead->firm.' increase revenues and remove financial barriers for patients.<br/><br/>

About Us: Our team has processed applications worth over Rs 2,000 cr annually and won a Banking Technology Award for Best Mobile Initiative. We have extensive experience in credit, investment banking and vendor management and have graduated from London Business School, Northwestern University (USA), SAIC (USA) besides attaining the CFA charter.<br/><br/>

We would request your time as per your convenience to help take this further.<br/><br/>

Look forward to speaking with you!<br/><br/>';


                $body_generic = 'Hello,<br/><br/>
    
    I wanted to reach out to you and your team at '.$lead->firm.', as our digital consumer lending NBFC, Credit Fair, is partnering with leading healthcare institutions such as Indira IVF, Partha Dental & VLCC Healthcare to boost their occupancy up to 25% by providing 0% interest EMI options to their patients.<br/><br/>
    
    We create value for our brand partners by<br/><br/>
    <ul>
    <li>Offering customised loan products from Rs 10k to Rs 10 lakhs</li>
    <li>Taking over the responsibility for fee collections while you get the funds straight away</li>
    <li>Doubling your lead to enrolment conversion with our higher approval rate</li>
    <li>Generating new leads</li>
    <li>Reducing turnaround time on decisions to 5 minutes with Auto Approvals on our Mobile App</li>
    <li>Industry leading time to disbursements of less than 24 hours</li>
    </ul>
    These will help '.$lead->firm.' increase revenue and remove financial barriers for patients.<br/><br/>
    
    About Us: Our team has processed applications worth over Rs 2,000 crore annually and won a Banking Technology Award for Best Mobile Initiative. We have extensive experience in credit, investment banking and vendor management and have graduated from London Business School, Northwestern University (USA), SAIC (USA) besides attaining the CFA charter.<br/><br/>
    
    We would request your time as per your convenience to help take this further.<br/><br/>
    
    Look forward to speaking with you!<br/><br/>';


                $subject = '0% EMI Options for'.$lead->firm.'’s Patients';
                break;
            case 23:
            case 14:

                $body_specific = 'Dear '.implode(', ', $names).',<br/><br/>

Thanks for connecting with us on LinkedIn! I would like to reach out to you and your team at '.$lead->firm.' as our digital consumer lending company, Credit Fair, is partnering with leading home decor brands such as Saviesa Homes, Design Cafe, Arrivae and Sleek by Asian Paints to boost their sales up to 45% by providing 0% interest EMI options to their customers.<br/><br/>

We create value for our brand partners by<br/><br/>
<ul>
<li>Offering customised loan products from Rs 10k to Rs 20 lakhs</li>
<li>Taking over the responsibility for fee collections while you get the funds straight away</li>
<li>Doubling your lead to enrolment conversion with our higher approval rate</li>
<li>Generating new leads</li>
<li>Reducing turnaround time on decisions to 5 minutes with Auto Approvals on our Mobile App</li>
<li>Industry leading time to disbursements of less than 24 hours</li>
</ul>
These will help '.$lead->firm.' grab market share, increase customer satisfaction and revenues.<br/><br/>

About Us: Our team has processed applications worth over Rs 2,000 cr annually and won a Banking Technology Award for Best Mobile Initiative. We have extensive experience in credit, investment banking and vendor management and have graduated from London Business School, Northwestern University (USA), SAIC (USA) besides attaining the CFA charter.<br/><br/>

We would request your time as per your convenience to help take this further.<br/><br/>

Look forward to speaking with you!<br/><br/>';

                $body_generic = 'Hello,<br/><br/>

I would like to reach out to you and your team at '.$lead->firm.' as our digital consumer lending company, Credit Fair, is partnering with leading home decor brands such as Saviesa Homes, Design Cafe, Arrivae and Sleek by Asian Paints to boost their sales up to 45% by providing 0% interest EMI options to their customers.<br/><br/>


We create value for our brand partners by<br/><br/>
<ul>
<li>Offering customised loan products from Rs 10k to Rs 20 lakhs</li>
<li>Taking over the responsibility for fee collections while you get the funds straight away</li>
<li>Doubling your lead to enrolment conversion with our higher approval rate</li>
<li>Generating new leads</li>
<li>Reducing turnaround time on decisions to 5 minutes with Auto Approvals on our Mobile App</li>
<li>Industry leading time to disbursements of less than 24 hours</li>
</ul>
These will help '.$lead->firm.' grab market share, increase customer satisfaction and revenues.<br/><br/>

About Us: Our team has processed applications worth over Rs 2,000 crore annually and won a Banking Technology Award for Best Mobile Initiative. We have extensive experience in credit, investment banking and vendor management and have graduated from London Business School, Northwestern University (USA), SAIC (USA) besides attaining the CFA charter.<br/><br/>

We would request your time as per your convenience to help take this further.<br/><br/>

Look forward to speaking with you!<br/><br/>';
                $subject = '0% EMI Options for '.$lead->firm.'s Customers';
                break;
            case 7:

                $body_specific = 'Dear '.implode(', ', $names).',<br/><br/>
    
    Thanks for connecting with us on LinkedIn! We wanted to reach out to you and your team at '.$lead->firm.' as our digital consumer lending NBFC, Credit Fair, is partnering with leading Electronic Vehicle manufacturers like Tunwal E Bike, Techo Electra & Ampere E Vehicle to boost their sales up to 40% by providing Easy EMI options to their customers.<br/><br/>
    
    We create value for our brand partners by<br/><br/>
    <ul>
    <li>Offering customised loan products from Rs 10k to Rs 10 lakhs</li>
    <li>Taking over the responsibility for fee collections while you get the funds straight away</li>
    <li>Doubling your lead to enrolment conversion with our higher approval rate</li>
    <li>Generating new leads</li>
    <li>Reducing turnaround time on decisions to 5 minutes with Auto Approvals on our Mobile App</li>
    <li>Industry leading time to disbursements of less than 24 hours</li>
    </ul>
    These will help '.$lead->firm.' increase revenues and remove financial barriers for customers.<br/><br/>
    
    About Us: Our team has processed applications worth over Rs 2,000 cr annually and won a Banking Technology Award for Best Mobile Initiative. We have extensive experience in credit, investment banking and vendor management and have graduated from London Business School, Northwestern University (USA), SAIC (USA) besides attaining the CFA charter.<br/><br/>
    
    We would request your time as per your convenience to help take this further.<br/><br/>
    
    Look forward to speaking with you!<br/><br/>';


                $body_generic = 'Hello,<br/><br/>
    
    We wanted to reach out to you and your team at '.$lead->firm.' as our digital consumer lending NBFC, Credit Fair, is partnering with leading Electronic Vehicle manufacturers like Tunwal E Bike, Techo Electra & Ampere E Vehicle to boost their sales up to 40% by providing Easy EMI options to their customers.<br/><br/>
    
    We create value for our brand partners by<br/><br/>
    <ul>
    <li>Offering customised loan products from Rs 10k to Rs 10 lakhs</li>
    <li>Taking over the responsibility for fee collections while you get the funds straight away</li>
    <li>Doubling your lead to enrolment conversion with our higher approval rate</li>
    <li>Generating new leads</li>
    <li>Reducing turnaround time on decisions to 5 minutes with Auto Approvals on our Mobile App</li>
    <li>Industry leading time to disbursements of less than 24 hours</li>
    </ul>
    These will help '.$lead->firm.' increase revenues and remove financial barriers for customers.<br/><br/>
    
    About Us: Our team has processed applications worth over Rs 2,000 cr annually and won a Banking Technology Award for Best Mobile Initiative. We have extensive experience in credit, investment banking and vendor management and have graduated from London Business School, Northwestern University (USA), SAIC (USA) besides attaining the CFA charter.<br/><br/>
    
    We would request your time as per your convenience to help take this further.<br/><br/>
    
    Look forward to speaking with you!<br/><br/>';


                $subject = 'Easy EMI Plans for '.$lead->firm.'’s Customers';
                break;
        }

        return ['body_specific' => $body_specific, 'body_generic' => $body_generic, 'subject' => $subject];
    }

    public function getDuplicateLeads(){
        $applications = ConsumerApplication::where('name','like',$this->request->get('firm_name'))->get(['id','name']);

        $response = '<table class="table"><tr><th>ID</th><th>Name</th><th>View</th></tr>';
        foreach ($applications as $application){
            $response .= '<tr><td>'.$application->id.'</td><td>'.$application->name.'</td><td><a class="btn btn-primary" style="text-decoration: none;" target="_blank" href="/admin/consumer-applications/edit/'.$application->id.'">View</a></td></tr>';
        }
        $response .= '</table>';
        return response()->json(['status' => 'OK', 'leads' => $response]);
    }

    public function deleteLead(){
        $lead = ProjectLeads::where('id', $this->request->get('lead_id'))->first();
        $user = User::find($this->request->get('user_id'));
        ProjectLeads::where('id', $this->request->get('lead_id'))->update(['deleted_by' => $this->request->get('user_id')]);
        ProjectLeads::where('id', $this->request->get('lead_id'))->delete();

        (new Slack(new Request(['title'=>'Lead Deleted','fields'=>['Firm' => $lead->firm, 'Deleted By' => $user->name, 'Source' => $lead->source],'group' => 'businessdevelopment'])))->send();

        return response()->json(['status' => 'OK', 'message' => 'Lead deleted']);
    }
}
