<?php

namespace App\Console\Commands;

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

class ProductReceiptNotification extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:product-receipt-notification';

    /**
     * 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');

        $environment_data = getEnvironmentData();

        // Get all paid products older than 48 hours where receipt is not uploaded
        $payments = Orders::with(['product', 'product.user']) // 'product.user' is seller
            ->where('created_at', '<=', $now->subHours($environment_data['PRODUCT_RECEIPT_NOTIFICATION_TIME']))
            ->whereHas('productReceipt', function ($query) {
                $query->where('reminder_flag', 0);
            })
            ->get();

        foreach ($payments as $payment) {
            $productSku = $payment->product_sku;

            // Check if receipt exists
            $receiptExists = ProductReceipt::where('product_sku', $productSku)->exists();

            if (!$receiptExists && $payment->product) {
                ProductReceipt::where('product_sku', $productSku)->update(['reminder_flag' => 1]);

                $seller = $payment->product->user;

                // Send mail to seller
                if ($seller) {
                    Mail::to($seller->email)->send(new \App\Mail\SellerMissingReceiptMail($payment));
                }

                // Send mail to admin
                $adminEmail = env('MAIL_FROM_ADDRESS'); // define in config/mail.php
                if ($adminEmail) {
                    Mail::to($adminEmail)->send(new \App\Mail\AdminMissingReceiptMail($payment));
                }
            }
        }


        \Log::info("Product Receipt Notification" . $now);
    }
}