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

namespace App;


use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Controllers\Couriers\CouriersController;
use App\Http\Controllers\MerchantApiController;
use App\Imports\CollectionImport;
use App\Tally\Tally;
use App\Tally\TallyConnector;
use App\Tally\TallyJobs;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TallyJobsListener
{

    public $job_id = null;
    public $isAuto = false;
    public $autoTally = array();
    public static $schedule = [];

    public function __construct(){

    }

    public function start(){

        $serviceCount = 0;
        $jobs = TallyJobs::where('is_available',0);
        if($this->job_id){
            $jobs = $jobs->where('id', $this->job_id);
        }else{
            $jobs = $jobs->where('payload','like','%LEDGER%');
            //$jobs = TallyJobs::where('is_available',0)->where('created_at','>=','2019-12-13 00:00:00')->where('created_at','<=','2019-12-13 23:59:59')->orderBy('emi_date','asc')->get();
            //$jobs = TallyJobs::where('id',7290)->orderBy('emi_date','asc')->get();
        }
        $jobs = $jobs->orderBy('application_id','asc')->orderBy('emi_date','asc')->get();


        $Ledgers = [];
        $EMIs = [];
        foreach ($jobs as $job){
            $payload = json_decode($job->payload,1);
            if ($payload['type'] == 'LEDGER') {
                $Ledgers[] = $job;
            }else{
                $EMIs[] = $job;
            }
        }

        $response = [
            'Ledgers' => $Ledgers,
            'EMI' => $EMIs
        ];

        $id = [];
        $appIds = [];
        if ($jobs->count()) {
            foreach ($response as $jobs) {
                foreach ($jobs as $job) {
                    try {
                        if (!in_array($job->id, $appIds)) {
                            $appIds[] = $job->id;
                            $payload = json_decode($job->payload, 1);
                            $this->queue($job, $payload);
                            $job = null;
                            $serviceCount++;
                        }

                    } catch (\Exception $e) {

                        $this->sendOps($e->getMessage(), [$e->getFile(), $e->getLine(), $id]);
                        (new Slack(new Request(['title' => 'Tally Exception', 'fields' => ['m' => $e->getMessage(), 'f' => $e->getFile(), 'l' => $e->getLine(), 'id' => $id], 'group' => Slack::$TALLY_INTEGRATION])))->send();

                    }
                }
            }
        } else {
            return false;
        }

        return $serviceCount;
    }

    public function queue($job, $payload){
        switch ($job->from) {
            case 'TALLY_Communication':
                if($this->tallyListener($job, $payload)){
                    TallyJobs::where('id',$job->id)->update(['is_available' => 2]);
                }
                break;
        }
    }

    public function tallyListener($job, $payload){

        $status = false;

        try {

        $tally = new Tally(
            new Request([
                'job' => $job,
                'is_auto' => $this->isAuto
            ]),
            new TallyConnector()
        );

        if ($payload['type'] == 'EMI') {
            if ($this->autoTally = $tally->createEMIEntryV1($payload['tally'], $payload['id'], $payload['emiPaymentID'])) {
                $status = true;
            }
        }else if ($payload['type'] == 'LEDGER'){
            if ($tally->createMasters($payload['id'])) {
                $status = true;
            }
        }
        }catch (\Exception $e){
            $status = false;
        }

        return $status;
    }

    public function sendOps($error, $job){
        \Mail::send('emails.blank',
            ['body'=>$error,'job'=>$job]
            , function ($message) {
                $message->to('tech@creditfair.in')->subject('Error in queue');
                /*$message->cc(env('NOTIFY_EMAIL', ''));*/
            });
    }
}
