<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\StripeEvent;
use App\SubscriptionEvent;
use App\Transactions;

class StripeEventController extends Controller
{
   public function events()
   {
    try {

        // $date = date('Y-m-d')."T00:00:00.000Z";
        // $date1 = "2021-06-28T00:00:00.000Z";

        //  $success = false;
        //  $gocardless_subscription = false;

        \Stripe\Stripe::setApiKey(env("STRIPE_SECRET"));

        $stripe = \Stripe\Event::all();

        $success = false;

        foreach($stripe as $row){

                    $exists = SubscriptionEvent::where('eventId',$row->id)->first();
    
                        if(!$exists){
                            
                                $subscription = StripeEvent::where('stripe_id',$row['data']['object']['id'])->first();

                                if($subscription){                                    

                                    $transaction = Transactions::where('subscription_id',$subscription->id)->where('paymentMethod','credit_card')->first();  

                                    $arr = [
                                        'action' => $row['object'] ?? '',
                                        'eventId' => $row->id, 
                                        'customer_id' => $transaction->customer_id ?? '',
                                        'transaction_id' => $transaction->id ?? '',
                                        'customerId' => $row['data']['object']['id'] ?? '',
                                        'payment_method' => $transaction->paymentMethod ?? '',
                                        'body' => $row['data']['object']['items']['data']
                                    ];

                                    $success = SubscriptionEvent::create($arr);

                                }                              
                                
                        }
                        return $success ? 'success' : 'error';

        }

       

        
    } catch (Stripe\Exception\InvalidRequestException $e) {

    }
   }

        


}
