<?php
require_once 'config.php';

echo "=== Checking Orders Without Balance History ===\n\n";

// Find orders that are processing/delivered but have no balance history
$query = "
    SELECT o.id, o.order_reference, o.store_id, o.status, o.created_at, s.owner_id, o.amount
    FROM orders o
    INNER JOIN stores s ON o.store_id = s.id
    WHERE o.status IN ('processing', 'delivered', 'completed')
    AND o.store_id IS NOT NULL
    AND NOT EXISTS (
        SELECT 1 FROM balance_history bh 
        WHERE bh.ref_id = o.id 
        AND bh.reason = 'order'
    )
    ORDER BY o.created_at DESC
    LIMIT 20
";

$result = $conn->query($query);
$missingCount = 0;

while ($row = $result->fetch_assoc()) {
    $missingCount++;
    echo "Order ID: {$row['id']}, Ref: {$row['order_reference']}, Store: {$row['store_id']}, Owner: {$row['owner_id']}, Status: {$row['status']}, Amount: {$row['amount']}, Date: {$row['created_at']}\n";
    
    // Check if order has paystack_reference
    $paystackCheck = $conn->prepare("SELECT paystack_reference FROM orders WHERE id = ?");
    $paystackCheck->bind_param("i", $row['id']);
    $paystackCheck->execute();
    $paystackResult = $paystackCheck->get_result();
    $paystackData = $paystackResult->fetch_assoc();
    $paystackCheck->close();
    
    $hasPaystack = !empty($paystackData['paystack_reference']);
    echo "  → Paystack Reference: " . ($hasPaystack ? $paystackData['paystack_reference'] : "NONE") . "\n";
    
    // Check owner's current balance
    $balanceCheck = $conn->prepare("SELECT balance FROM agents WHERE id = ?");
    $balanceCheck->bind_param("i", $row['owner_id']);
    $balanceCheck->execute();
    $balanceResult = $balanceCheck->get_result();
    $balanceData = $balanceResult->fetch_assoc();
    $balanceCheck->close();
    
    echo "  → Owner Current Balance: " . ($balanceData['balance'] ?? 'N/A') . "\n\n";
}

echo "\n=== Summary ===\n";
echo "Total orders missing balance history: $missingCount\n";

// Check if BalanceHistory class exists
if (class_exists('App\classes\BalanceHistory')) {
    echo "✓ BalanceHistory class exists\n";
} else {
    echo "✗ BalanceHistory class NOT FOUND\n";
}

// Test BalanceHistory logging
echo "\n=== Testing BalanceHistory Logging ===\n";
require_once 'app/classes/BalanceHistory.php';
$testAgentId = 30; // Use a real agent ID
$testResult = \App\classes\BalanceHistory::log($conn, $testAgentId, 0.01, 'manual_adjustment', null, 'TEST');
echo "Test log result: " . ($testResult ? "SUCCESS" : "FAILED") . "\n";


























