<?php
namespace App\Http\Controllers;
use Illuminate\Support\Collection;
use PDF;
use Mail;
use App\Mail\ReportMail;
use App\Models\Settings\Configuration;
use App\Models\Settings\State;
use App\Models\Facility\Facility;
use App\Models\Sales\ReportData;
use App\Helpers\ReportClass;
use App\Models\Sales\Invoice;
use App\Models\Sales\Transaction;
use App\Models\Sales\Ticket;
use App\Models\Sales\TicketSeat;
use App\Models\Sales\PaymentMethod;
use App\Models\Sales\PaymentType;
use App\Models\Sales\FeeWaiverApproval;
use App\Models\Sales\ShowCancel;
use App\Models\Sales\Refund;
use App\Models\Settings\ScheduleLog;


class StatusCheckController extends Controller
{
    public function checkstatus()
    {

        //$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',4197)->get();  ///for testing
       // dd($transactions);
        foreach($transactions as $transaction)
        {

            $transaction_id = $transaction->id;
            $mid = $transaction->mid;
            $encykey = $transaction->enckey;
            $order_id = $transaction->order_id;

            if(!$transaction->transaction_req_date || $transaction->transaction_req_date=='NA')
                $transaction->transaction_req_date = $transaction->created_at;

            echo $transaction->transaction_req_date;

            $transaction_req_date = date('d-m-Y',strtotime($transaction->transaction_req_date));
            $checkcount = $transaction->checkcount;
            if(!$checkcount)
                $checkcount = 0;

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

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

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

            $reconciliationData = json_decode($result, true);
            dd($reconciliationData);

        }


    }

    public function checkrefundtest()
    {
        $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)->where('id',55)->get();
        foreach($refunds as $refund)
        {
            echo $refund_id = $refund->id;
            $invoice_id = $refund->invoice_id;
            $invoices = Invoice::where('id',$invoice_id)->where('status',2)->first();//cancelled invoice
            //dd($invoices);
            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;
                
                echo $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();
        } 
    }
    
}
