<?php
require_once 'config.php';

echo "=== Balance History Table Structure ===\n";
$result = $conn->query("DESCRIBE balance_history");
while($row = $result->fetch_assoc()) {
    echo json_encode($row, JSON_PRETTY_PRINT) . "\n";
}

echo "\n=== Recent Balance History Entries (Last 10) ===\n";
$result = $conn->query("SELECT * FROM balance_history ORDER BY created_at DESC LIMIT 10");
while($row = $result->fetch_assoc()) {
    echo "ID: {$row['id']}, Agent: {$row['agent_id']}, Change: {$row['change_amount']}, Reason: {$row['reason']}, Ref ID: {$row['ref_id']}, Date: {$row['created_at']}\n";
}

echo "\n=== Recent Customer Orders (Last 10) ===\n";
$result = $conn->query("SELECT o.id, o.order_reference, o.store_id, o.status, o.created_at, s.owner_id 
                        FROM orders o 
                        LEFT JOIN stores s ON o.store_id = s.id 
                        WHERE o.store_id IS NOT NULL 
                        ORDER BY o.created_at DESC LIMIT 10");
while($row = $result->fetch_assoc()) {
    echo "Order ID: {$row['id']}, Ref: {$row['order_reference']}, Store: {$row['store_id']}, Owner: {$row['owner_id']}, Status: {$row['status']}, Date: {$row['created_at']}\n";
    
    // Check if balance history exists for this order
    $bhCheck = $conn->prepare("SELECT id FROM balance_history WHERE ref_id = ? AND reason = 'order'");
    $bhCheck->bind_param("i", $row['id']);
    $bhCheck->execute();
    $bhResult = $bhCheck->get_result();
    $hasHistory = $bhResult->num_rows > 0;
    $bhCheck->close();
    
    echo "  → Balance History: " . ($hasHistory ? "EXISTS" : "MISSING") . "\n";
}

echo "\n=== Recent Agent Orders (Last 10) ===\n";
$result = $conn->query("SELECT ao.id, ao.agent_id, ao.store_id, ao.status, ao.created_at, s.owner_id 
                        FROM agent_orders ao 
                        LEFT JOIN stores s ON ao.store_id = s.id 
                        WHERE ao.store_id IS NOT NULL 
                        ORDER BY ao.created_at DESC LIMIT 10");
while($row = $result->fetch_assoc()) {
    echo "Agent Order ID: {$row['id']}, Agent: {$row['agent_id']}, Store: {$row['store_id']}, Owner: {$row['owner_id']}, Status: {$row['status']}, Date: {$row['created_at']}\n";
    
    // Check if balance history exists for this order
    $bhCheck = $conn->prepare("SELECT id FROM balance_history WHERE ref_id = ? AND reason = 'order'");
    $bhCheck->bind_param("i", $row['id']);
    $bhCheck->execute();
    $bhResult = $bhCheck->get_result();
    $hasHistory = $bhResult->num_rows > 0;
    $bhCheck->close();
    
    echo "  → Balance History: " . ($hasHistory ? "EXISTS" : "MISSING") . "\n";
}


























