<?php
/**
 * Created by PhpStorm.
 * User: sunil
 * Date: 10/27/18
 * Time: 10:30 AM
 */

namespace App\Exports;


use App\ConsumerApplication;
use App\Lenders;
use App\User;
use Carbon\Carbon;
use function foo\func;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithTitle;

class RBLNach implements FromArray, WithTitle
{
    private $utility_code = 'NACH00000000019187';
    private $accountTypes = ['savings' => 'S', 'current' => 'C'];
    private $frequency = ['monthly' => 'M', 'O' => 'O'];
    private $request;
    private $lender;
    private $isMonthly;
    private $lender_id;

    public function __construct(Request $request){
        $this->request = $request;
        $this->isMonthly = $this->request->attributes->has('isMonthly') ? 1 : 0;
        $this->setLender();
    }

    public function setLender(){
        $this->lender = Lenders::with('bank_details')->where('id',$this->request->get('lender_id'))->first();
        $this->lender_id = ($this->request->has('lender_id')) ? $this->request->get('lender_id') : $this->request->attributes->get('lender_id');
    }

    public function title(): string
    {
        return 'Mandates';
    }

    public function getApplicationData(){
        $applications  = ConsumerApplication::whereHas('logs', function($query){
            $query->where('status','disbursed')
                ->where('created_at','>=',Carbon::now()->subDay(1)->startOfDay()->toDateTimeString())
                ->where('created_at','<=',Carbon::now()->subDay(1)->endOfDay()->toDateTimeString());
        })->with('bank_details','emi','mandateMany')->whereNull('is_deleted');
        if($this->request->attributes->has('applicationsIds') && is_array($this->request->attributes->get('applicationsIds'))){
            $applications = $applications->whereIn('id',$this->request->attributes->get('applicationsIds'));
        }
        $applications = $applications->where('lender_id',$this->lender_id)->get();

        $response = [];
        foreach ($applications as $key=>$application){
            foreach($application->mandateMany as $mandate){
                if($this->isMonthly && $mandate->monthly_frequency == 1) {
                    break;
                }
                $response[] = array_values($this->responseFileArray($key, $application, $mandate));
            }
        }
        if(count($response) > 0){
            $header = $this->getColumns();
            $response =  array_merge([$header], $response);
        }

        return $response;
    }

    public function responseFileArray($key, $application, $mandate){
        if($this->isMonthly){
            return [
                'UserNumber' => $this->lender->bank_details->utility_code,
                'Date' => $this->request->attributes->get('applicationsJobData')[$application->id]->emi_date,
                'UMRN' => $mandate->umrn,
                'Amount' => $this->request->attributes->get('applicationsJobData')[$application->id]->amount,
            ];
        }else{
            return [
                'SRNO' => ($key + 1),
                'UTILITYCODE' => $this->lender->bank_details->utility_code,
                'ACTION' => isset($mandate->action) ? $mandate->action : 'N',
                'UMRN' => null,
                'MANDATE_DATE' => date('m/d/Y', time()),
                'ACCNUMBER' => $application->bank_details->account_number,
                'AC_TYPE' => $this->accountTypes[$application->bank_details->account_type],
                'IFSC_MICR' => $application->bank_details->ifsc_code,
                'BANK' => $application->bank_details->bank_details,
                'COLLECTION TYPE' => isset($mandate->collection) ? $mandate->collection : 'M',
                'AMOUNT' => $mandate->mandate_amount,
                'REFNO1' => $application->id,
                'REFNO2' => null,
                'FREQUENCY' => $mandate->frequency,
                'START_DATE' => date('m/d/Y' ,strtotime($application->emi->emi_date)),
                'END_DATE' => null,
                'UNTILCANCEL' => null,
                'CUST_NAME' => $application->name,
                'PHONE' => null,
                'MOBILE' => $application->mobile_number,
                'MAIL' => $application->email
            ];
        }
    }

    public function getColumns(){
        if($this->isMonthly) {
            return [
                'UserNumber', 'Date', 'UMRN', 'Amount'
            ];
        }else{
            return [
                'SRNO', 'UTILITYCODE', 'ACTION', 'UMRN', 'MANDATE_DATE', 'ACCNUMBER', 'AC_TYPE', 'IFSC_MICR', 'BANK', 'COLLECTION TYPE', 'AMOUNT', 'REFNO1',
                'REFNO2', 'FREQUENCY', 'START_DATE', 'END_DATE', 'UNTILCANCEL', 'CUST_NAME', 'PHONE', 'MOBILE', 'MAIL'
            ];
        }
    }

    /**
     * @return array
     */
    public function array(): array
    {
        // TODO: Implement array() method.
        return $this->getApplicationData();
    }
}
