<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use App\Models\vendorsSubscriptions;
use App\Models\websiteUser;
use App\Mail\website\ExpiredSubscription;

class CheckExpiredSubscriptions extends Command
{
    protected $signature = 'subscriptions:check-expired';
    protected $description = 'Check for expired subscriptions and send emails';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        // Get the current date
        $currentDate = now()->toDateString();

        // Find users with expired subscriptions
        $expiredUsers = vendorsSubscriptions::with('vendor', 'subscription')->where('vendors_subscriptions_DateToEnd', '<=', $currentDate)
            // Optional, to send the email only once
            ->get();

        // Loop through each user and send an email
        if (empty($expiredUsers)) {
        } else {
            foreach ($expiredUsers as $user) {
                $username = websiteUser::where(['website_user_id' => $user->vendor['vendor_websiteuser_id']])->get();
                // Send the subscription expired email
                Mail::to($user->vendor['vendor_email'])->send(new ExpiredSubscription(
                    $username[0]->website_user_name,
                    $user->vendor['vendor_name'],
                    $user->vendor['vendor_email'],
                    $user->vendors_subscriptions_DateToEnd,
                    $user->subscription['subscription_NameAR'],
                ));

                // Mark the user as notified
                // $user->update(['subscription_notified' => true]); // Optional flag to prevent multiple emails
            }
        }

        $this->info('Subscription check complete.');
    }
}
