<?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
$marketingOfficer = \App\Models\User::role('marketing_officer')->first();

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

echo "Testing Generate All Periods for Marketing Officer:\n";
echo "ID: {$marketingOfficer->id}\n";
echo "Name: {$marketingOfficer->name}\n";
echo "Created: {$marketingOfficer->created_at->format('Y-m-d')}\n\n";

// Count existing periods before
$existingCount = \DB::table('marketing_officer_payments')
    ->where('marketing_officer_id', $marketingOfficer->id)
    ->count();

echo "Existing payment periods: {$existingCount}\n\n";

// Simulate the generateAllPeriods logic
$accountCreated = \Carbon\Carbon::parse($marketingOfficer->created_at);
$firstMonday = $accountCreated->copy();
if ($firstMonday->dayOfWeek !== \Carbon\Carbon::MONDAY) {
    $firstMonday->next(\Carbon\Carbon::MONDAY);
}

echo "First Monday on or after creation: {$firstMonday->format('Y-m-d')}\n";

$currentPeriodStart = $firstMonday->copy();
$now = \Carbon\Carbon::now();
$periodsToGenerate = 0;

echo "\nPeriods that will be generated:\n";
echo str_repeat('-', 60) . "\n";

while ($currentPeriodStart->lt($now)) {
    $currentPeriodEnd = $currentPeriodStart->copy()->addDays(13);
    
    $existingPeriod = \DB::table('marketing_officer_payments')
        ->where('marketing_officer_id', $marketingOfficer->id)
        ->where('period_start', $currentPeriodStart->format('Y-m-d'))
        ->first();
    
    if (!$existingPeriod) {
        echo sprintf(
            "Period %d: %s to %s\n",
            ++$periodsToGenerate,
            $currentPeriodStart->format('Y-m-d'),
            $currentPeriodEnd->format('Y-m-d')
        );
    } else {
        echo sprintf(
            "SKIP: %s to %s (already exists)\n",
            $currentPeriodStart->format('Y-m-d'),
            $currentPeriodEnd->format('Y-m-d')
        );
    }
    
    $currentPeriodStart->addWeeks(2);
}

echo str_repeat('-', 60) . "\n";
echo "\nTotal periods to generate: {$periodsToGenerate}\n";
