<?php
// check_purchase_status.php — Polling endpoint called every 2s from my_purchases.php
ob_start();
require_once '../config/database.php';
require_once '../includes/functions.php';
if (session_status() === PHP_SESSION_NONE) session_start();

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

function jsonOut($d){ ob_end_clean(); echo json_encode($d); exit; }

if (!isset($_SESSION['user_id'])) {
    jsonOut(['completed' => false, 'pending_count' => 0, 'error' => 'not_logged_in']);
}

$userId = intval($_SESSION['user_id']);
$conn   = getConnection();

// ── Step 1: Fix any product_purchases stuck as 'pending' when transaction is 'completed'
// Use checkout_request_id to join — no JSON_EXTRACT needed
$fixStmt = $conn->prepare("
    UPDATE product_purchases pp
    INNER JOIN transactions t ON t.reference = pp.checkout_request_id
    SET pp.status       = 'completed',
        pp.purchased_at = COALESCE(pp.purchased_at, NOW()),
        pp.download_token = CASE
            WHEN pp.download_token IS NULL OR pp.download_token = ''
            THEN SHA2(CONCAT(pp.id, pp.user_id, NOW(), RAND()), 256)
            ELSE pp.download_token
        END
    WHERE pp.user_id   = ?
      AND pp.status    = 'pending'
      AND t.status     = 'completed'
      AND t.user_id    = ?
");
$fixStmt->bind_param("ii", $userId, $userId);
$fixStmt->execute();
$fixed = $fixStmt->affected_rows;

// ── Step 2: Also fix via meta_json purchase_id as fallback
// Get all completed transactions for this user of type product_purchase
$txStmt = $conn->prepare("
    SELECT id, meta_json, reference FROM transactions
    WHERE user_id = ? AND type = 'product_purchase' AND status = 'completed'
");
$txStmt->bind_param("i", $userId);
$txStmt->execute();
$txRows = $txStmt->get_result()->fetch_all(MYSQLI_ASSOC);

foreach ($txRows as $tx) {
    $meta = json_decode($tx['meta_json'] ?? '{}', true);
    $purchaseId = intval($meta['purchase_id'] ?? 0);
    if (!$purchaseId) continue;

    // Check if this purchase is still pending
    $chk = $conn->prepare("SELECT id, status, download_token FROM product_purchases WHERE id=? AND user_id=? LIMIT 1");
    $chk->bind_param("ii", $purchaseId, $userId);
    $chk->execute();
    $row = $chk->get_result()->fetch_assoc();

    if ($row && $row['status'] === 'pending') {
        $token = !empty($row['download_token']) ? $row['download_token']
               : hash('sha256', $purchaseId . $userId . time() . rand());
        $upd = $conn->prepare("
            UPDATE product_purchases
            SET status='completed', purchased_at=COALESCE(purchased_at, NOW()), download_token=?
            WHERE id=? AND user_id=?
        ");
        $upd->bind_param("sii", $token, $purchaseId, $userId);
        $upd->execute();
        $fixed += $upd->affected_rows;
    }
}

// ── Step 3: Count current state
$countStmt = $conn->prepare("
    SELECT
        SUM(status='pending')   as pending_count,
        SUM(status='completed') as completed_count
    FROM product_purchases WHERE user_id=?
");
$countStmt->bind_param("i", $userId);
$countStmt->execute();
$counts = $countStmt->get_result()->fetch_assoc();

$pendingCount   = intval($counts['pending_count']   ?? 0);
$completedCount = intval($counts['completed_count'] ?? 0);

ob_end_clean();
echo json_encode([
    'completed'       => ($fixed > 0),   // true only if we just fixed something new
    'pending_count'   => $pendingCount,
    'completed_count' => $completedCount,
    'fixed'           => $fixed,
    'items'           => $fixed > 0 ? [['fixed' => true]] : [],
]);