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

use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

echo "=== Syncing Views from Product Table ===\n";

// Clear any existing views in product_views table first to avoid duplication
DB::table('product_views')->truncate();
echo "Cleared existing product_views table.\n";

$products = DB::table('product')->where('views', '>', 0)->get();
echo "Found " . $products->count() . " products with views > 0.\n";

$totalInserted = 0;
foreach ($products as $product) {
    $totalViews = (int)$product->views;
    
    // We will generate the exact number of view records for this product
    // spread randomly over the last 60 days
    for ($i = 0; $i < $totalViews; $i++) {
        $randomDaysAgo = rand(0, 60);
        $createdAt = Carbon::now()->subDays($randomDaysAgo)->subHours(rand(0, 23))->subMinutes(rand(0, 59));
        
        DB::table('product_views')->insert([
            'product_id' => $product->id,
            'ip_address' => '127.0.0.1',
            'created_at' => $createdAt,
        ]);
        $totalInserted++;
    }
    
    echo "Product: {$product->product_name} (ID: {$product->id}) - Syncing {$totalViews} views.\n";
}

echo "Successfully populated {$totalInserted} views in product_views!\n";
