<?php
/**
 * Backfill missing balance history for orders that were processed but don't have balance history entries
 * This script will create balance history entries for orders that are missing them
 */

require_once 'config.php';
require_once 'app/classes/BalanceHistory.php';
require_once 'app/classes/ExternalAPIPricingManager.php';
require_once 'app/classes/StorePricingManager.php';

use App\classes\ExternalAPIPricingManager;
use App\classes\StorePricingManager;

echo "=== Backfilling Missing 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, 
           o.network_type, o.package_size, o.beneficiary_number
    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
";

$result = $conn->query($query);
$processed = 0;
$errors = 0;

while ($row = $result->fetch_assoc()) {
    $orderId = $row['id'];
    $ownerId = $row['owner_id'];
    $storeId = $row['store_id'];
    
    echo "Processing Order ID: {$row['id']}, Ref: {$row['order_reference']}, Owner: $ownerId\n";
    
    // Calculate admin cost (what store owner needs to pay)
    $externalPricingManager = new ExternalAPIPricingManager($conn);
    $adminPrice = $externalPricingManager->getAdminPrice($row['package_size'], $row['network_type']);
    
    if ($adminPrice === null) {
        // Fallback to default pricing
        $pricingManager = new StorePricingManager($conn);
        $priceInfo = $pricingManager->calculatePrice($storeId, $row['package_size'], $row['network_type']);
        $adminPrice = $priceInfo['admin_cost'] ?? $row['amount'];
    }
    
    $amount = floatval($adminPrice);
    
    // Get current balance to estimate balance_before
    // We'll estimate based on current balance + amount (assuming it was deducted)
    $balanceStmt = $conn->prepare("SELECT balance FROM agents WHERE id = ?");
    $balanceStmt->bind_param("i", $ownerId);
    $balanceStmt->execute();
    $balanceResult = $balanceStmt->get_result();
    $balanceData = $balanceResult->fetch_assoc();
    $balanceStmt->close();
    
    $currentBalance = floatval($balanceData['balance'] ?? 0);
    
    // Estimate: balance_before = current_balance + amount (since amount was deducted)
    $estimatedBalanceBefore = $currentBalance + $amount;
    $estimatedBalanceAfter = $currentBalance;
    
    // Log balance history
    try {
        $success = \App\classes\BalanceHistory::log(
            $conn, 
            $ownerId, 
            -1 * $amount, 
            'order', 
            $orderId, 
            $row['beneficiary_number'], 
            $estimatedBalanceBefore, 
            $estimatedBalanceAfter
        );
        
        if ($success) {
            echo "  ✓ Balance history logged (Estimated: Before={$estimatedBalanceBefore}, After={$estimatedBalanceAfter})\n";
            $processed++;
        } else {
            echo "  ✗ Failed to log balance history\n";
            $errors++;
        }
    } catch (Exception $e) {
        echo "  ✗ Error: " . $e->getMessage() . "\n";
        $errors++;
    }
    
    echo "\n";
}

echo "\n=== Summary ===\n";
echo "Processed: $processed\n";
echo "Errors: $errors\n";
echo "\nDone!\n";


























