<?php

require __DIR__.'/vendor/autoload.php';

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

// Get a marketing officer user
$marketingOfficer = \App\Models\User::role('marketing_officer')->first();

if (!$marketingOfficer) {
    echo "No marketing officer found in database\n";
    exit(1);
}

echo "Testing commission endpoint for Marketing Officer:\n";
echo "ID: {$marketingOfficer->id}\n";
echo "Name: {$marketingOfficer->name}\n";
echo "Email: {$marketingOfficer->email}\n";
echo "Commission %: {$marketingOfficer->commission_percentage}\n\n";

// Test the logic
try {
    // Get payment periods
    $paymentPeriods = \DB::table('marketing_officer_payments')
        ->where('marketing_officer_id', $marketingOfficer->id)
        ->orderBy('period_start', 'desc')
        ->get();
    
    echo "Payment Periods Found: " . $paymentPeriods->count() . "\n";
    
    // Calculate unpaid commission
    $lastPayment = \DB::table('marketing_officer_payments')
        ->where('marketing_officer_id', $marketingOfficer->id)
        ->orderBy('period_end', 'desc')
        ->first();

    $unpaidCommissionStart = $lastPayment 
        ? \Carbon\Carbon::parse($lastPayment->period_end)->addDay()
        : \Carbon\Carbon::parse($marketingOfficer->created_at);
    
    $unpaidCommissionEnd = \Carbon\Carbon::now();
    
    echo "Unpaid Commission Period: {$unpaidCommissionStart->format('Y-m-d')} to {$unpaidCommissionEnd->format('Y-m-d')}\n";

    $commissionPercentage = $marketingOfficer->commission_percentage ?? 0;
    echo "Commission Percentage: {$commissionPercentage}%\n";

    // Calculate subscriptions
    $subscriptionAmount = \DB::table('immigo_pro_subscriptions')
        ->join('marketing_officer_users', 'immigo_pro_subscriptions.user_id', '=', 'marketing_officer_users.user_id')
        ->where('marketing_officer_users.marketing_officer_id', $marketingOfficer->id)
        ->whereBetween('immigo_pro_subscriptions.created_at', [$unpaidCommissionStart, $unpaidCommissionEnd])
        ->whereIn('immigo_pro_subscriptions.status', ['active', 'completed'])
        ->sum('immigo_pro_subscriptions.total_amount');
    
    echo "Subscription Amount: \${$subscriptionAmount}\n";

    // Calculate invoices
    $invoiceAmount = \DB::table('invoices')
        ->join('marketing_officer_users', 'invoices.user_id', '=', 'marketing_officer_users.user_id')
        ->whereNotNull('invoices.subscription_id')
        ->where('marketing_officer_users.marketing_officer_id', $marketingOfficer->id)
        ->whereBetween('invoices.created_at', [$unpaidCommissionStart, $unpaidCommissionEnd])
        ->where('invoices.status', 'paid')
        ->sum('invoices.amount');
    
    echo "Invoice Amount: \${$invoiceAmount}\n";

    $totalUnpaidAmount = $subscriptionAmount + $invoiceAmount;
    $unpaidCommission = ($totalUnpaidAmount * $commissionPercentage) / 100;
    
    echo "Total Unpaid Commission: \${$unpaidCommission}\n";
    
    echo "\n✓ Test completed successfully!\n";
    
} catch (\Exception $e) {
    echo "\n✗ Error: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . "\n";
    echo "Line: " . $e->getLine() . "\n";
}
