<?php
// Update existing batch sizes to be proportional (equal percentages)

$host = '162.215.11.244';
$username = 'ac3_marketing_portal';
$password = '=Y^3GIyrG;J)TV]z';
$database = 'ac3_marketing_portal';
$port = 3306;

try {
    $pdo = new PDO("mysql:host=$host;port=$port;dbname=$database;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "📊 UPDATING BATCH SIZES TO PROPORTIONAL DISTRIBUTION\n";
    echo str_repeat("=", 60) . "\n";
    
    // Get all schedules with their total recipients and current batches
    $schedules = $pdo->query("
        SELECT 
            sm.id as schedule_id,
            sm.total_recipients,
            sm.parts,
            COUNT(smb.id) as batch_count
        FROM scheduled_messages sm
        LEFT JOIN scheduled_message_batches smb ON sm.id = smb.scheduled_message_id
        GROUP BY sm.id, sm.total_recipients, sm.parts
        ORDER BY sm.id
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    echo "📋 Found " . count($schedules) . " campaigns to update:\n";
    echo str_repeat("-", 60) . "\n";
    
    foreach ($schedules as $schedule) {
        $schedule_id = $schedule['schedule_id'];
        $total_recipients = (int)$schedule['total_recipients'];
        $parts = (int)$schedule['parts'];
        $batch_count = (int)$schedule['batch_count'];
        
        if ($parts <= 1 || $batch_count === 0) {
            echo "⏭️  Schedule #{$schedule_id}: Skipping (only {$parts} parts, {$batch_count} batches)\n";
            continue;
        }
        
        echo "🔄 Schedule #{$schedule_id}: " . number_format($total_recipients) . " total → {$parts} equal parts\n";
        
        // Calculate equal portions
        $baseSize = floor($total_recipients / $parts);
        $remainder = $total_recipients % $parts;
        
        // Get current batches for this schedule
        $batches = $pdo->query("
            SELECT id, batch_number, batch_size 
            FROM scheduled_message_batches 
            WHERE scheduled_message_id = {$schedule_id}
            ORDER BY batch_number
        ")->fetchAll(PDO::FETCH_ASSOC);
        
        echo "   Current batches: ";
        foreach ($batches as $batch) {
            echo number_format($batch['batch_size']) . " ";
        }
        echo "\n";
        
        // Update each batch with proportional size
        for ($i = 0; $i < count($batches) && $i < $parts; $i++) {
            $batch = $batches[$i];
            $newSize = $baseSize;
            
            // Add 1 to first few batches to distribute remainder
            if ($i < $remainder) {
                $newSize++;
            }
            
            $pdo->exec("
                UPDATE scheduled_message_batches 
                SET batch_size = {$newSize}
                WHERE id = {$batch['id']}
            ");
            
            $percentage = round(($newSize / $total_recipients) * 100, 1);
            echo "   ✅ Delivery " . ($i + 1) . ": " . number_format($batch['batch_size']) . " → " . number_format($newSize) . " ({$percentage}%)\n";
        }
        
        // Verify the total matches
        $newTotal = $pdo->query("
            SELECT SUM(batch_size) as total 
            FROM scheduled_message_batches 
            WHERE scheduled_message_id = {$schedule_id}
        ")->fetch(PDO::FETCH_ASSOC)['total'];
        
        if ($newTotal == $total_recipients) {
            echo "   ✅ Verified: Total = " . number_format($newTotal) . " ✓\n\n";
        } else {
            echo "   ❌ ERROR: Total mismatch! Expected: " . number_format($total_recipients) . ", Got: " . number_format($newTotal) . "\n\n";
        }
    }
    
    echo str_repeat("=", 60) . "\n";
    echo "📊 FINAL SUMMARY:\n";
    echo str_repeat("=", 60) . "\n";
    
    // Show updated results
    $updated_schedules = $pdo->query("
        SELECT 
            sm.id as schedule_id,
            sm.total_recipients,
            smb.batch_number,
            smb.batch_size,
            ROUND((smb.batch_size / sm.total_recipients) * 100, 1) as percentage
        FROM scheduled_messages sm
        JOIN scheduled_message_batches smb ON sm.id = smb.scheduled_message_id
        ORDER BY sm.id, smb.batch_number
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    $current_schedule = null;
    foreach ($updated_schedules as $row) {
        if ($current_schedule !== $row['schedule_id']) {
            $current_schedule = $row['schedule_id'];
            echo "\n🎯 Schedule #{$row['schedule_id']} (" . number_format($row['total_recipients']) . " total):\n";
        }
        echo "   └─ Delivery {$row['batch_number']}: " . number_format($row['batch_size']) . " records ({$row['percentage']}%)\n";
    }
    
    echo "\n🎉 ALL BATCH SIZES UPDATED TO EQUAL PROPORTIONS!\n";
    echo "📊 Each delivery now gets equal percentage of data\n";
    echo "🔄 Hard refresh browser to see updated delivery logs\n";
    
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}
?>