<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GoCardlessPro;
use Carbon\Carbon;

use App\GocardlessSubscriptions;
use App\GocardlessCustomers;
use App\Transactions;
use App\Invoice;
use App\SubscriptionEvent;


use DB;

class GocardlessController extends Controller {

    public function remote(Request $request) {

        $webhook_endpoint_secret = "-JW5gFGnB9vJ1kGPbma_OvL1Oqx-zLiwh5HLIhsZ";

        $request_body = file_get_contents('php://input');

        $headers = getallheaders();
        $signature_header = $headers["Webhook-Signature"];
        echo $request_body;
        die;
        try {
            $events = gocardless()->environment()->parse($request_body, $signature_header, $webhook_endpoint_secret);
            echo json_encode($events);
            foreach ($events as $event) {
                // You can access each event in the webhook.
                echo($event->id);
            }

            header("HTTP/1.1 200 OK");
        } catch (GoCardlessPro\Core\Exception\InvalidSignatureException $e) {
            echo $e->getMessages();
            // The webhook doesn't appear to be genuinely from GoCardless, as the signature
            // included in the `Webhook-Signature` header doesn't match the one computed with
            // your webhook endpoint secret and the body
            header("HTTP/1.1 498 Invalid Token");
        }
    }

    public function events(Request $request) {


        $temp = [];
        $temp1 = [];

        $actions = [];

        try {

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

            $success = false;

            $gocardless_subscription = false;

            $transaction = '';

            $linkObject = '';

            $events = gocardless()->events()->all(["params" => ["created_at[gt]" => $date1 ]]); 
            
            $i = 0;

            $subs = 0; 
            
            $trans = 0;
            
            foreach ($events as $event) {

               

                $i++;

                $e = gocardless()->events()->get($event->id);     
                
                // $temp['actions'][] = $e->action;
                // $temp['resource_type'][] = $e->resource_type;



                if($e->resource_type == 'subscriptions'){  

                    $linkObject = $e->links->subscription;

                    $temp['subscriptions'][] = $linkObject ;

                }  

                else if($e->resource_type == 'payments'){  

                    $linkObject = $e->links->payment;

                    $temp['payments'][] = $linkObject ;

                }  

                else if($e->resource_type == 'payouts'){  

                    $linkObject = $e->links->payout;    

                    $temp['payouts'][] = [ 'Event Id' => $e->id, 'Link Id' => $linkObject ,'data' => $e] ;

                }

                $gocardless_subscription = GocardlessSubscriptions::where('subscription',$linkObject)->first(); 


                if($e->resource_type == 'mandates'){  

                    $linkObject = $e->links->mandate;

                    $temp['mandates'][] = $linkObject ;

                    $gocardless_subscription = GocardlessCustomers::where('mandate',$linkObject)->first();

                }  

                if( $gocardless_subscription ){

                    $temp['withSubscriptions'] = $subs++ ;

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

                    

                    if( $transaction ){

                        $temp['withTransactions'] = $trans++ ;

                        $exists = SubscriptionEvent::where('eventId',$event->id)->first();
                        
    
                                if(!$exists){
            
                                        $transaction = Transactions::where('subscription_id',$gocardless_subscription->id)->where('paymentMethod','direct_debit')->first();  
        
                                        $params = [
        
                                            'action' => $e->action,
                                            'eventId' => $event->id, 
                                            'customer_id' => $transaction->customer_id,
                                            'transaction_id' => $transaction->id,
                                            'customerId' => $linkObject,
                                            'payment_method' => $transaction->paymentMethod,
                                            'body' => $e->api_response->body->events
        
                                        ];
                                        $temp['EventData'][]  = $saved = SubscriptionEvent::create($params);
                                        
                                
                //                 if($e->resource_type == 'payouts'){
                                    
                //                     $params=[            
                                    
                //                         'invoiceNumber' => 'HF-00',
                //                         'event_id' =>  $saved->id, 
                //                         'customer_id' => $transaction->customer_id,
                //                         'transaction_id' => $transaction->id,
                //                         'status' => 1,
                //                         'amount' => 5.00,
                //                         'netAmount' => 7.00,
                //                         'chargeFee' => 1.00,
                //                         'chargeDate' => now(),            
            
                //                     ];
                //                     d($params);
                //                    die;
                                        
                //                    $temp1[] = Invoice::create($params);


                        }
                    }
                }
            }

            return [

                'Total Record' => $i,
                'EventCount' => count($temp),
                'data' => $temp,

                // 'IvoicesCreated' => count($temp1) , 
            ];
            

        } catch (GoCardlessPro\Core\Exception\InvalidSignatureException $e) {
            echo $e->getMessages();
            // The webhook doesn't appear to be genuinely from GoCardless, as the signature
            // included in the `Webhook-Signature` header doesn't match the one computed with
            // your webhook endpoint secret and the body
            header("HTTP/1.1 498 Invalid Token");
        }
    }



    public function cancelled(Request $request) {

        try {
            $events = gocardless()->events()->all(["params" => ["created_at[gt]" => "2021-06-28T00:00:00.000Z"]]);
            //"action" => "created","resource_type" => "mandates"
            ///d($events,1);


            foreach ($events as $event) {
                $e = gocardless()->events()->get($event->id);

                   //if($e->resource_type == 'payouts'){                    

                        dump($e);

                    //}

             
                
            }

            // header("HTTP/1.1 200 OK");
        } catch (GoCardlessPro\Core\Exception\InvalidSignatureException $e) {
            echo $e->getMessages();
            // The webhook doesn't appear to be genuinely from GoCardless, as the signature
            // included in the `Webhook-Signature` header doesn't match the one computed with
            // your webhook endpoint secret and the body
            header("HTTP/1.1 498 Invalid Token");
        }
    }

    public function getLinkObject($e)
    {

        switch ($e->resource_type) {
            case "subscriptions":
              return $e->links->subscription;
              break;
            case "payments":
              return $e->links->payment;
              break;
            case "payouts":
              return $e->links->payout;
              break;
            default:
                return $e->links->mandate ?? '';
          }
    }

}
