<?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\EmiPayment;
use App\Exports\Exporter;
use App\Http\Controllers\Admin\AccountingController;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Controllers\Admin\DisbursementController;
use App\Lenders;
use App\Logging\CloudWatchLoggerFactory;
use App\PaymentTransaction;
use App\Services;
use App\Singularity\Singularity;
use App\Templates;
use App\Vivriti;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class AdviserReminders extends Command
{

    protected $signature = 'adviser:application_reminder {--collection_report=}';
    private $collection_report = 0;

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

    public function handle(){
        $hour = date('H',time());
        $day_of_week = date('N',time());

        if (\app()->runningInConsole()) {
            $this->collection_report = $this->option('collection_report');
        }

        // Now the merchant collection report will be triggered from cf-python-scripts service
        
        // if(($hour == 10 && ($day_of_week == 1 || $day_of_week == 3 || $day_of_week == 5)) || $this->collection_report){
        //     $accounting  = new AccountingController();
        //     $accounting->getMerchantCollectionReport();
        // }
        if($hour == 11 && !$this->collection_report){
            $this->getNonStaterList();
        }
        if($hour == 01 || $hour == 1){
            //(new DisbursementController(new Request()))->dump();
        }

        /*if ($this->collection_report == 0) {

            if ($hour == 9 || $hour == 15 || $hour == 19) {
                $application = new ConsumerApplicationController();
                $applicationData = $application->getAdviserApplication();

                $this->sendReminder($applicationData, $application);
            }
        }*/

        return true;
    }

    public function getNonStaterList(){
        try {
            if (Carbon::now()->day == 5 || Carbon::now()->day == 05 || Carbon::now()->day == 18) {
                return false;
            }

            $now = Carbon::now()->endOfDay()->toDateTimeString();

            $ids = EmiPayment::whereNotNull('application_id')
                ->whereNotIn('application_id', function ($query) use ($now) {
                    $query->select('application_id')
                        ->from('emi_payments')
                        ->where('emi_date', '<=', $now)
                        ->whereIn('payment_status', ['success', 'partial'])
                        ->whereNotNull('application_id');
                })
                ->whereNotIn('application_id', function ($query) {
                    $query->select('application_id')
                        ->from('payment_transactions')
                        ->where('payment_for', 'EMI')
                        ->whereNotNull('application_id');
                })
                ->where('emi_date', '<=', $now)
                ->groupBy('application_id')
                ->pluck('application_id')
                ->toArray();

            if (empty($ids)) {
                return false;
            }

            $lender = Lenders::where('id', 2)->first();

            $applications = ConsumerApplication::with('approved.user', 'advisor', 'proFormaInvoice', 'merchant', 'emi', 'lender', 'checkmandate', 'application_element.collection_executive', 'application_element.merchant_center')->whereNull('is_deleted')->whereIn('state', ['disbursed', 'nach registered'])->whereIn('id', $ids)->whereNotIn('lender_id', [Singularity::$lender_id, Capri::$lender_id, Vivriti::$lender_id])->get(['id', 'created_by', 'name', 'co_applicant_name', 'co_applicant_mobile_number', 'merchant_id', 'current_address_city', 'current_address_state', 'mobile_number', 'email', 'lender_id']);

            $merchantsMails = [];
            $merchantsMailsData = [];
            $merchantsMailsDataContacts = [];

            foreach ($applications as $application) {

                if ($application->merchant) {

                    if (!isset($merchantsMails[$application->merchant_id])) {
                        $merchantsMails[$application->merchant_id] = explode(',', trim($application->merchant->email));
                        $merchantsMailsData[$application->merchant_id] = $application->merchant->merchant_name;
                        $merchantsMailsDataContacts[$application->merchant_id] = [$application->merchant->contact_number, $application->merchant->rcp_mobile, $application->merchant->sales_head_mobile, $application->merchant->finance_head_mobile];
                    }

                    $response[$application->merchant_id][] = [
                        'credit_executive_name' => $application->approved->user->name ?? '',
                        'id' => $application->id,
                        'agreement_number' => $application->proFormaInvoice->loan_application_no ?? '',
                        'name' => $application->name,
                        'co_applicant_name' => $application->co_applicant_name,
                        'co_applicant_number' => $application->co_applicant_mobile_number,
                        'merchant_name' => $application->merchant->merchant_name ?? '',
                        'center_name' => $application->application_element->merchant_center->name ?? '',
                        'lender_name' => $application->lender->name ?? '',
                        'email' => $application->email,
                        'phone' => $application->mobile_number,
                        'amount' => $application->emi->emi,
                        'first_emi_date' => $application->emi->emi_date,
                        'nach_status' => isset($application->checkmandate->id) ? 'Active' : 'InActive',
                        'advisor' => $application->advisor->name ?? '',
                        'collection_executive' => $application->application_element->collection_executive->name ?? '',
                        'current_city' => $application->current_address_city,
                        'current_state' => $application->current_address_state
                    ];
                }
            }

            if (isset($response)) {
                $column = ['Credit Executive Name', 'ID', 'Agreement Number', 'Name', 'Co Applicant name', 'Co Applicant Number', 'Merchant Name', 'Center Name', 'Lender Name', 'Email', 'Phone', 'Amount', 'First EMI Date', 'Nach Status', 'Advisor', 'Collection Executive', 'Current City', 'Current State'];
                $completeData[] = $column;

                foreach ($response as $merchant_id => $item) {
                    if (isset($merchantsMails[$merchant_id]) && $merchantsMails[$merchant_id]) {
                        $file = time() . '_' . Carbon::now()->toDateTimeString() . $merchant_id . '-Non-Starter-List.xlsx';

                        $itemData = $item;

                        array_unshift($item, $column);

                        $requestData = new Request(['data' => $item, 'sheet' => 'Non-Starter Cases']);
                        Excel::store((new Exporter($requestData)), $file);

                        $mails = array_filter($merchantsMails[$merchant_id]);
                        $name = $merchantsMailsData[$merchant_id];
                        $contact = array_filter(array_values(array_unique($merchantsMailsDataContacts[$merchant_id])));

                        $completeData = array_merge($completeData, $itemData);

                        $body = "Dear $name,<br/>
    Please find your Non-Starter cases attached. We need your support to clear these cases as soon as possible.<br/>
    For discussing please call us on 8850077108 / 8928769161 / 7900125682.";

                        $fileName = 'Non-Starter-List ' . Carbon::now()->toDateTimeString() . $merchant_id . '.xlsx';
                        if (!(BNPL::is($merchant_id)) && !in_array($merchant_id, [6418, 6517, 6598, 6865, 6600])) {
                            try {
                                Mail::send('emails.reminders.basic_reminder',
                                    ['body' => $body]
                                    , function ($message) use ($file, $mails, $fileName) {
                                        $message->to($mails)->cc(['collections@creditfair.in'])->subject('Non-Starter Cases IMP');
                                        $message->attachData(file_get_contents(storage_path() . '/app/' . $file), $fileName);
                                    });

                                $this->sendDocumentOnWhatsapp(['pdf' => file_get_contents(storage_path() . '/app/' . $file), 'fileName' => $fileName, 'lender' => $lender, 'id' => $merchant_id, 'contact_number' => $contact, 'items' => $item]);
                            }catch (\Exception $e){

                            }
                        }
                        unlink(storage_path() . '/app/' . $file);
                    }

                }


                if (isset($completeData) && $completeData) {

                    $file = time() . time() . '_' . Carbon::now()->toDateTimeString() . '-Non-Starter-List.xlsx';

                    $requestData = new Request(['data' => $completeData, 'sheet' => 'Non-Starter Cases']);
                    Excel::store((new Exporter($requestData)), $file);


                    $body = "Dear Collection team,<br/>
    Please find your Non-Starter cases attached. We need your support to clear these cases as soon as possible.<br/>
    For discussing please call us on 8850077108 / 8928769161 / 7900125682.";

                    $bcc = ['imran@creditfair.in', 'ketan@creditfair.in', 'amol@creditfair.in','imran@creditfair.in',
                    'rohan.tawade@creditfair.in','mahendra.kumavat@creditfair.in','abhishek.shetty@creditfair.in',
                    'mansi@creditfair.in','dipak.atkar@creditfair.in','savitha.nadar@creditfair.in','nitesh.pandya@creditfair.in'];
                    try {
                        Mail::send('emails.reminders.basic_reminder',
                            ['body' => $body]
                            , function ($message) use ($file, $bcc) {
                                $message->to(['neel.gangar@creditfair.in', 'shraddha@creditfair.in'])->cc($bcc)->subject('Non-Starter Cases IMP');
                                $message->attachData(file_get_contents(storage_path() . '/app/' . $file), 'Non-Starter-List ' . Carbon::now()->toDateTimeString() . '.xlsx');
                            });

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

                    }
                }

            }
        }catch (\Exception $e){
            $cwFactory = new CloudWatchLoggerFactory();
            $_data = array(
                'exception' => 'Error while sending Non Starter Report',
                'message' => $e->getMessage(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            );
            $cwFactory->logger(json_encode($_data));
        }
    }

    public function sendDocumentOnWhatsapp($mailData){
        try {
            if($mailData['contact_number']) {

                $pdf = App::make('snappy.pdf.wrapper');

                $report = $pdf->loadView('front.application.nonstarterreport', ['items' => $mailData['items'], 'lender' => $mailData['lender'], 'type' => ''])->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');


                $name = str_replace(':','_', str_replace('.xlsx', '.pdf', str_replace(' ', '_', $mailData['fileName'])));
                Storage::disk('storage')->put($name, $report->output());

                $link = asset("stream/uploads/" . $name);
                foreach ($mailData['contact_number'] as $contact_number) {
                    sendWhatsAppMessage($contact_number, ['id' => $mailData['id'], 'caption' => 'Non-Starter Customers','templateId' => Templates::$non_starter_report_doc, 'args' => [$link], 'templateType' => 'richTemplate']);
                }
                //Storage::disk('public_file')->delete($name);
            }
        }catch (\Exception $e){

        }
    }

    public function sendReminder($applications, ConsumerApplicationController $application){
        $start_time = time();
        $serviceCount = 0;
        foreach ($applications as $applicationsData){
            if($applicationsData['flag']) {
                $this->sendMail($applicationsData, $application);
                $serviceCount++;
            }
        }

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

    public function sendMail($data, ConsumerApplicationController $application){
        if(isset($data['adviser']) && isset($data['adviser']->user_type) && $data['adviser']->user_type != 'consumer') {
            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 pending cases');
                });


            //$this->sendToSlack($data['applications'], $application);
        }
    }

    public function sendToSlack($data, ConsumerApplicationController $application){

    }

}
