<?php

namespace App\Console\Commands;
use App\Interfaces\SubscriptionRepositoryInterface;
use App\Interfaces\UserRepositoryInterface;
use App\Interfaces\OrganisationRepositoryInterface;
use App\Mail\PaymentSuccess;
use App\Mail\SubscriptionRenewed;
use App\Mail\SubscriptionReminder;
use App\Mail\SubscriptionFailed;
use Illuminate\Support\Facades\Mail;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class checkSubscription extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:check-subscription';
    private SubscriptionRepositoryInterface $subscriptionRepository;
    private UserRepositoryInterface $userRepository;
    private OrganisationRepositoryInterface $organisationRepository;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check Subscription Statues';

    /**
     * Execute the console command.
     */

     public function __construct(SubscriptionRepositoryInterface $subscriptionRepository, UserRepositoryInterface $userRepository,OrganisationRepositoryInterface $organisationRepository)
     {
        parent::__construct();
         $this->subscriptionRepository = $subscriptionRepository;
         $this->userRepository = $userRepository;
         $this->organisationRepository = $organisationRepository;
     }
 
    public function handle()
    {
        //Handle the Logic to send reminders and all subscription related activities
        try{
            echo "Running subscriptions cron";
            //Get Subscriptions 3 days to expiry
            $subscriptions = $this->subscriptionRepository->getSubscriptionThreeDaysToExpiry();
            //Loop through and send an email for reminder to all subscription
            foreach ($subscriptions as $subscription) {
                //Fetch all neccessary tables for action
                $org = $this->organisationRepository->findById($subscription->organisation_id);
                $user = $this->userRepository->findByField("organisation_id", $org->id);
                $mailData = [
                    "email" => $user->email,
                    "name" => $org->name,
                ];
                Mail::to($user->email)->send(new SubscriptionReminder($mailData));

                //Update Subscription so we don't resend email
                $updateData = [
                    "email_reminder_sent" => true,
                ];
                $updataSubscription = $this->subscriptionRepository->updateSubscription($subscription->id,$updateData);
            }

        } catch (\Exception $e) {
            echo 'Error Sending Reminders'.$e;
        }
    }
}
