<?php
/**
 * Created by PhpStorm.
 * User: sunil
 * Date: 10/26/18
 * Time: 6:14 PM
 */

namespace App;


use App\Exports\RBLNach;
use App\Imports\RBLNachImports;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Mail;
use Maatwebsite\Excel\Facades\Excel;

class Nach
{
    private $lenders;
    private $lenderID;
    private $properties;
    private $fileName;
    private $file;
    private $request;
    private $nachProperties;
    private $applicationsIds;
    private $lender;

    public function __construct(Request $request){
        $this->request = $request;
        $this->nachProperties = [
            [
                'action' => 'N',
                'collection' => 'M',
                'frequency' => 'M',
                'mandate_amount' => 0,
                'monthly_frequency' => 0,
                'mode' => 'nach'
            ],
            [
                'action' => 'N',
                'collection' => 'M',
                'frequency' => 'O',
                'mandate_amount' => 0,
                'monthly_frequency' => 1,
                'mode' => 'nach'
            ],
        ];
    }

    public function getLender(){
        $this->lenders = [
            1 => [
                'name' => 'Pride',
                'nach' => [
                    'name' => '\RBL',
                    'subject' => 'NACH Registration - Pride Financial Services'
                ],
            ],
            2 => [
                'name' => 'Credit Fair',
                'nach' => [
                    'name' => '\RBL',
                    'subject' => 'NACH Registration - Credit Fair Financial Services'
                ],
            ],
        ];

        return $this->lenders[$this->lenderID];
    }

    public function nach(){
        return $this->getLender()['nach'];
    }

    public function setFileName($fileName){
        $this->fileName = $fileName;
        return $this;
    }

    public function setLender($id){
        $this->lenderID = $id;
        $this->lender = Lenders::with('bank_details')->where('id',$this->lenderID)->first();
        $this->request->attributes->add(['lender_id' => $id]);
        return $this;
    }

    public function setProperties(){
        $this->properties = [
            'to' => explode(',',$this->lender->bank_details->email),
            'subject' => $this->nach()['subject'],
            'file' => storage_path().'/app/'.$this->file,
            'fileName' => $this->fileName
        ];
    }

    public function getMailer(){
        return (new Mailer($this));
    }

    public function getRBLNachExcel(){
        $this->getLender();
        $this->getAttachment();

    }

    public function getLenderObject($object){
        return new $object($this->request);
    }

    public function getAllApplications(){
        $fromDate = ($this->request->has('from_date')) ? Carbon::createFromFormat('Y-m-d',$this->request->get('from_date'))->startOfDay()->toDateTimeString()  : Carbon::now()->subDay(1)->startOfDay()->toDateTimeString();
        $toDate = ($this->request->has('to_date')) ? Carbon::createFromFormat('Y-m-d',$this->request->get('from_date'))->endOfDay()->toDateTimeString() : Carbon::now()->subDay(1)->endOfDay()->toDateTimeString();
        $status = StatusLogs::where('status','disbursed')->where('created_at','>=',$fromDate)
            ->where('created_at','<=',$toDate)->get();

        if ($status) {
            $ids = [];
            foreach ($status as $item) {
                if (!in_array($item->application_id, $ids)) {
                    $ids[] = $item->application_id;
                }
            }
            return ConsumerApplication::with('emi')->whereIn('id', $ids)->whereNull('is_deleted')->get();
        }

        return [];
    }

    public function getApplications(){
        return $this->getLenderObject('\App\Exports'.$this->nach()['name'].'Nach');
    }

    public function addNachMailer(){
        return $this->getLenderObject('\App\Imports'.$this->nach()['name'].'NachImports');
    }

    public function getAttachment(){
        $this->file = time().'/'.$this->fileName;
        Excel::store($this->getApplications(), $this->file);
        $this->setProperties();
        return $this;
    }

    public function sendNach($type = 'send'){
        try {
            $properties = $this->properties;


            if($type == 'download'){
                $headers = array(
                    'Content-Type: application/vnd.ms-excel',
                );
                return response()->download($properties['file'], $properties['fileName'], $headers);
            }

            Mail::send('emails.nach_' . strtolower(str_replace("\\", '', $this->nach()['name'])), [
                'properties' => $properties,
            ], function ($message) use ($properties) {
                $message->to($properties['to'])->subject($properties['subject']);
                $message->attachData(file_get_contents($properties['file']), $properties['fileName']);
            });

            return true;
        }catch (\Exception $e){
            return false;
        }
    }

    public function getDefaultNachProperties($application, $id){

        $data = [];
        if(count($application->mandateMany) == 1){
            if(isset($application->mandateMany[0]->monthly_frequency) && $application->mandateMany[0]->monthly_frequency == 1){
                $nachProperty = $this->nachProperties[0];
            }else{
                $nachProperty = $this->nachProperties[1];
            }

            $mandate = new \stdClass();
            $mandate->consumer_application_id = $id;
            $mandate->action =  $nachProperty['action'];
            $mandate->collection =  $nachProperty['collection'];
            $mandate->frequency =  $nachProperty['frequency'];
            $mandate->mandate_amount =  $nachProperty['mandate_amount'];
            $mandate->monthly_frequency =  $nachProperty['monthly_frequency'];
            $mandate->mode =  $nachProperty['mode'];

            $data[] = $mandate;
            $data[] = $application->mandateMany[0];
        }else {
            foreach ($this->nachProperties as $nachProperty) {
                $mandate = new \stdClass();
                $mandate->consumer_application_id = $id;
                $mandate->action = $nachProperty['action'];
                $mandate->collection = $nachProperty['collection'];
                $mandate->frequency = $nachProperty['frequency'];
                $mandate->mandate_amount = $nachProperty['mandate_amount'];
                $mandate->monthly_frequency = $nachProperty['monthly_frequency'];
                $mandate->mode =  $nachProperty['mode'];
                $data[] = $mandate;
            }
        }

        return $data;
    }
}
