<?php
/**
* ChronoForms 8
* Copyright (c) 2023 ChronoEngine.com, All rights reserved.
* Author: (ChronoEngine.com Team)
* license:     GNU General Public License version 2 or later; see LICENSE.txt
* Visit http://www.ChronoEngine.com for regular updates and information.
**/
defined('_JEXEC') or die('Restricted access');
?>
<?php
if(file_exists($this->path.DS.'libs/stripe/init.php')){
	require_once($this->path.DS.'libs/stripe/init.php');
}else{
	echo 'Payments lib not found, you can download the Payments lib here: <a target="_blank" href="https://www.chronoengine.com/downloads/chronoforms/chronoforms-v8/">Chronoforms v8 downloads</a>';
	return;
}

use Stripe\Stripe;
use Stripe\Webhook;

// Set your Stripe secret key and webhook secret
$stripeSecretKey = $element["secret_key"]; // From Stripe Dashboard
$webhookSecret = $element["webhook_secret"]; // From Stripe Dashboard > Webhooks

if(empty($stripeSecretKey) || empty($webhookSecret)){
	echo "<div class='nui red alert'>Missing secret key</div>";
	return;
}

// Initialize Stripe with your secret key
Stripe::setApiKey($stripeSecretKey);

// Get the raw request body
$payload = @file_get_contents('php://input');

// Get the Stripe-Signature header
$sigHeader = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';

try {
    // Verify the webhook signature
    $event = Webhook::constructEvent(
        $payload,
        $sigHeader,
        $webhookSecret,
        300 // Tolerance in seconds (default: 300)
    );

    // Handle the event
    switch ($event->type) {
        case 'payment_intent.succeeded':
            $paymentIntent = $event->data->object; // Stripe\PaymentIntent
            // Example: Update your database or send a confirmation email
            http_response_code(200);

			$this->set(CF8::getname($element), $paymentIntent);

            // echo "Payment succeeded: " . $paymentIntent->id;
			if(!empty($element["custom_id_var"])){
				$this->set($element["custom_id_var"], $paymentIntent->metadata->custom_id);
			}

			$DisplayElements($elements_by_parent, $element["id"], "success");
            break;
        // Add other event types as needed
        default:
            http_response_code(200);
            // echo "Unhandled event type: " . $event->type;
			$this->set(CF8::getname($element), $event);
			$DisplayElements($elements_by_parent, $element["id"], "other");
            break;
    }
} catch (\Stripe\Exception\SignatureVerificationException $e) {
    // Invalid signature
    http_response_code(400);
    echo "<div class='nui red alert'>Webhook signature verification failed: " . $e->getMessage()."</div>";
    // exit;
} catch (\UnexpectedValueException $e) {
    // Invalid payload (e.g., not valid JSON)
    http_response_code(400);
    echo "<div class='nui red alert'>Invalid payload: " . $e->getMessage()."</div>";
    // exit;
}
?>