<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Product;
use App\Models\Bid;
use App\Models\Notification;
use Carbon\Carbon;

class AuctionEndingAlert extends Command
{
    protected $signature = 'auction:ending-alert';
    protected $description = 'Send alert notification to bidders when auction is about to end';

    public function handle()
    {
        $now = Carbon::now('UTC');

        $environment_data = getEnvironmentData();  
        $auction_ending_soon_notification_time_hours = $environment_data['AUCTION_ENDING_SOON_NOTIFICATION_TIME'];

        // Convert HH:MM to minutes
        if ($auction_ending_soon_notification_time_hours && str_contains($auction_ending_soon_notification_time_hours, ':')) {
            [$hours, $minutes] = explode(':', $auction_ending_soon_notification_time_hours);
            $alertBeforeMinutes = ($hours * 60) + $minutes;
        } else {
            // Default 30 minutes
            $alertBeforeMinutes = 30;
        }

        $alertStart = $now->copy()->addMinutes($alertBeforeMinutes)->format('Y-m-d H:i');

        // $alertStart = '2025-12-15 08:00:00'; // For testing purpose

        $products = Product::where('product_type', 1)
            ->where('status', 'Approved')
            // ->where('finish_date', '>', $now)
            ->where('finish_date', '=', $alertStart)
            ->get();

        foreach ($products as $product) {
            // Get all bidders of the product
            $bidders = Bid::where('product_sku', $product->sku)->distinct('user_id')->pluck('user_id');

            if ($bidders->isEmpty()) continue;

            foreach ($bidders as $user_id) {
                $message = "The $product->name item is about to be sold! Last chance!";

                // 🔔 Store notification in DB
                Notification::create([
                    'user_id' => $user_id,
                    'title' => "Auction Ending Soon",
                    'message' => $message,
                ]);

                // 🔔 Push notification
                pushNotification($user_id, $message);
            }
        }

        return Command::SUCCESS;
    }
}