<?php
header('Content-Type: application/json');

// Enable error logging for debugging
error_log("get_purchases.php called");

// Get token from request
$headers = getallheaders();
$token = null;

// Check for token in Authorization header
if (isset($headers['Authorization'])) {
    $token = str_replace('Bearer ', '', $headers['Authorization']);
} else if (isset($_GET['token'])) {
    $token = $_GET['token'];
} else if (isset($_POST['token'])) {
    $token = $_POST['token'];
}

// If no token, try to read from request body
if (!$token) {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    if ($data && isset($data['token'])) {
        $token = $data['token'];
    }
}

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

// Verify token
try {
    $tokenData = json_decode(base64_decode($token), true);

    if (!$tokenData || !isset($tokenData["userId"]) || !isset($tokenData["exp"])) {
        echo json_encode(['success' => false, 'message' => 'Invalid token']);
        exit;
    }

    // Check expiration
    if ($tokenData["exp"] < time()) {
        echo json_encode(['success' => false, 'message' => 'Token expired']);
        exit;
    }

    $userId = $tokenData["userId"];
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Token verification failed']);
    exit;
}

// Use the API to get user info instead of decrypting directly
// This is simpler and more reliable
// Build absolute URL for the API call
$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']);
// For local development, disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$apiResponse = curl_exec($ch);
$curlError = curl_error($ch);
curl_close($ch);

if ($curlError) {
    error_log("cURL error: " . $curlError);
    echo json_encode(['success' => false, 'message' => 'API connection failed: ' . $curlError]);
    exit;
}

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

$apiResult = json_decode($apiResponse, true);

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

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

error_log("Retrieved user email via API: " . $userEmail);

// Define file paths
define('FORUM_PURCHASES_FILE', 'forum_purchases.json');
define('PRODUCTS_FILE', 'user_products.json');

// Function to load purchases
function getUserPurchases($email) {
    if (!file_exists(FORUM_PURCHASES_FILE)) {
        return [];
    }

    $purchases = json_decode(file_get_contents(FORUM_PURCHASES_FILE), true) ?: [];
    return $purchases[$email] ?? [];
}

// Function to load all products
function getAllProducts() {
    if (!file_exists(PRODUCTS_FILE)) {
        return [];
    }

    return json_decode(file_get_contents(PRODUCTS_FILE), true) ?: [];
}

// Get user's purchases
$userPurchases = getUserPurchases($userEmail);
error_log("Found " . count($userPurchases) . " purchases for user");

$allProducts = getAllProducts();
error_log("Loaded " . count($allProducts) . " products");

// Enrich purchases with product details
$enrichedPurchases = [];

foreach ($userPurchases as $purchase) {
    $productId = $purchase['product_id'];

    // Find product details
    $productDetails = null;
    foreach ($allProducts as $product) {
        if ($product['id'] === $productId) {
            $productDetails = $product;
            break;
        }
    }

    if ($productDetails) {
        $enrichedPurchases[] = [
            'product_id' => $productId,
            'transaction_id' => $purchase['transaction_id'],
            'purchase_date' => $purchase['purchase_date'],
            'status' => $purchase['status'],
            'product_name' => $productDetails['name'],
            'product_description' => $productDetails['description'] ?? '',
            'product_price' => $productDetails['price'],
            'owner_username' => $productDetails['owner_username'] ?? 'Unknown',
            'file_name' => $productDetails['file_name'] ?? 'download',
            'download_url' => "download.php?id={$productId}&transaction_id={$purchase['transaction_id']}&token=" . urlencode($token)
        ];
    } else {
        // Product not found, but include basic purchase info
        $enrichedPurchases[] = [
            'product_id' => $productId,
            'transaction_id' => $purchase['transaction_id'],
            'purchase_date' => $purchase['purchase_date'],
            'status' => $purchase['status'],
            'product_name' => 'Product Not Found',
            'product_description' => 'This product may have been removed',
            'product_price' => 'N/A',
            'owner_username' => 'Unknown',
            'file_name' => '',
            'download_url' => ''
        ];
    }
}

echo json_encode([
    'success' => true,
    'purchases' => $enrichedPurchases,
    'count' => count($enrichedPurchases)
]);
?>
