<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Category;
use App\Models\Product;
use App\Models\Transaction;
use Illuminate\Support\Facades\DB;

class CalculatePopularity extends Command
{
    protected $signature = 'popularity:calculate';
    protected $description = 'Calculate and update popular products/categories based on sales';

    public function handle()
    {
        $this->info('🔥 Calculating popularity...');
        
        // Calculate product sales (last 30 days)
        $productSales = Transaction::where('payment_status', 'PAID')
            ->where('created_at', '>=', now()->subDays(30))
            ->select('product_id', DB::raw('count(*) as sales_count'))
            ->groupBy('product_id')
            ->get();
        
        // Update products
        Product::query()->update(['is_popular' => false, 'total_sales' => 0]);
        
        foreach ($productSales as $sale) {
            Product::where('id', $sale->product_id)
                ->update([
                    'total_sales' => $sale->sales_count,
                    'is_popular' => $sale->sales_count >= 10 // 10+ sales = popular
                ]);
        }
        
        // Calculate category popularity
        $categorySales = Transaction::where('payment_status', 'PAID')
            ->where('created_at', '>=', now()->subDays(30))
            ->join('products', 'transactions.product_id', '=', 'products.id')
            ->select('products.category_id', DB::raw('count(*) as sales_count'))
            ->groupBy('products.category_id')
            ->get();
        
        // Update categories
        Category::query()->update(['is_popular' => false, 'popularity_score' => 0]);
        
        foreach ($categorySales as $sale) {
            Category::where('id', $sale->category_id)
                ->update([
                    'popularity_score' => $sale->sales_count,
                    'is_popular' => $sale->sales_count >= 50 // 50+ sales = popular
                ]);
        }
        
        $this->info('✅ Popularity calculated!');
        $this->info("   Popular products: " . Product::where('is_popular', true)->count());
        $this->info("   Popular categories: " . Category::where('is_popular', true)->count());
        
        return 0;
    }
}