<?php

namespace App\Classes\Jobs;

use App\Classes\Modules\KeyValuePairs\DataTransferObjects\KeyValuePairObject;
use App\Classes\Modules\KeyValuePairs\Services\CreatesKeyValuePair;
use App\Classes\Notifications\WelcomeVoucherEmail;
use App\Models\User;
use App\Models\Voucher;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendWelcomeVoucherEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    /** @var User */
    private $user;

    /** @var Voucher */
    private $voucher;

    /** @var int */
    private $emailSentCount;

    /**
     * SendWelcomeVoucherEmail constructor.
     * @param User $user
     * @param Voucher $voucher
     * @param int $emailSentCount
     */
    public function __construct(User $user, Voucher $voucher, int $emailSentCount = 1)
    {
        $this->user = $user;
        $this->voucher = $voucher;
        $this->emailSentCount = $emailSentCount;
    }


    public function handle()
    {
        $currentDatetime = Carbon::now();
        $dateToCompare = Carbon::parse($this->voucher->end_date);
        if (!$this->user->hasCustomAttribute($this->voucher->code."_EMAIL_COUNT")
            && $this->user->rewards->where('voucher_id', $this->voucher->id)->count() > 0
            && $currentDatetime->isBefore($dateToCompare))
        {
            //Key #1
            $keyValuePairObject = new KeyValuePairObject(
                $this->voucher->code."_EMAIL_COUNT",
                $this->emailSentCount
            );
            (App()->make(CreatesKeyValuePair::class))->execute($this->user, $keyValuePairObject);

             //Key #2
            $keyValuePairObject = new KeyValuePairObject(
                $this->voucher->code."_EMAIL_DATE_".$this->emailSentCount,
                Carbon::now()
            );
            (App()->make(CreatesKeyValuePair::class))->execute($this->user, $keyValuePairObject);

            $this->user->notify(new WelcomeVoucherEmail($this->user, $this->voucher));
        }
    }
}
