<?php
/**
 * Created by PhpStorm.
 * User: sunil
 * Date: 9/29/18
 * Time: 4:30 PM
 */

namespace App\Console\Commands;


use App\BNPL;
use App\Capri;
use App\ConsumerApplication;
use App\ConsumerApplicationFiles;
use App\Devices;
use App\DigitalSignDetails;
use App\Events\V1\EventLendboxRepayments;
use App\Events\V1\EventLendboxTransactionStatus;
use App\Exports\ExporterMultipleSheet;
use App\FCMNotification;
use App\Http\Controllers\Admin\AccountingController;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Controllers\Admin\LendboxController;
use App\Http\Controllers\FrontController;
use App\Http\Controllers\MerchantApiController;
use App\Merchant;
use App\PrincipalOutstanding;
use App\Reminders;
use App\Services;
use App\Shortio;
use App\Singularity\Singularity;
use App\Slack;
use App\StatusLogs;
use App\Tally\TallyJobs;
use App\Templates;
use App\User;
use App\Vivriti;
use Carbon\Carbon;
use App\Console\Commands\SendMerchantMIS;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Maatwebsite\Excel\Facades\Excel;

class BasicReminders extends Command
{

    protected $signature = 'basic:reminder';
    private $type = false;

    public function __construct(){
        parent::__construct();
    }

    public function handle(){
        $this->getReminder();
        if($this->type){
            $this->sendReminder();
        }
    }

    public function sendReminder(){
        switch ($this->type){
            case 'send_daily_mis':
                $mis = new SendMerchantMIS();
                $mis->handle();
                break;
            case 'rewards':
//                $this->sendRewardsReminder();
                break;
            case 'weekly_update_merchant':
                $this->checkMerchantWeeklyData();
                break;
            case 'auto_abort_approved':
                $this->autoAbortApprovedCases();
                break;
            case 'lendbox_repayments':
                $this->lendboxRepayments();
                break;
            case 'lendbox_transactions_status':
                $this->lendboxTransactionStatus();
                break;
            default:
                break;
        }
    }

    public function getReminder(){
        $date = Carbon::now();
        $hour = date('H',time());
        $first_day_of_the_current_month = Carbon::today()->startOfMonth()->toDateString();
        $today = Carbon::now()->toDateString();
        if($hour == 12)
        {
            /*if ($date->isMonday() || $date->isWednesday() || $date->isFriday() || $date->isSunday()) {
                $this->type = 'rewards';
            }else if ($date->isSaturday()){
                $this->type = 'weekly_update_merchant';
            } else {
                return true;
            }*/
            if($first_day_of_the_current_month == $today){
//                $this->sendAccountStatement();
            }
            if ($date->isLastOfMonth()){
                $this->sendMerchantTarget();
//                $this->sendAccountStatement();
            }
        }
        elseif($hour == 11){
            $this->type = 'auto_abort_approved';
        }
        elseif($hour == 20){
            $this->sendBirthdayReminder();
            $this->tallyEntriesAlert();
        }elseif($hour == 8 || $hour == 15){
            $this->type = 'send_daily_mis';
        }

        if($date->isSunday() && $hour == 11){
            $this->savePrincipalOutstanding();
        }

        if($hour == 22){
            $this->type = 'lendbox_repayments';
        }

        if($hour == 21){
            $this->type = 'lendbox_transactions_status';
        }

        return true;
    }

    public function autoAbortApprovedCases(){
        $data =  DB::select('select consumer_application.tenure as tenure,consumer_application.approved_amount as approved_amount,consumer_application.loan_amount as loan_amount,consumer_application.id,consumer_application.state as status,consumer_application.name as customer_name,consumer_application.co_applicant_name,consumer_application.co_applicant_mobile_number,consumer_application.co_applicant_email,consumer_application.mobile_number,consumer_application.email as customer_email,merchant.merchant_name,merchant.anchor_merchant_id,merchant.email as merchant_email,merchant.contact_number,users.id as advisore_id,users.name as advisore_name,users.email as advisore_email,merchant_location.name as merchant_center,merchant_location.email as merchant_center_email,merchant_location.phone as merchant_center_phone, @approved_date := (select status_logs.created_at from status_logs where status_logs.application_id = consumer_application.id and status_logs.status = "approved" order by status_logs.created_at desc limit 1) as approved_date, DATEDIFF((CURRENT_TIMESTAMP()),@approved_date) as approved_days from consumer_application left JOIN merchant on merchant.id = consumer_application.merchant_id LEFT JOIN consumer_application_element on consumer_application_element.application_id = consumer_application.id left JOIN merchant_location on consumer_application_element.center_id = merchant_location.id left JOIN users on users.id = consumer_application.created_by where consumer_application.state = "approved" and consumer_application.is_deleted is null and merchant.is_auto_abort_approved = 1');

        $advisor = array();
        foreach ($data as $customer){

            if ($customer->approved_amount < 50000){
                $days = 2;
                $days_abort = 3;
            }else if ($customer->approved_amount >= 50000 && $customer->approved_amount <= 75000){
                $days = 3;
                $days_abort = 4;
            }else{
                $days = 5;
                $days_abort = 8;
            }
            if($customer->approved_days >= $days_abort && $customer->status != 'aborted'){

                ConsumerApplication::where('id', $customer->id)
                    ->update(['state' => 'aborted']);

                StatusLogs::insert([
                    'application_id' => $customer->id,
                    'user_id' => 107,
                    'status' => 'aborted',
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);

                (new ConsumerApplicationController())->saveAutoAbortComment($customer->id);

                $customerData = array();
                $customerData['subject'] = "We are canceling your EMI application since we haven’t received all the documents duly post approval.";
                $customerData['merchant_name'] = $customer->merchant_name;
                $customerData['applicant_name'] = $customer->customer_name;
                $customerData['to'] = isset($customer->customer_email) ? wall_decrypt($customer->customer_email) : '';

                $cc_emails = array();
                if(isset($customer->co_applicant_email) && $customer->co_applicant_email != "" && $customer->co_applicant_email != null) {
                    $cc_emails[] = wall_decrypt($customer->co_applicant_email);
                }
                if ($customerData['to']) {
                    Mail::send('emails.reminders.customer_for_aborted_approved', [
                        'data' => $customerData,
                    ], function ($message) use ($customerData, $cc_emails) {
                        $message->bcc(_env('BACKUP_EMAIL'));
                        $message->to($customerData['to'])->subject($customerData['subject']);
                        array_push($cc_emails, 'centralops@creditfair.in');
                        $cc_emails = array_unique($cc_emails);
                        if($cc_emails) {
                            $message->cc($cc_emails);
                        }
                    });
                }

                $customer_message = "Dear ". $customer->customer_name.",<br/>We wanted to update you on the status of your loan application. The loan application has been cancelled since we haven't received the required documents post approval. Please contact the us if there has been an error. <br/>Best Regards,<br/>Team Credit Fair";
                $customer_message = str_replace('<br/>', "\n", $customer_message);
                $customer_message = str_replace('<br>', "\n", $customer_message);

                if (isset($customer->mobile_number) && !empty($customer->mobile_number)) {
                    $mobile = '91' . wall_decrypt($customer->mobile_number);
                    if(isset($customer->co_applicant_mobile_number) && !empty($customer->co_applicant_mobile_number)){
                        $mobile.= $mobile.",91".wall_decrypt($customer->co_applicant_mobile_number);
                    }
                    //send_sms($mobile, ['message'=>$customer_message,'id'=>$customer->id,'id_type'=>'application_id']);
                }

                $merchantData = array();
                $merchantData['subject'] = "We are canceling ". $customer->customer_name."s application since we haven’t received all the documents duly post approval.";
                $merchantData['merchant_name'] = $customer->merchant_name;
                $merchantData['applicant_name'] = $customer->customer_name;
                $merchantData['to'] = isset($customer->merchant_email) ? explode(',', $customer->merchant_email) : '';
                if($merchantData['to']){
                    $emailData = [];
                    foreach ($merchantData['to'] as $merchantDataEmail) {
                        $emailData[] = wall_decrypt($merchantDataEmail);
                    }

                    $merchantData['to'] = $emailData;
                }

                $cc_emails = array();
                if(isset($customer->merchant_center_email) && $customer->merchant_center_email != "" && $customer->merchant_center_email != null) {
                    $cc_emails[] = wall_decrypt($customer->merchant_center_email);
                }
                if ($merchantData['to']) {
                    Mail::send('emails.reminders.merchant_for_aborted_approved', [
                        'data' => $merchantData,
                    ], function ($message) use ($merchantData, $cc_emails) {
                        $message->bcc(_env('BACKUP_EMAIL'));
                        $message->to($merchantData['to'])->subject($merchantData['subject']);
                        array_push($cc_emails, _env('NOTIFY_EMAIL', ''));
                        $cc_emails = array_unique($cc_emails);
                        if($cc_emails) {
                            $message->cc($cc_emails);
                        }
                    });
                }


                $merchant_message = "Dear ". $customer->merchant_name.",<br>We wanted to update you on the status of ". $customer->customer_name."'s loan application. The loan application has been cancelled since we haven’t received the required documents post approval. Please contact the customer and us if there has been an error.<br/>Best Regards,<br/>Team Credit Fair";
                $merchant_message = str_replace('<br/>', "\n", $merchant_message);
                $merchant_message = str_replace('<br>', "\n", $merchant_message);
                $merchantmobilesend = "";

                if($customer->contact_number != "" && $customer->contact_number != null){
                    $merchantmobiles = explode(",",$customer->contact_number);
                    foreach ($merchantmobiles as $merchantmobile){
                        if($merchantmobilesend == ""){
                            $merchantmobilesend = "91".$merchantmobile;
                        }else {
                            $merchantmobilesend = $merchantmobilesend.",91".$merchantmobile;
                        }
                    }
                }

                    if($customer->merchant_center_phone != "" && $customer->merchant_center_phone != null){
                        $centermobiles = explode(",",$customer->merchant_center_phone);
                        foreach ($centermobiles as $centermobile){
                            if($merchantmobilesend == ""){
                                $merchantmobilesend = "91".$centermobile;
                            }else {
                                $merchantmobilesend = $merchantmobilesend.",91".$centermobile;
                            }
                        }
                    }

                    if($merchantmobilesend != ""){
                        send_sms($merchantmobilesend, ['message'=>$merchant_message,'id'=>$customer->id,'id_type'=>'application_id']);
                    }
            }elseif($customer->approved_days == $days){
                $approved_date=date_create($customer->approved_date);
                date_add($approved_date,date_interval_create_from_date_string($days_abort." days"));
                $abort_date = date_format($approved_date,"Y-m-d");

                $customerData = array();
                $customerData['subject'] = "Last reminder - Following Documents pending since ".$days." days for your loan application to purchase from ". $customer->merchant_name.":";
                $customerData['merchant_name'] = $customer->merchant_name;
                $customerData['applicant_name'] = $customer->customer_name;
                $customerData['to'] = isset($customer->customer_email) ? wall_decrypt($customer->customer_email) : '';

                $documents = ConsumerApplicationFiles::where('consumer_application_id',$customer->id)->get();
                $doc_array = ['E-signed Loan Agreement','Utility Bill','Signed Nach forms','Security cheque','Self Attested'];
                $doc_key = ['loan_agreement_esign','agreement','electricity_bill','gas_bill','nach','security_cheques','self_attested'];
                foreach ($documents as $consumer_documents){
                    if(in_array($consumer_documents->file_type,$doc_key)){
                        if($consumer_documents->file_type == 'loan_agreement_esign' || $consumer_documents->file_type == 'agreement'){
                            unset($doc_array[0]);
                        }
                        if($consumer_documents->file_type == 'electricity_bill' || $consumer_documents->file_type == 'gas_bill'){
                            unset($doc_array[1]);
                        }
                        if($consumer_documents->file_type == 'nach'){
                            unset($doc_array[2]);
                        }
                        if($consumer_documents->file_type == 'security_cheques'){
                            unset($doc_array[3]);
                        }
                        if($consumer_documents->file_type == 'self_attested'){
                            unset($doc_array[4]);
                        }
                    }
                }
                $customerData['docs'] = $doc_array;
                $cc_emails = array();
                if(isset($customer->co_applicant_email) && $customer->co_applicant_email != "" && $customer->co_applicant_email != null) {
                    $cc_emails[] = wall_decrypt($customer->co_applicant_email);
                }

                if ($customerData['to']) {
                    Mail::send('emails.reminders.customer_for_aborted_approved_reminder', [
                        'data' => $customerData,
                    ], function ($message) use ($customerData, $cc_emails) {
                        $message->to($customerData['to'])->subject($customerData['subject']);
                        array_push($cc_emails, _env('NOTIFY_EMAIL', ''));
                        $cc_emails = array_unique($cc_emails);
                        if($cc_emails) {
                            $message->cc($cc_emails);
                        }
                    });
                }
                $isCarepayAnchor = isset($customer->anchor_merchant_id) && $customer->anchor_merchant_id == 7865 ? 1 : 0;
                $consumer_app_link = 'https://lnk.creditfair.in/Wgmx';//\Bitly::getUrl('https://play.google.com/store/apps/details?id=com.consumer.creditfair&hl=en_US');
//                $customer_message = "Dear ". $customer->customer_name.",<br/>Kindly note that the your approved loan application will expire on ". $abort_date.", upon not receiving the required documents. A complete loan application can improve your credit score. Therefore, we would advise you to send in the documents at the earliest. Let us know if you have any questions. <br/>Best Regards,<br/> Team Credit Fair";
                if($customer->merchant_name == "CarePay" || $isCarepayAnchor == 1){
                    $customer_message = "URGENT! <br/>". $customer->customer_name."Your loan application will expire on ". $abort_date.". Submit documents now to get quick disbursal.<br/> Regards Credit Fair";
                    $customer_message = str_replace('<br/>', "\n", $customer_message);
                    $customer_message = str_replace('<br>', "\n", $customer_message);
                    $entity = ['templateid' => '1307169752840247653', 'entityid' => Templates::$entityid];
                } else {
                    $customer_message = "URGENT! ".$customer->customer_name.", Your loan application will expire on ".$abort_date.". Submit documents now to get quick disbursal. Please download our app to check what are the pending requirements. ".$consumer_app_link." Credit Fair";
                    $customer_message = str_replace('<br/>', "\n", $customer_message);
                    $customer_message = str_replace('<br>', "\n", $customer_message);
                    $entity = ['templateid' => '1307173271578732842', 'entityid' => Templates::$entityid];
                }
                if (isset($customer->mobile_number) && !empty($customer->mobile_number)) {
                    $mobile = '91' . wall_decrypt($customer->mobile_number);
                    if(isset($customer->co_applicant_mobile_number) && !empty($customer->co_applicant_mobile_number)){
                        $mobile = $mobile.",91".wall_decrypt($customer->co_applicant_mobile_number);
                    }
                    $templateId = Templates::$application_expire_c1;

                    if($customer->merchant_name == "CarePay" || $isCarepayAnchor == 1){
                        $templateId = Templates::$loan_application_expire_v2_new;
                    }
                    $args = [$customer->customer_name, $abort_date];
                    send_sms($mobile, ['message'=>$customer_message,'id'=>$customer->id,'id_type'=>'application_id','templateId' => $templateId, 'args' => $args, 'templateDetails' => $entity]);
                }
                $merchantData = array();
                $merchantData['subject'] = "Last reminder - Following Documents pending since ".$days." days for ". $customer->customer_name."s loan application";
                $merchantData['merchant_name'] = $customer->merchant_name;
                $merchantData['applicant_name'] = $customer->customer_name;
                $merchantData['to'] = isset($customer->merchant_email) ? explode(',', wall_decrypt($customer->merchant_email)) : '';
                $merchantData['docs'] = $doc_array;
                $cc_emails = array();
                if(isset($customer->merchant_center_email)) {
                    $cc_emails = explode(',',wall_decrypt($customer->merchant_center_email));
                }
                if ($merchantData['to']) {
                    \Mail::send('emails.reminders.merchant_for_aborted_approved_reminder', [
                        'data' => $merchantData,
                    ], function ($message) use ($merchantData, $cc_emails) {
                        $message->to($merchantData['to'])->subject($merchantData['subject']);
                        array_push($cc_emails, _env('NOTIFY_EMAIL', ''));
                        $cc_emails = array_unique($cc_emails);
                        if($cc_emails) {
                            $message->cc($cc_emails);
                        }
                    });
                }

//                $merchant_message = "Dear ". $customer->merchant_name.",<br/>Kindly note that the ". $customer->customer_name."'s approved loan application will expire on ". $abort_date.", upon not receiving the required documents. Please follow up on the same to proceed with the disbursement.<br/>Best Regards,<br/>Team Credit Fair";
                $merchant_message = "Dear ". $customer->merchant_name.",
                                    <br/>Kindly note that the approved loan request of ". $customer->customer_name." will be aborted upon not receiving the required documents. Kindly follow up on the same to proceed with disbursal.";
                $entity = ['templateid' => '1307159973401302282', 'entityid' => Templates::$entityid];
                $merchant_message = str_replace('<br/>', "\n", $merchant_message);
                $merchant_message = str_replace('<br>', "\n", $merchant_message);

                $templateId = Templates::$aborted_c2;
                $args = [$customer->merchant_name,$customer->customer_name];

                $merchantmobilesend = "";

                if($customer->contact_number != "" && $customer->contact_number != null){
                    $merchantmobiles = explode(",",$customer->contact_number);
                    foreach ($merchantmobiles as $merchantmobile){
                        if($merchantmobilesend == ""){
                            $merchantmobilesend = "91".$merchantmobile;
                        }else {
                            $merchantmobilesend = $merchantmobilesend.",91".$merchantmobile;
                        }
                    }
                }

                if($customer->merchant_center_phone != "" && $customer->merchant_center_phone != null){
                    $centermobiles = explode(",",$customer->merchant_center_phone);
                    foreach ($centermobiles as $centermobile){
                        if($merchantmobilesend == ""){
                            $merchantmobilesend = "91".$centermobile;
                        }else {
                            $merchantmobilesend = $merchantmobilesend.",91".$centermobile;
                        }
                    }
                }

                if($merchantmobilesend != ""){
                    send_sms($merchantmobilesend, ['message'=>$merchant_message,'id'=>$customer->id,'id_type'=>'application_id', 'templateId' => $templateId, 'args' => $args, 'templateDetails' => $entity]);
                }


                $advisor[$customer->advisore_id][$customer->merchant_name][] = [
                    'id' => $customer->id,
                    'customer_name' => $customer->customer_name,
                    'loan_amount' => $customer->loan_amount,
                    'phone' => wall_decrypt($customer->mobile_number),
                    'status' => $customer->status,
                    'approved_amount'=>$customer->approved_amount,
                    'email' => $customer->customer_email,
                    'tenure' => $customer->tenure
                ];

            }
        }

        if($advisor){
            foreach ($advisor as $advisore_id=>$item) {
                $applicationData[] = [
                    'adviser' => User::where('id', $advisore_id)->first(['name', 'email', 'mobile_number', 'user_type']),
                    'applications' => $item,
                    'flag' => count($item) > 0 ? true : false
                ];
            }

            foreach ($applicationData as $dataItem){
                $this->sendMail1($dataItem);
            }
        }
    }

    public function sendMail1($data){
        if($data['adviser']->user_type > 4) {
            Mail::send('emails.reminders.adviser_application_reminder',
                ['data' => $data['applications']]
                , function ($message) use ($data) {
                    $message->to($data['adviser']->email);
                    $message->cc('rohit@creditfair.in')->subject('Your Approved cases pending for documents');
                });
        }
    }

    public function sendAccountStatement($event = null){
        $start_time = time();
        $serviceCount = 0;
        $applications = ConsumerApplication::whereHas('emi',function($query){
            return $query->where('emi_date','<=',Carbon::now()->toDateString());
        })->whereIn('state',['disbursed', 'nach registered'])->whereNotIn('lender_id', [Singularity::$lender_id, Capri::$lender_id, Vivriti::$lender_id])->groupBy('id')->get(['id','email','name','merchant_id']);
        $frontController = new FrontController();

        $month = date('m');
        $year = date('Y');

        $month = $month - 1;

        foreach ($applications as $application) {
            try {
                if ($event) {
                    $event->comment('sending statement ' . $application->id);
                }
                $statement = $frontController->getStatement($application->id, true);

                if ($event)
                    $event->comment('sending statement ' . $application->id);

                if ($statement && (!(BNPL::is($application->merchant_id)) && !in_array($application->merchant_id,[6418,6517,6598,6865,6600]))) {

                    $body = "Dear $application->name,<br/>

Please find your statement for the month of $month - $year.";

                    $mailData = ['email' => $application->email, 'pdf' => $statement, 'fileName' => "Account_Statement_$month-$year.pdf", 'body' => $body];

                    Mail::send('emails.reminders.basic_reminder', [
                        'body' => $body,
                    ], function ($message) use ($mailData) {
                        $message->to($mailData['email'])->subject('Account Statement');
                        $message->attachData($mailData['pdf']->output(), $mailData['fileName']);
                    });

                    $serviceCount++;
                }
            }catch (\Exception $e){

            }
        }

        (new Services())->log('monthly_account_statement', ['status' => true, 'service_count' => $serviceCount, 'start_time' => $start_time]);
    }

    public function checkMerchantWeeklyData(){
        $serviceCount = 0;
        $start_time = time();
        /*$applications = ConsumerApplication::whereHas('logs', function($query){
            $query->where('status','approved')->where('created_at','>=',Carbon::now()->startOfWeek()->toDateTimeString())
                ->where('created_at','<=',Carbon::now()->endOfWeek()->toDateTimeString());
        })->with('merchant')->where('state','approved')->whereNotIn('state',['aborted','rejected','cancelled'])->get();*/

        $applications = ConsumerApplication::with('merchant')->whereNull('is_deleted')->where('state','approved')->get();

        $response = [];
        $merchantData = [];
        foreach ($applications as $application){
            if ($application->merchant) {
                $statusLogs = StatusLogs::where('application_id', $application->id)->where('status', 'approved')->orderBy('created_at', 'desc')->first(['created_at']);
                if (isset($statusLogs->created_at)) {
                    $response[$application->merchant_id][] = ['id' => $application->id, 'customer' => $application->name, 'phone' => $application->mobile_number, 'approved_amount' => $application->approved_amount, 'approved_at' => $statusLogs->created_at];
                    $merchantData[$application->merchant_id] = ['id' =>$application->merchant_id ,'name' => $application->merchant->merchant_name, 'email' => $application->merchant->email];
                }
            }
        }

        foreach ($response as $merchant_id=>$app){
            if (count($app) > 1){
                $this->sendMerchantCommunication($app, $merchantData[$merchant_id]);
                $serviceCount++;
            }
        }

        (new Services())->log($this->type, ['status' => true, 'service_count' => $serviceCount, 'start_time' => $start_time]);
    }

    public function sendRewardsReminder($event = array()){
        if ($event)
            $event->comment('Processed');
        $serviceCount = 0;
        $start_time = time();
        $users = User::whereIn('user_type',['center_head','center_executive','merchant'])->get();
        $merchantApiController = new MerchantApiController();
        $one_down_check = '';
        foreach($users as $user){
            if($user->merchant_id > 0) {
                $rewardsStatus = $merchantApiController->getRewardsStatus([$user->merchant_id, $user->id], true);
                $rewardsStatus = $rewardsStatus['data'];
                if(isset($rewardsStatus['badges'])){
                    foreach ($rewardsStatus['badges'] as $badge => $badgeView){

                        if($badge == 'refer_badge'){
                            if($badgeView == 'eligible') {
                                if(Carbon::now()->isSaturday()) {
                                    $this->sendMail(6, $user);
                                    $serviceCount++;
                                }
                            }else{
                                if(isset($rewardsStatus['attributes'])) {
                                    $ref = ConsumerApplication::whereNotIn('state', $rewardsStatus['attributes']['status'])
                                        ->whereIn('merchant_id', $rewardsStatus['attributes']['merchant_id'])
                                        ->where('src_representative_name', $rewardsStatus['attributes']['user_id'])
                                        ->whereNull('is_deleted')
                                        ->where('created_at', '>=', Carbon::now()->subWeek(2)->toDateTimeString())
                                        ->count();
                                    if ($ref) {
                                        if(Carbon::now()->isSaturday()) {
                                            $this->sendMail(6, $user);
                                            $serviceCount++;
                                        }
                                    }
                                }
                            }

                        }

                        if($badge == 'one_down'){
                            if ($badgeView['status'] == 'in-process'){
                                $one_down_check = true;
                                $this->sendMail(1, $user);
                                $serviceCount++;
                            }else if ($badgeView['status'] == 'achieved' && $rewardsStatus['badges']['hat_trick']['status'] != 'achieved'){
                                $this->sendMail(2, $user);
                                $serviceCount++;
                            }
                        }
                        if($badge == 'hat_trick' && empty($one_down_check)){
                            if ($badgeView['status'] == 'eligible'){
                                $this->sendMail(3, $user);
                                $serviceCount++;
                            }else if($badgeView['status'] == 'in-process'){
                                $this->sendMail(4, $user);
                                $serviceCount++;
                            }else if ($badgeView['status'] == 'achieved'){
                                $this->sendMail(5, $user);
                                $serviceCount++;
                            }
                            break;
                        }
                    }
                }
            }

            if($user->id){
                $device = Devices::where('user_id',$user->id)->first(['id']);
                if (!isset($device->id)) {
                    $this->sendMail(7, $user);
                    $serviceCount++;
                }
            }
        }

        (new Services())->log($this->type, ['status' => true, 'service_count' => $serviceCount, 'start_time' => $start_time]);
    }

    public function sendMail($type, $user){

        $sms = "";
        $notification = "";
        $name = $user->name;
        $phone = $user->mobile_number;
        $deeplink = "";
        $notification_type = "";
        $bitly = "https://partner.creditfair.in";
        $endOfWeek = date('d M, Y',Carbon::now()->endOfWeek()->timestamp);
        $nextWeekStart = date('d M, Y',Carbon::now()->addDay(1)->startOfWeek()->timestamp);
        $playStore = 'https://bit.ly/3etTzRP';//\Bitly::getUrl("https://play.google.com/store/apps/details?id=com.partner.creditfair");

        if($type == 1){
            $deeplink = "/rewards?click=one_down";
            $bitly .= $deeplink;
            $bitly = Shortio::getUrl($bitly);
            $notification_type = "one_down_not_achieved";
            $sms = "Dear $name,<br/>Login 5 application using Credit Fair’s App with minimum approval amount of Rs.1,50000 to receive Rs.500 .Start now @ $bitly.<br/>Regards,<br/>Team Credit Fair";
            $notification = "Login 5 applications to receive Rs.500!";
            $title = "Your Rewards – Rs.500.";
        }elseif ($type == 2){
            $deeplink = "/rewards?click=one_down";
            $bitly .= $deeplink;
            $bitly = Shortio::getUrl($bitly);
            $notification_type = "one_down_on_achievement";
            $sms = "Dear $name,<br/>Congrats on earning Rs.500. Login 20 more applications with the disbursal amount of Rs.500000 before $endOfWeek to earn Rs.3000 Go to @ $bitly.<br/>Regards,<br/>Team Credit Fair";
            $notification = "Congrats on earning Rs.500! Login twenty more applications with the disbursal amount of Rs.500000 $endOfWeek to earn Rs.3000.";
            $title = "Congrats on CashBack of Rs.500!";
        }elseif ($type == 3){
            $deeplink = "/rewards?click=hat_trick";
            $bitly .= $deeplink;
            $bitly = Shortio::getUrl($bitly);
            $notification_type = "hat_trick_not_achieved_one_down_achieved";
            $sms = "Dear $name,<br/>Login 25 applications using Credit Fair’s App with minimum disbursal of Rs.500000 to earn  Rs.3000! Visit $bitly.<br/>Regards,<br/>Team Credit Fair";
            $notification = "Login 25 applications using Credit Fair’s App with minimum disbursal of Rs.500000 to earn Rs.3000!";
            $title = "Your Rewards – Rs.3000.";
        }elseif ($type == 4){
            $deeplink = "/rewards?click=hat_trick";
            $bitly .= $deeplink;
            $bitly = Shortio::getUrl($bitly);
            $notification_type = "hat_trick_not_achieved_one_down_achieved";
            $sms = "Dear $name,<br/>Login 25 applications using Credit Fair’s App with minimum disbursal of Rs.500000 to earn  Rs.3000! Visit $bitly.<br/>Regards,<br/>Team Credit Fair";
            $notification = "Login 25 applications using Credit Fair’s App with minimum disbursal of Rs.500000 to earn Rs.3000!";
            $title = "Your Rewards – Rs.3000.";
        }elseif ($type == 5){
            $notification_type = "hat_trick_on_achievement";
            $sms = "Dear $name,<br/>Congrats on earning Rs.3000! You can earn Rs.3000 again after $nextWeekStart.<br/>Regards,<br/>Team Credit Fair";
            $notification = "Congrats on earning Rs.3000! You can earn Rs.3000 again after $nextWeekStart.";
            $title = "Congrats on Hat Trick!";
        }elseif($type == 6){
            $deeplink = "/rewards?click=refer_badge";
            $bitly .= $deeplink;
            $bitly = Shortio::getUrl($bitly);
            $notification_type = "refer_a_friend_not_achieved";
//            $sms = "Dear $name,<br/>Refer a Friend today to earn Rs 500 and increase your chances to win the lucky draw! Visit $bitly.<br/>Regards,<br/>Team Credit Fair";
            $sms = "Dear $name,<br/>Refer your friend & earn upto Rs.10k on successful disbursal. Referring also helps you increase your social score. Refer now $bitly";
            $notification = "Refer a Friend today to earn Rs 500 and increase your chances to win the lucky draw!";
            $title = "Refer a Friend.";
        }elseif($type == 7){
            $sms = "Dear $name,<br/>Download Credit Fair’s Merchant App today to grow your business and receive cash rewards & enter lucky draw! Start now @ $playStore OR visit partner.creditfair.in.<br/> Regards,<br/>Team Credit Fair";
        }

        if($sms) {
            (new Reminders(new Request()))
                ->setSMSBody(str_replace('<br/>', "\n", $sms))
                ->setPhone($phone)
                ->setAdditionalData(['id' => $user->id, 'id_type' => 'user_id'])
                ->send();
        }

        if($notification){
            $request = [
                'type' => 'user',
                'id' => $user->id,
                'notification_type' => $notification_type,
                'title' => $title,
                'body' => $notification,
                'deeplink' => $deeplink
            ];
            new FCMNotification(new Request($request));
        }
    }

    public function sendMerchantCommunication($applications, $merchant){

        $body = "Dear ".$merchant['name'].",<br/><br/>Thank you for choosing us as your financial partner. we want to update you on approved cases. Following are the cases which are approved and awaiting for disbursement.<br/>Please follow up with the customers to convert your sales:<br/><br/>";

        $body .= "<table style='font-family: arial, sans-serif;border-collapse: collapse;width: 100%;'><tr style='background-color: #dddddd;'><td style='border: 1px solid #dddddd;text-align: left;padding: 8px;'>Customer Name</td><td style='border: 1px solid #dddddd;text-align: left;padding: 8px;'>Contact</td><td style='border: 1px solid #dddddd;text-align: left;padding: 8px;'>Approved Amount</td><td style='border: 1px solid #dddddd;text-align: left;padding: 8px;'>Approved Date</td><td style='border: 1px solid #dddddd;text-align: left;padding: 8px;'>Reason For Hold</td></tr>";
        $sendMessage = 0;
        foreach ($applications as $key=>$application) {
            if ($reason = $this->getHoldReason($application['id'])) {
                $sendMessage = 1;
                $body .= "<tr><td style='border: 1px solid #dddddd;text-align: left;padding: 8px;'>" . $application['customer'] . "</td><td style='border: 1px solid #dddddd;text-align: left;padding: 8px;'>" . $application['phone'] . "</td><td style='border: 1px solid #dddddd;text-align: left;padding: 8px;'>" . $application['approved_amount'] . "</td><td style='border: 1px solid #dddddd;text-align: left;padding: 8px;'>" . $application['approved_at'] . "</td><td style='border: 1px solid #dddddd;text-align: left;padding: 8px;'>" . $reason . "</td></tr>";
            }
        }
            $body .="</table>";


        $subject = "Update on your approved cases";

        if ($sendMessage && (!(BNPL::is($merchant['id'])) && !in_array($merchant['id'],[6418,6517,6598,6865,6600]))) {
            \Mail::send('emails.reminders.basic_reminder',
                ['body' => $body]
                , function ($message) use ($merchant, $subject) {
                    $message->to($merchant['email'])->subject($subject);
                    $message->cc(_env('NOTIFY_EMAIL', ''));
                });
        }
    }


    public function getHoldReason($id){
        $checks = ['security_cheques', 'nach', 'agreement'];
        $files = ConsumerApplicationFiles::where('consumer_application_id', $id)->whereIn('file_type',$checks)->groupBy('file_type')->get(['file_type']);
        $availableFiles = [];
        foreach ($files as $file){
            $availableFiles[] = $file->file_type;
        }

        $missing = [];
        foreach ($checks as $check){
            if(!in_array($check, $availableFiles)){
                if ($check == 'agreement'){
                    if (!$this->isSigned($id)) {
                        $missing[] = ucwords(str_replace('_', ' ', $check));
                    }
                }else{
                    $missing[] = ucwords(str_replace('_',' ',$check));
                }
            }else if ($check == 'agreement'){
                if (!$this->isSigned($id)) {
                    $missing[] = ucwords(str_replace('_', ' ', $check));
                }
            }
        }
        return $missing ? 'Pendings document: '.implode(', ',array_unique($missing)) : '-';
    }

    public function isSigned($id){
        $consumer_application = ConsumerApplication::with('digital_sign')->where('id',$id)->first();
        if(!empty($consumer_application->name) && !empty($consumer_application->co_applicant_name)){
            if ($consumer_application->digital_sign && count($consumer_application->digital_sign) == 2){
                return true;
            }
        }else if ($consumer_application->digital_sign && count($consumer_application->digital_sign) == 1){
            return true;
        }

        return false;
    }

    public function savePrincipalOutstanding($event = array(), $dateOf = null){
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $applications = ConsumerApplication::whereIn('state',['disbursed','nach registered'])->whereNull('is_deleted')->get(['id']);


        $created_at = Carbon::now()->toDateTimeString();;
        $response = null;
        $date = $dateOf ? $dateOf : Carbon::now()->endOfMonth()->toDateString();
        $accounting = new AccountingController();
        $i = 0;

        $principalOutstanding = PrincipalOutstanding::where('date', $date)->get(['id','application_id']);

        $ids = [];
        foreach ($principalOutstanding as $item){
            $ids[] = $item->application_id;
        }

        foreach ($applications as $application) {
            try {

                if(!in_array($application->id, $ids)) {

                    $logged = false;
                    if ($event) {
                        $event->comment('Processing ' . $application->id);
                    }

                    $schedules = $accounting->viewloanschedule($application->id, 1, 1);
                    foreach ($schedules['schedule'] as $key => $schedule) {
                        $logged = false;
                        if (date('Y-m', strtotime($schedule['emi_date'])) == date('Y-m', strtotime($date))) {
                            $response = ['application_id' => $application->id, 'principal_outstanding' => round($schedule['principal_outstanding'], 2), 'date' => $date, 'created_at' => $created_at];
                            $logged = true;
                            break;
                        }
                    }

                    if (!$logged && isset($schedules['schedule'][0]) && isset($schedules['schedule'][0]['principal_outstanding'])) {
                        $statusLogs = StatusLogs::where('created_at', 'like', '%' . date('Y-m', strtotime($date)) . '%')->where('status', 'disbursed')->first(['id']);
                        if (isset($statusLogs->id) && date('Y-m-d', strtotime($schedules['schedule'][0]['emi_date'])) >= date('Y-m-d', strtotime($date))) {
                            $response = ['application_id' => $application->id, 'principal_outstanding' => round($schedules['schedule'][0]['principal_outstanding'], 2), 'date' => $date];
                        }
                    }

                    if ($response) {
                        PrincipalOutstanding::insert($response);
                        $response = null;
                    }
                }
            }catch (\Exception $e){
                if(!$i) {
                    (new Slack(new Request(['title' => 'Principal outstanding Calc', 'fields' => ['m' => $e->getMessage(), 'l' => $e->getLine(), 'f' => $e->getFile()], 'group' => Slack::$STAGE_TESTING])))->send();
                    $i = 1;
                }
                if($event){
                    $event->comment($e->getMessage().'|'.$e->getLine().'|'.$e->getLine());
                }
            }
        }

    }

    public function tallyEntriesAlert(){
        $ledgerCount = TallyJobs::where('created_at','>=',Carbon::now()->startOfDay()->toDateTimeString())->where('created_at','<=',Carbon::now()->endOfDay()->toDateTimeString())->where('payload','like','%LEDGER%')->count();
        $repaymentCount = TallyJobs::where('created_at','>=',Carbon::now()->startOfDay()->toDateTimeString())->where('created_at','<=',Carbon::now()->endOfDay()->toDateTimeString())->where('payload','like','%emi_amount%')->count();

        if($ledgerCount || $repaymentCount) {
            (new Slack(new Request(['title' => 'Tally entries summary', 'fields' => ['Total Ledger Created' => $ledgerCount, 'Total Repayment Created' => $repaymentCount], 'group' => Slack::$accounting_entries])))->send();
        }
    }

    public function sendBirthdayReminder()
    {
        $today = Carbon::now()->today()->format('m-d');

        $consumer_birthday = ConsumerApplication::where('dob', 'like', '%' . $today . '%')->whereIn('state',['disbursement checklist done', 'ready for disbursement','disbursed','approved','closed','nach registered','ready for disbursement'])->get(['name', 'email', 'dob']);

        $co_consumer_birthday = ConsumerApplication::where('co_applicant_dob', 'like', '%' . $today . '%')->whereIn('state',['disbursement checklist done', 'ready for disbursement','disbursed','approved','closed','nach registered','ready for disbursement'])->get(['co_applicant_name as name', 'co_applicant_email as email', 'co_applicant_dob as dob']);

        $merchant_birthday = Merchant::where('dob', 'like', '%' . $today . '%')->where('status','active')->where('is_guest_active',1)->get(['merchant_name', 'email', 'dob']);

        $subject = 'Happy Birthday';
        $customerSent = 0;
        $emails = [];
        foreach ($consumer_birthday as $birthday) {
            if(isset($birthday) && !empty($birthday) && $birthday->email && !in_array($birthday->email, $emails)) {
                $content = "<div><h4>Dear $birthday->name, <br/>Team Credit Fair wishes You Happy Birthday!</h4></div>";

                    \Mail::send('emails.reminders.birthday', [
                        'body' => $content,
                    ], function ($message) use ($birthday, $subject) {
                        //$message->from(_env('CENTRALOPS'));
                        $message->to($birthday->email)->subject($subject);
                        //$message->cc('ops@creditfair.in');
                    });

                $emails[] = $birthday->email;
                $customerSent++;
            }
        }

        if($customerSent) {
            (new Slack(new Request(['title' => 'Customer Birthday Wishes Sent', 'fields' => ['Total Sent' => $customerSent], 'group' => Slack::$BIRTHDAY_REMINDER])))->send();
        }

        $coCustomerSent = 0;
        foreach ($co_consumer_birthday as $birthday) {
            if(isset($birthday) && !empty($birthday) && $birthday->email && !in_array($birthday->email, $emails)) {
                $content = "<div><h4>Dear $birthday->name, <br/><br>Team Credit Fair wishes You Happy Birthday!</h4></div>";

                \Mail::send('emails.reminders.birthday', [
                    'body' => $content,
                ], function ($message) use ($birthday, $subject) {
                    //$message->from(_env('CENTRALOPS'));
                    $message->to($birthday->email)->subject($subject);
                });

                $emails[] = $birthday->email;
                $coCustomerSent++;
            }
        }

        if($coCustomerSent) {
            (new Slack(new Request(['title' => 'Co Applicant Birthday Wishes Sent', 'fields' => ['Total Sent' => $coCustomerSent], 'group' => Slack::$BIRTHDAY_REMINDER])))->send();
        }

        $merchantSent = 0;
        foreach ($merchant_birthday as $birthday) {
            if (isset($birthday) && !empty($birthday) && $birthday->email && !in_array($birthday->email, $emails)) {
                $content = "<div><h4 style='text-align:center; font-weight: 800; font-family: 'Courier New'>Dear $birthday->merchant_name, <br/><br> Team Credit Fair wishes You Happy Birthday!</h4></div>";

                    \Mail::send('emails.reminders.birthday', [
                        'body' => $content,
                    ], function ($message) use ($birthday, $subject) {
                        //$message->from(_env('CENTRALOPS'));
                        $message->to($birthday->email)->subject($subject);
                    });

                $emails[] = $birthday->email;
                $merchantSent++;
            }
        }

        if($merchantSent) {
            (new Slack(new Request(['title' => 'Merchant Birthday Wishes Sent', 'fields' => ['Total Sent' => $merchantSent], 'group' => Slack::$BIRTHDAY_REMINDER])))->send();
        }
    }

    public function sendMerchantTarget(){
        try {
            $merchants = Merchant::where('status', 'active')->where('is_guest_active', 1)->where('pre_status', 0)->where('target_number_application', '>', 0)->where('target_value_application', '>', 0)->get();

            $response[] = ['ID', 'Merchant Name', 'Actual number of applications', 'Actual value of application', 'Target number of applications', 'Target value of application'];
            foreach ($merchants as $merchant) {
                $target_number_application = ConsumerApplication::whereNull('is_deleted')->where('merchant_id', $merchant->id)->where('created_at', '>=', Carbon::now()->startOfMonth()->toDateTimeString())->where('created_at', '<=', Carbon::now()->endOfMonth()->toDateTimeString())->count();
                $target_value_application = ConsumerApplication::whereNull('is_deleted')->where('merchant_id', $merchant->id)->where('created_at', '>=', Carbon::now()->startOfMonth()->toDateTimeString())->where('created_at', '<=', Carbon::now()->endOfMonth()->toDateTimeString())->sum('loan_amount');

                $achieved_number_application = ($target_number_application / $merchant->target_number_application) * 100;
                $achieved_value_application = ($target_value_application / $merchant->target_value_application) * 100;

                if ($achieved_number_application < 50 || $achieved_value_application < 75) {
                    $response[] = [
                        'id' => $merchant->id,
                        'merchant_name' => $merchant->merchant_name,
                        'achieved_number_application' => $target_number_application,
                        'achieved_value_application' => $target_value_application,
                        'target_number_application' => $merchant->target_number_application,
                        'target_value_application' => $merchant->target_value_application,
                    ];
                }
            }

            if ($response) {
                $file = time() . '_' . Carbon::now()->toDateTimeString() . '_Merchant_Performance.xlsx';
                $this->getAttachment($file, $response);

                $emails = !env('APP_CONNECTION') ? ['pratik@creditfair.in', 'sunil@creditfair.in'] : ['merchantperformance@creditfair.in'];

                $count = count($response) - 1;
                Mail::send('emails.reminders.basic_reminder',
                    ['body' => "Dear Team,<br/> Please find attached Merchant's Performance sheet of " . $count . " merchants"]
                    , function ($message) use ($file, $emails) {
                        $message->to($emails)->subject('Merchant Performance Reminder');
                        $message->attachData(file_get_contents(storage_path() . '/app/' . $file), 'Merchant Performance Reminder ' . Carbon::now()->toDateTimeString() . '.xlsx');
                    });

                unlink(storage_path() . '/app/' . $file);
            }
        }catch (\Exception $e){

        }
    }

    public function getAttachment($file, $response){
        $request = new Request([
            'sheet' => ['Merchant Performance'],
            'data'  => [$response]
        ]);
        Excel::store(new ExporterMultipleSheet($request), $file);
    }

    public function lendboxRepayments(){
        event(new EventLendboxRepayments());
    }

    public function lendboxTransactionStatus(){
        event(new EventLendboxTransactionStatus());
    }
}
