<?php
/**
 * Created by PhpStorm.
 * User: sunil
 * Date: 10/29/18
 * Time: 12:43 PM
 */

namespace App\Http\Controllers\Admin;


use App\ConsumerApplication;
use App\Exports\Exporter;
use App\Http\Controllers\Controller;
use App\Lenders;
use App\Mandate;
use App\Nach;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class NachController extends Controller{

    private $request;

    public function __construct(Request $request){
        $this->request = $request;
    }

    public function index(){
        $lenders = Lenders::with('bank_details')->paginate(10);
        $applications = $this->getNachToBeSend();
        foreach ($lenders as $key=>$lender){
            $applicationInRequest = [];
            foreach ($applications as $application){
                if($lender->id == $application->lender_id) {
                    $applicationInRequest[] = $application;
                }
            }
            $lenders[$key]->nachApplications = $applicationInRequest;
        }

        $data = [
            'from_date' => $this->request->get('from_date'),
            'to_date' => $this->request->get('to_date')
        ];
        return view('admin.o-nach.index',['lenders' => $lenders],$data);
    }

    public function sendNach(){
        $status = 'FAIL';
        if($this->request->has('lender_id')){
            $status = (new Nach($this->request))
                ->setFileName('NACH - Mandate Registration.xlsx')
                ->setLender($this->request->get('lender_id'))
                ->getAttachment()->sendNach($this->request->get('type'));

            if($this->request->get('type') == 'download'){
                return $status;
            }
            $status = ($status) ? 'OK' : 'FAIL';
        }
        return response()->json(['status'=>$status],200);
    }

    public function sendMonthlyNach(){

        $lenderSpecificIds = [];
        $ConsumerApplications = ConsumerApplication::whereIn('id',$this->request->get('applications'))->get(['id','lender_id']);
        foreach ($ConsumerApplications as $application){
            $lenderSpecificIds[$application->lender_id][] = $application->id;
        }
        foreach ($lenderSpecificIds as $lender_id => $specificId) {
            $this->request->attributes->add(['applicationsIds' => $specificId, 'isMonthly' => true]);
            $status = (new Nach($this->request))
                ->setFileName('NACH_TXN_FILE_NEW.xlsx')
                ->setLender($lender_id)
                ->getAttachment()->sendNach();
            if(!$status){
                $this->setTechBug($specificId);
            }
        }
    }

    public function setTechBug($specificId){
        \Mail::send('emails.blank',
            ['body'=>$specificId.' Application, Error while sending monthly email']
            , function ($message) {
                $message->to('tech@creditfair.in')->subject('Error in queue');
                /*$message->cc(env('NOTIFY_EMAIL', ''));*/
            });
    }

    public function getNachToBeSend(){
        return $nach = (new Nach($this->request))
            ->getAllApplications();
    }

    public function getNachCancellation(){
        //$lender_id = Input::has('lender_id') ? Input::get('lender_id') : 0;

        $response = array();
        //$response['lenders'] = Lenders::all();

        $status = ['cancelled','closed'];
        $applications = ConsumerApplication::with('mandateMany','bank_details','lender')->wherein('state',$status)->whereNull('is_deleted');
//        if($lender_id > 0){
//            $applications = $applications->where('lender_id',$lender_id);
//        }
        $applications = $applications->get();
        foreach ($applications as $application){
            foreach ($application->mandateMany as $mandates){
                if($mandates->status == 'active') {
                    $response['applications'][$mandates->id]['id'] = $application->id;
                    $response['applications'][$mandates->id]['name'] = $application->name;
                    $response['applications'][$mandates->id]['status'] = ucfirst($application->state);
                    $response['applications'][$mandates->id]['lender'] = $application->lender->name;
                    $response['applications'][$mandates->id]['bank_name'] = isset($application->bank_details) ? $application->bank_details->bank_name : '';
                    $response['applications'][$mandates->id]['account_number'] = isset($application->bank_details) ? $application->bank_details->account_number : '';
                    $response['applications'][$mandates->id]['mandate_id'] = $mandates->id;
                    $response['applications'][$mandates->id]['amount'] = $mandates->mandate_amount;
                    $response['applications'][$mandates->id]['umrn'] = $mandates->umrn;
                    $response['applications'][$mandates->id]['frequency'] = (isset($mandates->frequency) and $mandates->frequency == "M") ? "Monthly" : "Adhoc";
                    $response['applications'][$mandates->id]['mode'] = $mandates->mode;
                }
            }
        }

        return view('admin.o-nach.nachCancellation',$response);

    }

    public function cancelMandate(Request $request){
        $nachs = $request->get('nachs');
        $status = 'OK';
        $message = '';
        $nachs = array_keys($nachs);
        $mandates = Mandate::whereIn('id', array_values($nachs))->get();

        $RBLNach = [];
        $HDFCNach = [];
        $LotusPayNach = [];

        foreach ($mandates as $mandate){
            $application = ConsumerApplication::with('bank_details')->where('id',$mandate->consumer_application_id)->first();
            if ($mandate->mode == 'nach') {
                if ($application->lender_id == 1) {
                    $RBLNach[] = ['email' => $application->email];
                } else {
                    if($mandate->umrn) {
                        $HDFCNach[] = ['umrn' => $mandate->umrn, 'reference_number' => $application->id, 'account_number' => $application->bank_details->account_number, 'name' => $application->name];
                    }
                }
            } else if (strpos($mandate->mode, 'lotuspay') !== false) {
                if($mandate->mandate_id) {
                    $LotusPayNach[] = ['id'=> $mandate->id,'mandate_id'=>$mandate->mandate_id];
                }
            } else {
                //nach cancel failed
                $nachCancelFailed[] = $application->name;
            }
        }


        if($RBLNach){

        }
        if($HDFCNach){
            $this->sendCancellationToHDFC($HDFCNach);
        }
        if($LotusPayNach){
            $this->cancelLotusPayMandate($LotusPayNach);
        }


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

    public function cancelLotusPayMandate($LotusPayNach){
        foreach ($LotusPayNach as $nach) {
            Mandate::cancel($nach['id'],$nach['mandate_id']);
        }
    }

    public function sendCancellationToHDFC($HDFCNach){
        $header[] = ['UMRN number','Reference Number','Customer Account number','Customer Name'];
        $header = array_merge($header,$HDFCNach);
        $request = new Request(['data' => $header,'sheet'=>'sheet']);
        $file = 'HDFC UMRN Data for NACH Cancellation_'.time().'.xlsx';
        Excel::store((new Exporter($request)), $file);
        \Mail::send('emails.blank',
            ['body'=>'Dear Team,<br/>Please find the attached UMRN data for cancellation.']
            , function ($message) use($file, $HDFCNach) {
                $message->to(['Swapnalatha.Salian@hdfcbank.com','nach@hdfcbank.com'])->subject('K M GLOBAL CREDIT PVT LTD No. of Mandates ('.count($HDFCNach).')'); //Swapnalatha.Salian@hdfcbank.com,nach@hdfcbank.com
                $message->attachData(file_get_contents(storage_path().'/app/'.$file), 'HDFC UMRN Data for NACH Cancellation.xlsx');
            });
    }
}
