<?php

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

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

echo "=== FIXING ORDER TIMESTAMPS ===\n\n";

echo "Current Server Time: " . now()->format('Y-m-d H:i:s') . "\n\n";

echo "Finding orders with future timestamps...\n";

$futureOrders = \App\Models\Order::where('created_at', '>', now())->get();

if ($futureOrders->isEmpty()) {
    echo "\n✅ No orders with future timestamps found!\n";
    echo "All timestamps are correct.\n";
    exit;
}

echo "Found " . $futureOrders->count() . " orders with future timestamps:\n";
echo "================================================================\n\n";

foreach ($futureOrders as $order) {
    echo sprintf(
        "ID: %d | Name: %-15s | Wrong time: %s | Will fix to: %s\n",
        $order->id,
        $order->student_name,
        $order->created_at->format('Y-m-d H:i:s'),
        now()->format('Y-m-d H:i:s')
    );
}

echo "\n🔧 Fixing timestamps NOW...\n\n";

$fixed = 0;
foreach ($futureOrders as $order) {
    $oldTime = $order->created_at->format('Y-m-d H:i:s');
    $order->created_at = now()->subSeconds($fixed * 5); // Stagger by 5 seconds each
    $order->save();
    echo "✓ Fixed Order #{$order->id} ({$order->student_name}): {$oldTime} → " . $order->created_at->format('Y-m-d H:i:s') . "\n";
    $fixed++;
}

echo "\n✅ SUCCESS! Fixed {$fixed} order timestamp(s)!\n\n";

echo "Now checking new order after fix...\n";
echo "==================================\n\n";

$latest = \App\Models\Order::orderBy('created_at', 'desc')->take(5)->get();

echo "Latest 5 orders (after fix):\n";
foreach ($latest as $order) {
    echo sprintf(
        "%d. %-15s | %s | %s\n",
        $order->id,
        $order->student_name,
        $order->created_at->format('Y-m-d H:i:s'),
        $order->created_at->diffForHumans()
    );
}

echo "\n🎉 Done! Please refresh your browser to see the correct order.\n";

