<?php
// record_purchase.php - Manual purchase recording for testing
header('Content-Type: application/json');

// Get POST data
$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['product_id']) || !isset($data['transaction_id'])) {
    die(json_encode(['success' => false, 'message' => 'Missing required fields']));
}

$productId = $data['product_id'];
$transactionId = $data['transaction_id'];

// Get token from request
$token = null;
if (isset($data['token'])) {
    $token = $data['token'];
}

$headers = getallheaders();
if (!$token && isset($headers['Authorization'])) {
    $token = str_replace('Bearer ', '', $headers['Authorization']);
}

if (!$token) {
    die(json_encode(['success' => false, 'message' => 'Not authenticated - no token provided']));
}

// Verify token and get user email using the API
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$baseDir = dirname($_SERVER['SCRIPT_NAME']);
$apiUrl = $protocol . '://' . $host . $baseDir . '/api.php?action=validate_token';

$apiData = json_encode(['token' => $token]);

$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $apiData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$apiResponse = curl_exec($ch);
curl_close($ch);

if (!$apiResponse) {
    die(json_encode(['success' => false, 'message' => 'Failed to validate token']));
}

$apiResult = json_decode($apiResponse, true);

if (!$apiResult || !$apiResult['success']) {
    die(json_encode(['success' => false, 'message' => 'Invalid token']));
}

$user = $apiResult['user'];
$userEmail = $user['email'];

// Define files
$forumPurchasesFile = 'forum_purchases.json';
$productsFile = 'user_products.json';

// Load forum purchases
$purchases = [];
if (file_exists($forumPurchasesFile)) {
    $purchases = json_decode(file_get_contents($forumPurchasesFile), true) ?: [];
}

// Initialize user's purchases array if not exists
if (!isset($purchases[$userEmail])) {
    $purchases[$userEmail] = [];
}

// Check if already purchased
$exists = false;
foreach ($purchases[$userEmail] as $purchase) {
    if ($purchase['product_id'] === $productId) {
        $exists = true;
        break;
    }
}

if ($exists) {
    echo json_encode(['success' => false, 'message' => 'Product already purchased']);
    exit;
}

// Add purchase
$purchases[$userEmail][] = [
    'product_id' => $productId,
    'transaction_id' => $transactionId,
    'purchase_date' => date('Y-m-d H:i:s'),
    'status' => 'completed'
];

// Save purchases
if (file_put_contents($forumPurchasesFile, json_encode($purchases, JSON_PRETTY_PRINT))) {
    echo json_encode([
        'success' => true,
        'message' => 'Purchase recorded successfully',
        'email' => $userEmail,
        'product_id' => $productId
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to save purchase']);
}
?>
