<?php

namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\Sales\Invoice;
use App\Models\Sales\Transaction;
use App\Models\Sales\Ticket;
use App\Models\Sales\TicketSeat;
use App\Models\Settings\ScheduleLog;
use App\Helpers\BookingClass;
use App\Models\PublicUser;
use App\Models\Mail\MailTicket;

class TransactionStatusCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'transactionstatus:cron';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This command will check the status of the transactions';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $checkcount = 0;
        $todaytime = date("Y-m-d H:i:s");
        $insertobj_scheduler = ScheduleLog::create([
            'command' => 'transactionstatus:cron',
            'command_log' => "transaction scheduler started at ".$todaytime,
            'starttime' => $todaytime,
            'status' => 0,
        ]);
        $scheudleid = $insertobj_scheduler->id;

        //get current time
        $time = time();
        $ticket_time_out = 10; //10 minutes
        $time = $time - ($ticket_time_out*60); //get current time minus 10 minutes or else it may be a current transaction which is not yet over
        $checktime = date("Y-m-d H:i:s", $time);
      

        ////////////////////////////////////////////////////////////////////////////
        $transactions = Transaction::where('status',0)->where('status_code',NULL)->where('checkcount','<',3)->whereNotNull('public_user_id')->whereNotNull('order_id')->where('created_at','<=',$checktime)->get();
        //dd($transactions);
        //$transactions = Transaction::where('id',52)->get();  ///for testing
        foreach($transactions as $transaction)
        {
            echo $transaction_id = $transaction->id;
            $mid = $transaction->mid;
            $encykey = $transaction->enckey;
            $order_id = $transaction->order_id;
            $checkcount = $transaction->checkcount;
            if(!$checkcount)
                $checkcount = 0;


            //generate merchant request 
            /*include 'public/worldline/AWLMEAPI.php';
            //generate merchant request from Helper file
            //create an Object of the above included class
            $obj = new \AWLMEAPI();
            //create an object of response Message
            $pgMeTrnRefNo = '';
            $resMsgDTO = $obj->getTransactionStatus($mid , $order_id , $pgMeTrnRefNo , $encykey);
            $trnsrefno = $resMsgDTO->getPgMeTrnRefNo();
            $trnsamount = $resMsgDTO->getTrnAmt();
            $trnsstatuscode = $resMsgDTO->getStatusCode();
            $trnsstatusdesc = $resMsgDTO->getStatusDesc();
            $trnsreqdate = $resMsgDTO->getTrnReqDate();
            $trnsresponsecode = $resMsgDTO->getResponseCode();
            $trns_rrn = $resMsgDTO->getRrn();
            $trnsauthzcode = $resMsgDTO->getAuthZCode();*/

            if(!$transaction->transaction_req_date || $transaction->transaction_req_date=='NA')
                $transaction->transaction_req_date = $transaction->created_at;
            
            $transaction_req_date = date('d-m-Y',strtotime($transaction->transaction_req_date));
            

            $currency = config('worldline.currency');

            $arr_req = array(
                "merchant" => [
                    "identifier" => $mid
                ],
                "transaction" => [ "deviceIdentifier" => "S", "currency" => $currency, "identifier" => $order_id, "dateTime" => $transaction_req_date, "requestType" => "O"]
            );

            $finalJsonReq = json_encode($arr_req);

            $method = 'POST';
            $url = "https://www.paynimo.com/api/paynimoV2.req";

            $curl = curl_init();
            switch ($method){
                  case "POST":
                     curl_setopt($curl, CURLOPT_POST, 1);
                     if ($finalJsonReq)
                        curl_setopt($curl, CURLOPT_POSTFIELDS, $finalJsonReq);
                     break;
                  case "PUT":
                     curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
                     if ($finalJsonReq)
                        curl_setopt($curl, CURLOPT_POSTFIELDS, $finalJsonReq);                              
                     break;
                  default:
                     if ($finalJsonReq)
                        $url = sprintf("%s?%s", $url, http_build_query($finalJsonReq));
            }
            // OPTIONS:
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
               'Content-Type: application/json',
            ));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            // EXECUTE:
            echo $result = curl_exec($curl);


            if(!$result){die("Connection Failure !! Try after some time.");}
            curl_close($curl);

            $result = json_decode($result, true);

            

            if($result)
            {
                $trnsrefno = $result["paymentMethod"]["paymentTransaction"]["identifier"];
                $trnsamount = $result["paymentMethod"]["paymentTransaction"]["amount"];
                $trnsstatuscode = $result["paymentMethod"]["paymentTransaction"]["statusMessage"];
                $trnsstatusdesc = $result["paymentMethod"]["paymentTransaction"]["errorMessage"];
                $trnsreqdate = $result["paymentMethod"]["paymentTransaction"]["dateTime"];
                $trnsresponsecode = $result["paymentMethod"]["paymentTransaction"]["statusCode"];
                $trns_rrn = $result["paymentMethod"]["paymentTransaction"]["statusCode"];
                $trnsauthzcode = $result["paymentMethod"]["paymentTransaction"]["reference"];

            }



            //dd($trnsstatuscode);
            /////////
            $invoice_id = "";
            $invocies = "";
            if(($result["paymentMethod"]["paymentTransaction"]["statusCode"] == '0300') || ($result["paymentMethod"]["paymentTransaction"]["statusMessage"] == 'SUCCESS'))
            {
                $checkcount++;
                ///update transaction table
                $transaction_upd = Transaction::where('id',$transaction_id)->first();
                $transaction_upd->status = 1;
                $transaction_upd->transaction_refno = $trnsrefno;
                $transaction_upd->status_code = $trnsstatuscode;
                $transaction_upd->status_desc = $trnsstatusdesc;
                $transaction_upd->transaction_req_date = $trnsreqdate;
                $transaction_upd->response_code = $trnsresponsecode;
                $transaction_upd->rrn = $trns_rrn;
                $transaction_upd->auth_zcode = $trnsauthzcode;
                $transaction_upd->checkcount = $checkcount;
                $transaction_upd->save();
                ////update invoice table
                //echo "transaction_id=$transaction_id..<br>";
                $invoices = Invoice::where('transaction_id',$transaction_id)->first();
                if(isset($invoices))
                {
                    if($invoices->id)
                        $invoice_id = $invoices->id;
                    if($invoice_id)
                    {
                        $invoices->status = 1;
                        $invoices->save();
                    }

                    $invoice_no = $invoices->invoice_no;
                     if(!$invoice_no)
                     {
                        $organisation_id = $invoices->organisation_id;
                        $booking = new BookingClass;
                        $invoicearr = $booking->getnewInvoice($organisation_id);
                        $invoice_no = $invoicearr[0];
                        $invoice_time = $invoicearr[1];
                        $invoices->invoice_no = $invoice_no;
                        $invoices->invoice_time = $invoice_time;
                        $invoices->save();
                     }
                }
                if($invoice_id)
                {
                    ////update ticket table
                    $ticekts = Ticket::where('invoice_id',$invoice_id)->get();
                    foreach($ticekts as $ticket)
                    {
                        $ticket_id = $ticket->id;
                        $ticket_upd = Ticket::where('id',$ticket_id)->first();
                        //check if there is ticket_no
                        $ticket_no = $ticket_upd->ticket_no;
                        if(!$ticket_no)
                        {
                            $facility_id = $ticket_upd->facility_id;
                            $booking = new BookingClass;
                            $ticketno = $booking->getnewTicket($facility_id);
                            $ticket_upd->ticket_no = $ticketno;
                        }
                        $ticket_upd->status = 1;
                        $ticket_upd->save();
                        ////update ticket seat table
                        $ticket_seats = TicketSeat::where('ticket_id',$ticket_id)->get();
                        foreach($ticket_seats as $ticket_seat)
                        {
                            $ticket_seat_id = $ticket_seat->id;
                            $ticket_seat_upd = TicketSeat::where('id',$ticket_seat_id)->first();
                            $ticket_seat_upd->status = 1;
                            $ticket_seat_upd->save();
                        }
                    }
                }

                //send mail
                if($invoice_id)
                {
                    $public_user_id = $invoices->public_user_id;

                    $userobj = PublicUser::where('id',$public_user_id)->first();
                    if(isset($userobj))
                    {
                        $email = $userobj->email;
                    
                        $mailobj = MailTicket::create([
                            'email' => $email,
                            'invoice_id' => $invoice_id,
                            'status' => 0,
                            'public_user_id' => $public_user_id,
                            'mail_type' => 1
                        ]);
 
                    }

                    

                }

            }
            if(($result["paymentMethod"]["paymentTransaction"]["statusMessage"] == 'FAILED') || ($result["paymentMethod"]["paymentTransaction"]["statusCode"] == '9999') || ($result["paymentMethod"]["paymentTransaction"]["statusMessage"] == 'ABORTED'))
            {
                $checkcount++;
                ///update transaction table
                $transaction_upd = Transaction::where('id',$transaction_id)->first();
                $transaction_upd->status = 2;
                $transaction_upd->transaction_refno = $trnsrefno;
                $transaction_upd->status_code = $trnsstatuscode;
                $transaction_upd->status_desc = $trnsstatusdesc;
                $transaction_upd->transaction_req_date = $trnsreqdate;
                $transaction_upd->response_code = $trnsresponsecode;
                $transaction_upd->rrn = $trns_rrn;
                $transaction_upd->auth_zcode = $trnsauthzcode;
                $transaction_upd->checkcount = $checkcount;
                $transaction_upd->save();
            }
        }  
        $todaytimeend = date("Y-m-d H:i:s");
        $scheudlerlogupd = ScheduleLog::where('id',$scheudleid)->where('status',0)->first();
        if(isset($scheudlerlogupd))
        {
            $scheudlerlogupd->status = 1;
            $scheudlerlogupd->endtime = $todaytimeend;
            $scheudlerlogupd->save();
        }
    }
}
