<?php
// live_test.php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/kindamba.php';

$phone = '0762817032';
$amount = 1000;
$name = 'Live Tester';
$email = 'tester@kindamba.site';
$videoID = 1; // Assuming a video with ID 1 exists

// Fetch admin token for test
$adminStmt = $pdo->query("SELECT api_key, webhook_token FROM users WHERE id = 1 LIMIT 1");
$admin = $adminStmt->fetch(PDO::FETCH_ASSOC);
$publicKey = $admin['api_key'] ?? KINDAMBA_PUBLIC_KEY;
$webhookToken = $admin['webhook_token'] ?? '';

$callbackUrl = SITE_URL . '/webhook.php?token=' . $webhookToken;
$externalId = 'LIVE-TEST-' . time();

echo "Initiating payment to $phone for $amount TZS...\n";
echo "Callback URL: $callbackUrl\n";
echo "Using Public Key: " . substr($publicKey, 0, 10) . "...\n";

$result = kindamba_initiate_payment($phone, $amount, $name, $email, $externalId, $callbackUrl, $publicKey);

echo "HTTP Code: " . $result['code'] . "\n";
echo "Response: " . json_encode($result['data'], JSON_PRETTY_PRINT) . "\n";

if ($result['code'] == 200 && isset($result['data']['data']['transaction_id'])) {
    $tid = $result['data']['data']['transaction_id'];
    echo "\nSUCCESS! Transaction ID: $tid\n";
    echo "Please complete the USSD on your phone (0762817032).\n";
    echo "Once paid, you can check the status by running: php check_test.php $tid\n";
    
    // Save to temp file for the check script
    file_put_contents('last_test_id.txt', $tid);
} else {
    echo "\nFAILED to initiate payment.\n";
}
