<?php
// Test script to verify failed records distribution across batches

// Include CodeIgniter
require_once dirname(__FILE__) . '/index.php';

echo "Testing Failed Records Distribution Across Batches\n";
echo "================================================\n";

// Get the CI instance
$CI = &get_instance();

// Test campaign ID - replace with actual campaign ID
$campaign_id = 1; // Change this to your test campaign ID
$user_id = 1;     // Change this to your test user ID

// First, let's see the total failed records
$CI->db->where('campaign_id', $campaign_id);
$CI->db->where('user_id', $user_id);
$CI->db->where('status', 'failed');
$total_failed = $CI->db->count_all_results('campaign_user_data');

echo "Total Failed Records: {$total_failed}\n";

// Get all batches for this campaign
$CI->db->select('smb.*, sm.campaign_id');
$CI->db->from('scheduled_message_batches smb');
$CI->db->join('scheduled_messages sm', 'sm.id = smb.scheduled_message_id');
$CI->db->where('sm.campaign_id', $campaign_id);
$CI->db->order_by('smb.batch_number');
$batches = $CI->db->get()->result();

$total_batches = count($batches);
echo "Total Batches: {$total_batches}\n";

if ($total_batches > 0) {
    $failed_per_batch = floor($total_failed / $total_batches);
    $failed_remainder = $total_failed % $total_batches;
    
    echo "\nFailed Distribution Calculation:\n";
    echo "Failed per batch (base): {$failed_per_batch}\n";
    echo "Remainder to distribute: {$failed_remainder}\n";
    
    echo "\nPer Batch Breakdown:\n";
    echo "Batch Number | Expected Failed Count | Batch Size | % Failed\n";
    echo "-------------|----------------------|------------|----------\n";
    
    $total_expected = 0;
    
    foreach ($batches as $batch) {
        $batch_number = $batch->batch_number;
        $batch_size = $batch->batch_size;
        
        // Calculate expected failed for this batch
        $expected_failed = $failed_per_batch + (($batch_number <= $failed_remainder) ? 1 : 0);
        $total_expected += $expected_failed;
        
        $percentage = $batch_size > 0 ? round(($expected_failed / $batch_size) * 100, 2) : 0;
        
        printf("     %-7d | %-21d | %-10d | %s%%\n", 
            $batch_number, 
            $expected_failed, 
            $batch_size, 
            $percentage
        );
    }
    
    echo "-------------|----------------------|------------|----------\n";
    echo "    TOTAL    | {$total_expected} | | \n";
    echo "\nDistribution Check: " . ($total_expected == $total_failed ? "✅ CORRECT" : "❌ MISMATCH") . "\n";
    
    // Test actual implementation by simulating the controller logic
    echo "\nTesting Controller Logic Simulation:\n";
    echo "===================================\n";
    
    foreach ($batches as $batch) {
        $batch_number = $batch->batch_number;
        $batch_size = $batch->batch_size;
        
        // Simulate the controller calculation
        $batch_failed_count = $failed_per_batch + (($batch_number <= $failed_remainder) ? 1 : 0);
        
        echo "Batch {$batch_number}: Expected {$batch_failed_count} failed records\n";
        
        // Test with a few different page scenarios
        $length = 25; // Records per page
        
        for ($page = 0; $page < 3; $page++) {
            $start = $page * $length;
            
            // Calculate failed records for this page (simulate controller logic)
            $failed_per_page = ceil($batch_failed_count / ceil($batch_size / $length));
            $failed_on_this_page = min($failed_per_page, $batch_failed_count - floor($start / $length) * $failed_per_page);
            $failed_on_this_page = max(0, min($failed_on_this_page, $length));
            
            if ($failed_on_this_page > 0) {
                echo "  Page {$page} (start:{$start}): {$failed_on_this_page} failed records expected\n";
            }
        }
        echo "\n";
    }
} else {
    echo "No batches found for campaign {$campaign_id}\n";
}

echo "Test completed!\n";
?>