<?php
require '../conn.php';

$q = $mysqli->query("SELECT * FROM pending_tx WHERE status = 'pending'");

if (!$q) {
    error_log("Error fetching pending_tx: " . $mysqli->error);
    exit;
}

while ($row = $q->fetch_assoc()) {
    $tx_id = $row['tx_id'];
    $email = $row['email'];
    $type = $row['type'];

    $u = getUserInfo($email);
    if (empty($u)) {
        $stmt = $mysqli->prepare("DELETE FROM pending_tx WHERE tx_id = ?");
        $stmt->bind_param("s", $tx_id);
        $stmt->execute();
        $stmt->close();
        continue;
    }

    try {
        $response = $client->request('POST', $vtpBase . 'requery', [
            'headers' => [
                'Content-Type' => 'application/json',
                'secret-key' => $vtpSecKey,
                'api-key'    => $vtpApiKey,
            ],
            'body' => json_encode(["request_id" => $tx_id]),
        ]);

        $res = json_decode($response->getBody(), true);

        // === DELIVERED ===
        if (
            isset($res['code']) && $res['code'] === "000" &&
            $res['content']['transactions']['status'] === "delivered"
        ) {
            $payload = $mysqli->real_escape_string(json_encode($res));

            // Update transaction
            $stmt = $mysqli->prepare("UPDATE transactions SET status = 'Complete', payload = ? WHERE our_ref = ?");
            $stmt->bind_param("ss", $payload, $tx_id);
            $stmt->execute();
            $stmt->close();

            // Send email
            $name = $u['first_name'] ?? '';
            $subject = 'Transaction Processed';
            $emailMessage = "<p>Hello $name,</p><p>Your purchase was successful.</p>";

            switch ($type) {
                case "education":
                    $trx = $res['content']['transactions'];
                    $emailMessage .= "<h3>Education Transaction Details</h3>";
                    $emailMessage .= "<p><strong>Name:</strong> {$trx['product_name']}</p>";
                    if (!empty($trx['quantity']))
                        $emailMessage .= "<p><strong>Quantity:</strong> {$trx['quantity']}</p>";
                    if (!empty($trx['unit_price']))
                        $emailMessage .= "<p><strong>Unit Price:</strong> ₦" . number_format($trx['unit_price']) . "</p>";
                    if (!is_null($trx['convinience_fee']))
                        $emailMessage .= "<p><strong>Convenience Fee:</strong> ₦" . number_format($trx['convinience_fee']) . "</p>";
                    $emailMessage .= "<p><strong>Total Amount:</strong> ₦" . number_format($res['amount']) . "</p>";
                    $emailMessage .= "<p><strong>Status:</strong> {$trx['status']}</p>";
                    if (!empty($res['tokens'])) {
                        $emailMessage .= "<h4>PINS</h4>";
                        foreach ($res['tokens'] as $i => $pin) {
                            $emailMessage .= "<p><strong>PIN " . ($i + 1) . ":</strong> $pin</p>";
                        }
                    }
                    if (!empty($res['cards'])) {
                        $emailMessage .= "<h4>Cards</h4>";
                        foreach ($res['cards'] as $i => $card) {
                            $emailMessage .= "<p><strong>Card " . ($i + 1) . ":</strong><br>PIN: {$card['Pin']}<br>SN: {$card['Serial']}</p>";
                        }
                    }
                    break;

                case "electricity":
                    $emailMessage .= "<h3>Electricity Transaction Details</h3>";
                    $emailMessage .= "<p><strong>Name:</strong> " . ($res['customerName'] ?? $res['Name']) . "</p>";
                    $emailMessage .= "<p><strong>Address:</strong> " . ($res['customerAddress'] ?? $res['Address']) . "</p>";
                    $emailMessage .= "<p><strong>Amount:</strong> ₦" . number_format($res['amount']) . "</p>";
                    if (!empty($res['balance'])) {
                        $emailMessage .= "<p><strong>Balance:</strong> {$res['balance']}</p>";
                    }
                    if (!empty($res['purchased_code'])) {
                        $emailMessage .= "<p><strong>PIN:</strong> {$res['purchased_code']}</p>";
                    }
                    if (!empty($res['units'])) {
                        $emailMessage .= "<p><strong>Units:</strong> {$res['units']}</p>";
                    }
                    break;

                case "tv":
                case "airtime":
                case "data":
                    $trx = $res['content']['transactions'];
                    $emailMessage .= "<h3>" . ucfirst($type) . " Transaction Details</h3>";
                    if (!empty($trx['name'])) $emailMessage .= "<p><strong>Name:</strong> {$trx['name']}</p>";
                   
                    if (!empty($trx['unique_element'])) $emailMessage .= "<p><strong>Number:</strong> {$trx['unique_element']}</p>";
                    $emailMessage .= "<p><strong>Product Name:</strong> {$trx['product_name']}</p>";
                    $emailMessage .= "<p><strong>Amount:</strong> ₦" . number_format($res['amount']) . "</p>";
                    $emailMessage .= "<p><strong>Status:</strong> {$trx['status']}</p>";
                    break;

                default:
                    $emailMessage .= "<p>No matching transaction type found.</p>";
                    break;
            }

            // Send email & clean pending_tx
            if (sendMail($email, $subject, $emailMessage)) {
                $stmt = $mysqli->prepare("DELETE FROM pending_tx WHERE tx_id = ?");
                $stmt->bind_param("s", $tx_id);
                $stmt->execute();
                $stmt->close();
            }
addNotification($u['id'], $subject, 'Transaction Alert!');

        } elseif (isset($res['code']) && in_array($res['code'], $nonChargeableFailureCodes)) {
            // === FAILED ===
            $payload = $mysqli->real_escape_string(json_encode($res));
            $amount = floatval($row['amount']);

            // Refund user
            $stmt = $mysqli->prepare("UPDATE users SET ngn_balance = ngn_balance + ?, total_spent = total_spent - ? WHERE email = ?");
            $stmt->bind_param("dds", $amount, $amount, $email);
            $stmt->execute();
            $affected = $stmt->affected_rows;
            $stmt->close();

            if ($affected > 0) {
                // Mark transaction as failed
                $stmt = $mysqli->prepare("UPDATE transactions SET status = 'Complete', flow = 'in', title = 'Purchase refund',  payload = ? WHERE our_ref = ?");
                $stmt->bind_param("ss", $payload, $tx_id);
                $stmt->execute();
                $stmt->close();

                // Delete from pending_tx
                $stmt = $mysqli->prepare("DELETE FROM pending_tx WHERE tx_id = ?");
                $stmt->bind_param("s", $tx_id);
                $stmt->execute();
                $stmt->close();

                $name = $u['first_name'] ?? '';
$subject = 'You have received a refund for your recent purchase';

$emailMessage = "
  <p>Hello {$name},</p>
  <p>Your purchase could not be completed and has been <strong>successfully refunded</strong>.</p>
  <p><strong>Refund Amount:</strong> ₦" . number_format($amount) . "</p>
  <p>The refunded amount has been credited back to your wallet.</p>
  <p>If you have any questions, please contact support.</p>
";

sendMail($email, $subject, $emailMessage);
addNotification(
    $u['id'],
    '₦' . number_format($amount) . ' has been refunded to your wallet.', 'Purchase Refunded'
);

            }
        }

    } catch (Exception $e) {
        error_log("VTpass requery failed for tx $tx_id: " . $e->getMessage());
    }
}

$q->free();
?>
