<?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)
        {
            $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();*/

            $url = "http://159.89.167.203/worldline/transactioncheck.php?orderId=".$order_id."&mId=".$mid."&enc_key=".$encykey;
    
            $client = curl_init($url);

            

            curl_setopt($client, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Accept: application/json'
            ));

            curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
            $response = curl_exec($client);

            curl_close($client);
            
            $result = json_decode($response);

            if($result)
            {
                $trnsrefno = $result[0];
                $trnsamount = $result[1];
                $trnsstatuscode = $result[2];
                $trnsstatusdesc = $result[3];
                $trnsreqdate = $result[4];
                $trnsresponsecode = $result[5];
                $trns_rrn = $result[6];
                $trnsauthzcode = $result[7];

            }



            //dd($trnsstatuscode);
            /////////
            $invoice_id = "";
            $invocies = "";
            if($trnsstatuscode=="S")
            {
                $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($trnsstatuscode=="F")
            {
                $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();
        }
    }
}
