<?php

namespace App\Tally;

use App\Slack;
use Carbon\Carbon;
use Illuminate\Http\Request;

class TallyListener{

    public static $port = 9000;
    public static $endPoint = 'http://120.63.204.17:';
    private $curRequest;
    //public static $companyName = 'Pride Financial Private Limited';
    public static $companyName = 'K M Global Credit Pvt Ltd';
    public $request;
    public static $creditorAndDebtors;
    public static $voucher;
    private $response;
    public $settlement_id = null;
    public $subvention_only = null;


    public function __construct(Request $request){
        $this->request = $request;
        $voucher = $this->request->get('voucher');
        if (isset($voucher->lender_id) && $voucher->lender_id == 1){
            static::$companyName = 'Pride Financial Private Limited';
        }
    }

    public static function setCreditors($ledgerName, $amount, $allocation = array()){
        $creditors = [
            'ledgerName' => $ledgerName,
            'amount' => $amount,
            'sundry' => 'CR',
            'voucher' => null
        ];

        foreach ($allocation as $key=>$value){
            $creditors = array_merge($creditors, [
                $key => $value
            ]);
        }

        static::$creditorAndDebtors[] = (object)$creditors;
    }

    public static function setDebtors($ledgerName, $amount, $allocation = array()){
        $debtors = [
            'ledgerName' => $ledgerName,
            'amount' => $amount,
            'sundry' => 'DR',
            'voucher' => null
        ];

        foreach ($allocation as $key=>$value){
            $debtors = array_merge($debtors, [
                $key => $value
            ]);
        }

        static::$creditorAndDebtors[] = (object)$debtors;
    }

    public function createLedger(){
        $ledger = new Ledger($this->request);
        $this->curRequest = $ledger->getLedger();
        return $this->import();
    }

    public function createJournalVoucher(){
        if(!$this->subvention_only) {
            if ($this->request->has('payments') && !empty($this->request->get('payments'))) {
                $journalVoucher = new JournalVoucher($this->request);
                $this->curRequest = $journalVoucher->getJournalVoucher();
                $this->response = $this->import();
            }
            if ($this->request->has('bank') && !empty($this->request->get('bank'))) {
                $this->response = $this->bankEntry();
            }
            if ($this->request->has('subvention') && !empty($this->request->get('subvention'))) {
                $this->response = $this->subventionEntry();
            }
            if ($this->request->has('processing_fee') && !empty($this->request->get('processing_fee'))) {
                $this->response = $this->processingFeeEntry();
            }
        }else{
            if ($this->request->has('subvention') && !empty($this->request->get('subvention'))) {
                $this->response = $this->subventionEntry();
            }
        }

        return $this->response;
    }

    public function createPaymentEntry(){
        $bank = new Payment($this->request);
        $this->curRequest = $bank->getPaymentEntry();
        return $this->import();
    }

    public function subventionEntry(){
//        (new Slack(new Request(['title' => 'Tally Settlement - Log 3', 'fields' => ['status' => 'in voucher function'], 'group'=>Slack::$TALLY_INTEGRATION])))->send();
        $bank = new JournalVoucher($this->request->merge(['payments' => $this->request->get('subvention')]));
        $this->curRequest = $bank->getJournalVoucher();
        if ($this->request->get('return_type') == 'xml'){
            return $this->curRequest;
        }
        return $this->import();
    }

    public function processingFeeEntry(){
        $bank = new ProcessingFee($this->request);
        $this->curRequest = $bank->getBankEntry();
        return $this->import();
    }

    public function bankEntry(){
        $bank = new Bank($this->request);
        $this->curRequest = $bank->getBankEntry();
        return $this->import();
    }

    public function import(){

        /*$fileURL = storage_path() . "/tally/may" . time() . ".xml";
        $file = fopen($fileURL, "w") or die("Unable to open file!");
        fwrite($file, $this->curRequest);
        fclose($file);
        return true;*/

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_PORT => _env('TALLY_PORT'),
            CURLOPT_URL => _env('TALLY_CONNECTION'),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $this->curRequest,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/x-www-form-urlencoded",
                "cache-control: no-cache"
            ),
        ));

        $response = curl_exec($curl);

        try{
            $myfile = fopen("tally_".Carbon::now()->toDateString().".txt", "a") or die("Unable to open file!");
            $txt = $response;
            fwrite($myfile, "\n". $this->curRequest);
            fwrite($myfile, "\n". $txt);
            fclose($myfile);
        }catch (\Exception $e){

        }

        $response = simplexml_load_string($response);

        $err = curl_error($curl);

        curl_close($curl);

        if (!$err && isset($response->CREATED) && $response->CREATED == 1){
            return true;
        }else{
            //$this->import();
            if (isset($response->LINEERROR) && !strpos((string)$response->LINEERROR, 'already exists!') !== false){
                (new Slack(new Request(['title' => 'Settlement Failed', 'fields' => ['message' => (string)$response->LINEERROR, 'settlement id' => $this->settlement_id, 'ledger id' => $this->request->has('voucher') ? $this->request->get('voucher')->id : 'None'], 'group' => Slack::$TALLY_INTEGRATION])))->send();
            }
            return false;
        }
    }
}
