<?php
require_once __DIR__ . '/vendor/autoload.php';
$config = json_decode(file_get_contents(__DIR__ . '/data/config.json'), true);
$ucrmOptions = [
    'base_uri' => 'https://localhost/crm/api/v1.0/',
    'verify' => false,
    'headers' => [
        'X-Auth-App-Key' => $config['apitoken'],
        'Content-Type' => 'application/json'
    ]
];
$ucrmClient = new \GuzzleHttp\Client($ucrmOptions);

// Fetch client 157
$res = $ucrmClient->get('clients/157');
$client = json_decode($res->getBody()->getContents(), true);
$stripeCustomerId = null;
foreach ($client['attributes'] as $attr) {
    if (stripos($attr['name'], 'Stripe') !== false && stripos($attr['name'], 'Customer') !== false) {
        $stripeCustomerId = $attr['value'];
    }
}
if (!$stripeCustomerId) {
    foreach ($client['attributes'] as $attr) {
        if ($attr['key'] === 'stripeCustomerId' || $attr['key'] === 'customerIdStripe') {
            $stripeCustomerId = $attr['value'];
        }
    }
}
echo "Stripe Customer ID: $stripeCustomerId\n";

if ($stripeCustomerId && isset($config['tokenstripe'])) {
    $stripeOptions = [
        'base_uri' => 'https://api.stripe.com/v1/',
        'auth' => [$config['tokenstripe'], ''],
    ];
    $stripeClient = new \GuzzleHttp\Client($stripeOptions);
    $res = $stripeClient->get("payment_intents?customer=$stripeCustomerId&limit=3");
    $intents = json_decode($res->getBody()->getContents(), true);
    foreach ($intents['data'] as $intent) {
        echo "PaymentIntent: {$intent['id']}, Amount: {$intent['amount']}, Status: {$intent['status']}, Types: " . implode(',', $intent['payment_method_types']) . "\n";
        echo "Metadata: " . json_encode($intent['metadata']) . "\n";
    }
}
