<?php

/*
 * ==========================================================
 * STRIPE.PHP
 * ==========================================================
 *
 * Process Stripe payments
 *
 */

header('Content-Type: application/json');
$raw = file_get_contents('php://input');
$response = json_decode($raw, true);

if ($response && empty($response['error']) && !empty($response['id'])) {
    require('functions.php');
    $metadata = crpay_isset($response['data']['object'], 'metadata');
    if ($metadata && isset($metadata['source']) && $metadata['source'] === 'cryptopayment') {
        if (CRPAY_CLOUD) {
            if (isset($metadata['cloud'])) {
                $_POST['cloud'] = $metadata['cloud'];
                crpay_cloud_load();
            } else {
                die();
            }
        }
        $response = crpay_stripe_curl('events/' . $response['id'], 'GET');
        $data = $response['data']['object'];
        switch ($response['type']) {
            case 'checkout.session.completed':
                $transaction = crpay_transactions_get($data['client_reference_id']);
                if ($transaction) {
                    crpay_transactions_complete($transaction, $data['amount_total'] / crpay_stripe_get_divider($transaction['currency']), $data['customer']);
                    if (CRPAY_CLOUD) {
                        crpay_cloud_spend_credit($data['amount_total'] / crpay_stripe_get_divider($transaction['currency']), $transaction['currency']);
                    }
                }
                break;
        }
    }
}

?>