<?php

namespace App\Console\Commands;

use App\Company;
use App\Util;
use Illuminate\Console\Command;
use \Carbon\Carbon;

class SendingChargeExpiryEmails extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sends the required expiry emails to the charged users';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $emailsToSend = [];
        $chargesExpiresSoon = \DB::select('SELECT company_id, expires_at FROM transactions WHERE expires_at IS NOT NULL AND expires_at > ?', [\Carbon\Carbon::now()->toDateTimeString()]);
        foreach ($chargesExpiresSoon as $charge) {
            $this->info(\GuzzleHttp\json_encode($charge));
            //#1 Check Expiry Criteria
            // 14/7/3/1
            $days_left = Carbon::parse($charge->expires_at)->diff(Carbon::now())->days;
            if ($days_left > 14) {
                $company = Company::getDetails($charge->company_id);
                Util::sendMail('charge_expires_soon', [
                    'email' => $company->user_email,
                    'name' => $company->user_name,
                    'expires_at' => $charge->expires_at,
                    'days_left' => $days_left,
                    'domain' =>$company->domain,
                    'subject' => 'Your HRFlo subscription will Expire soon!'
                ]);
            }
        }
    }
}
