<?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\Sales\Refund;
use App\Models\Settings\ScheduleLog;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This command will check refunds and update the table';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $todaytime = date("Y-m-d H:i:s");
        $insertobj_scheduler = ScheduleLog::create([
            'command' => 'refundcheck:cron',
            'command_log' => "refundcheck scheduler started at ".$todaytime,
            'starttime' => $todaytime,
            'status' => 0,
        ]);
        $scheudleid = $insertobj_scheduler->id;
        ////////////////////////////////////////////////////////////////////////////
        $refunds = Refund::where('refund_status',0)->whereNotNull('public_user_id')->get();
        foreach($refunds as $refund)
        {
            $refund_id = $refund->id;
            $invoice_id = $refund->invoice_id;
            $invoices = Invoice::where('id',$invoice_id)->where('status',2)->first();//cancelled invoice
            if(isset($invoices))
            {
                //get current datetime
                $date = date('Y-m-d H:i:s');
                $newDate = date('Y-m-d H:i:s', strtotime($date. ' - 2 days'));
                $newDatestr = strtotime($newDate);

                $invoicetimestr = strtotime($invoices->invoice_time);

                //check if newDate is greater than invoice time
                if($newDatestr<$invoicetimestr)
                    continue;
                
                $transaction_id = $invoices->transaction_id;
                $status ="";
                $transaction = Transaction::where('id',$transaction_id)->where('status',1)->first();
                //dd($transaction);
                if(isset($transaction))
                {
                    $mid = $transaction->mid;
                    $encykey = $transaction->enckey;
                    $order_id = $transaction->order_id;
                    $response_url = $transaction->response_url;
                    $transaction_refno =$transaction->transaction_refno;
                    $status_code =$transaction->status_code;
                    $status_desc = $transaction->status_desc;
                    echo $amount = $refund->refund_amount;
                    //$paisaamt = $amount*100;
                    $transaction_req_date = date('d-m-Y',strtotime($transaction->transaction_req_date));

                    $currency = config('worldline.currency');
                    $arr_req = array(
                        "merchant" => [
                            "identifier" => $mid
                        ],
                        "cart" => [ "" => ""
                        ],
                        "transaction" => [ "deviceIdentifier" => "S", "amount" => $amount, "currency" => $currency, "dateTime" => $transaction_req_date, "token" => $transaction_refno, "requestType" => "R"]
                    );

                    echo $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);

                   $refundData = json_decode($result, true);
                   $refundstatuscode = $refundData["paymentMethod"]["paymentTransaction"]["statusCode"];
                   $refundstatusmessage = $refundData["paymentMethod"]["paymentTransaction"]["statusMessage"];


                    

                    ///update refund table/////
                    $refund_upd = Refund::where('id',$refund_id)->first();
                    $refund_upd->order_id = $order_id;
                    $refund_upd->transaction_refno = $transaction_refno;
                    $refund_upd->status_code = $refundstatuscode;
                    $refund_upd->status_desc = $refundstatusmessage;

                    
                    if($refundstatuscode=="0400")
                    {
                        $status = 1;
                    }
                    else
                    {
                        $status = 2;
                    }
                    $refund_upd->status_code = $refundstatuscode;
                    $refund_upd->refund_status = $status;
                    $refund_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();
        } 
    }
}
