<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Product;
use App\Models\Bid;
use App\Models\User;
use App\Models\Notification;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use DB;

class CheckFinishedAuctions extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:finished-auctions';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check finished auctions and notify highest bidders';

    /**
     * Execute the console command.
     */
    public function handle()
    { 
        $now = Carbon::now('UTC');

        $products = Product::where('finish_date', '<', $now) 
            ->where('status', 'Approved')
            ->whereNull('notified_at')
            ->where('current_notified_user_id', 0)
            ->where('payment_done', 0)
            ->get();
            
        $environment_data = getEnvironmentData();  
        $PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS = $environment_data['PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS'];

        $payment_options = $environment_data['PAYMENT_OPTIONS'];
        $codEnabled = data_get($payment_options, 'value', 0);

        $expiry_date = Carbon::parse($now)->addDays($PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS)->format('Y-m-d H:i');

        foreach ($products as $product) {
            $highestBid = $product->bids()->orderByDesc('amount')->where('is_notified', 1)->first();

            if ($highestBid) {
                $highestBid->notified_date_time = $now;
                $highestBid->is_notified = 1;
                $highestBid->is_crow = 1;
                $highestBid->expiry_date = $expiry_date;
                $highestBid->save();

                Bid::where('product_sku', $product->sku)
                    ->where('id', '!=', $highestBid->id)
                    ->update(['is_crow' => 0]);

                $winner = User::select('id', 'first_name', 'last_name', 'email', 'phone', 'country_id')->find($highestBid->user_id);

                $product->current_notified_user_id = $winner->id;
                $product->notified_at  = $now;
                $product->save();

                // Mail::to($winner->email)->send(new \App\Mail\WinnerMail($product, $winner));
                Mail::to('ankur.r.mts@gmail.com')->send(new \App\Mail\WinnerMail($product, $winner));

                if($codEnabled == 1){
                    $payment_link_1 = URL::temporarySignedRoute(
                        'admin.payment.select_payment_option', // named route
                        now()->addDays($PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS)->endOfDay(), // 15th day 11:59 PM
                        [
                            'user_id' => $winner->id,
                            'product_sku' => $product->sku,
                        ]
                    );
                } else {
                    $payment_link_1 = URL::temporarySignedRoute(
                        'admin.payment.process_to_buy_product', // named route
                        now()->addDays($PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS)->endOfDay(), // 15th day 11:59 PM
                        [
                            'user_id' => $winner->id,
                            'product_sku' => $product->sku,
                        ]
                    );  
                }

                $message = "Congratulations! You’ve won the auction for $product->name. Complete your purchase within $PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS days to secure the item — or it may be offered to the next highest bidder";
                Notification::create([
                    'user_id' => $winner->id,
                    'title' => "Congratulations! You won the auction",
                    'message' => $message,
                    'link' => $payment_link_1
                ]);

                // pushNotification($winner->id, $message);
            } else {
                $highestBid = $product->bids()->orderByDesc('amount')->first();

                if($highestBid){
                    $highestBid->notified_date_time = $now;
                    $highestBid->is_notified = 1;
                    $highestBid->is_crow = 1;
                    $highestBid->expiry_date = $expiry_date;
                    $highestBid->save();

                    Bid::where('product_sku', $product->sku)
                        ->where('id', '!=', $highestBid->id)
                        ->update(['is_crow' => 0]);

                    $winner = User::select('id', 'first_name', 'last_name', 'email', 'phone', 'country_id')->find($highestBid->user_id);

                    $product->current_notified_user_id = $winner->id;
                    $product->notified_at  = $now;
                    $product->save();

                    // Mail::to($winner->email)->send(new \App\Mail\WinnerMail($product, $winner));
                    Mail::to('ankur.r.mts@gmail.com')->send(new \App\Mail\WinnerMail($product, $winner));

                    if($codEnabled == 1){
                        $payment_link_1 = URL::temporarySignedRoute(
                            'admin.payment.select_payment_option', // named route
                            now()->addDays($PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS)->endOfDay(), // 15th day 11:59 PM
                            [
                                'user_id' => $winner->id,
                                'product_sku' => $product->sku,
                            ]
                        );
                    } else {
                        $payment_link_1 = URL::temporarySignedRoute(
                            'admin.payment.process_to_buy_product', // named route
                            now()->addDays($PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS)->endOfDay(), // 15th day 11:59 PM
                            [
                                'user_id' => $winner->id,
                                'product_sku' => $product->sku,
                            ]
                        );  
                    }

                    $message = "Congratulations! You’ve won the auction for $product->name. Complete your purchase within $PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS days to secure the item — or it may be offered to the next highest bidder";
                    Notification::create([
                        'user_id' => $winner->id,
                        'title' => "Congratulations! You won the auction",
                        'message' => $message,
                        'link' => $payment_link_1
                    ]);

                    // pushNotification($winner->id, $message);
                }
            }
        }

        // $after24Hours = $now->copy()->addHours($WINNER_USER_TIME);
        // $products = Product::where('finish_date', '<', $now)
        //     ->where('current_notified_user_id', '!=', 0)
        //     ->where('status', 'Approved')
        //     ->where('payment_done', 0)
        //     ->where('notified_at', '<=', $after24Hours)
        //     ->get();

        // foreach ($products as $key => $product) {
        //     $bids_data = $product->bids()->orderByDesc('bids.notified_date_time')->where('is_notified', 1)->first();

        //     if($bids_data){
        //         if (!is_null($bids_data->notified_date_time) && Carbon::parse($bids_data->notified_date_time)->lte(Carbon::now()->subHours(24))) {
        //             $bids = $product->bids()->orderByDesc('amount')->where('is_notified', 0)->first();

        //             if(isset($bids) && !empty($bids)){
        //                 $nextUser = User::select('id', 'first_name', 'last_name', 'email', 'phone', 'country_id')->where('id', $bids->user_id)->first();

        //                 Mail::to($nextUser->email)->send(new \App\Mail\SecondChanceWinnerMail($product, $nextUser));
        //                 // Mail::to('ankur.r.mts@gmail.com')->send(new \App\Mail\SecondChanceWinnerMail($product, $nextUser));

        //                 $bids->notified_date_time = $now;
        //                 $bids->is_notified = 1;
        //                 $bids->is_crow = 1;
        //                 $bids->save();

        //                 Bid::where('product_sku', $product->sku)
        //                     ->where('id', '!=', $bids->id)
        //                     ->update(['is_crow' => 0]);

        //                 $payment_link_2 = URL::temporarySignedRoute(
        //                     'admin.payment.process_to_buy_product', // named route
        //                     now()->addDay(), // expires after 24 hours
        //                     [
        //                         'user_id' => $nextUser->id,
        //                         'product_sku' => $product->sku,
        //                     ]
        //                 );

        //                 $message = "Congratulations! You’ve won the auction for $product->name. Complete your purchase within $WINNER_USER_TIME hours to secure the item — or it may be offered to the next highest bidder";
        //                 Notification::create([
        //                     'user_id' => $nextUser->id,
        //                     'title' => "Congratulations! You won the auction",
        //                     'message' => $message,
        //                     'link' => $payment_link_2
        //                 ]);

        //                 pushNotification($nextUser->id, $message);
        //             }
        //         }
        //     } else {
        //         $bids = $product->bids()->orderByDesc('amount')->where('is_notified', 0)->first();

        //         if(isset($bids) && !empty($bids)){
        //             $nextUser = User::select('id', 'first_name', 'last_name', 'email', 'phone', 'country_id')->where('id', $bids->user_id)->first();

        //             Mail::to($nextUser->email)->send(new \App\Mail\SecondChanceWinnerMail($product, $nextUser));
        //             // Mail::to('ankur.r.mts@gmail.com')->send(new \App\Mail\SecondChanceWinnerMail($product, $nextUser));

        //             $bids->notified_date_time = $now;
        //             $bids->is_notified = 1;
        //             $bids->is_crow = 1;
        //             $bids->save();

        //             Bid::where('product_sku', $product->sku)
        //                 ->where('id', '!=', $bids->id)
        //                 ->update(['is_crow' => 0]);

        //             $product->current_notified_user_id = $nextUser->id;
        //             $product->notified_at = $now;
        //             $product->save();

        //             $payment_link_3 = URL::temporarySignedRoute(
        //                 'admin.payment.process_to_buy_product', // named route
        //                 now()->addDay(), // expires after 24 hours
        //                 [
        //                     'user_id' => $nextUser->id,
        //                     'product_sku' => $product->sku,
        //                 ]
        //             );

        //             $message = "Congratulations! You’ve won the auction for $product->name. Complete your purchase within $WINNER_USER_TIME hours to secure the item — or it may be offered to the next highest bidder";
        //             Notification::create([
        //                 'user_id' => $nextUser->id,
        //                 'title' => "Congratulations! You won the auction",
        //                 'message' => $message,
        //                 'link' => $payment_link_3
        //             ]);

        //             pushNotification($nextUser->id, $message);
        //         }
        //     }
        // }

        \Log::info("CheckFinishedAuctions Command Run at " . $now);
    }
}