<?php

use App\Models\UserPlan;
use App\Models\Subscription;

require __DIR__ . '/vendor/autoload.php';
$app = require_once __DIR__ . '/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

echo "Starting Logic Test...\n";

try {
    // 1. Test Subscription Model Access
    $count = Subscription::count();
    echo "Subscription Count: $count\n";

    // 2. Test Revenue Calculation Logic (Mimic Controller)
    $revenue = 0;
    $plans = UserPlan::where('status', 'Active')->withCount('users')->get();
    
    foreach ($plans as $plan) {
        echo "Processing Plan: " . $plan->plan_name . "\n";
        
        // Logic from calculateTotalRevenueForPlan
        $subRevenue = Subscription::where('plan_id', $plan->id)
            ->where('status', 'active')
            ->sum('amount');
            
        if ($subRevenue > 0) {
            echo " - Found Sub Revenue: $subRevenue\n";
            $revenue += $subRevenue;
        } else {
            $calc = $plan->price * $plan->users_count;
            echo " - Fallback Revenue: $calc\n";
            $revenue += $calc;
        }
    }
    
    echo "Total Revenue: $revenue\n";
    echo "SUCCESS: Logic executed without crash.\n";

} catch (\Exception $e) {
    echo "CRASH DETECTED: " . $e->getMessage() . "\n";
    echo $e->getTraceAsString();
}
