<?php

namespace App\Console\Commands\PropertyTrialCheck;

use App\Core\Mail\TrialFirstMail;
use App\Core\Mail\TrialSecondMail;
use App\Core\Service\PropertyService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PropertyTrialMail extends Command
{
    protected $signature = 'cron:property-trial-mail';

    protected $description = '';

    private $propertyService;

    public function __construct(
        Mailer $mailer,
        PropertyService $propertyService
    )
    {
        parent::__construct();

        $this->mailer = $mailer;
        $this->propertyService = $propertyService;
    }

    public function handle()
    {

        $this->info(date('Y-m-d H:i:s') . ' START');

        $propertySelectCriteria = [
            'criteria' => [
                ['field' => 'status', 'condition' => '=', 'value' => 1],
                ['field' => 'commission', 'condition' => '=', 'value' => null],

            ],
            'orderBy' => [
                ["field" => "id", "value" => "ASC"]
            ],
        ];

        $propertyData = $this->propertyService->select($propertySelectCriteria);

        if ($propertyData['status'] == 'success') {

            foreach ($propertyData['data'] as $property) {

                $createDate = Carbon::createFromTimestamp($property['created_at'])->toDateTimeString();
                $expireDay = Carbon::now()->diff(Carbon::createFromTimestamp($property['created_at']))->days;

                if (in_array($expireDay, [4, 10])) {

                    if ($expireDay == 4) {
                        $this->mailer->onQueue('trialFirstMail', new TrialFirstMail(['propertyId' => $property['id']]));
                        $this->info(date('Y-m-d H:i:s') . ' SENT Day 4: ' . $property['id'] . ' - ' . $property['name'] . ' - ' . $createDate);
                    }

                    if ($expireDay == 10) {
                        $this->mailer->onQueue('trialSecondMail', new TrialSecondMail(['propertyId' => $property['id']]));
                        $this->info(date('Y-m-d H:i:s') . ' SENT Day 10: ' . $property['id'] . ' - ' . $property['name'] . ' - ' . $createDate);
                    }


                }

            }

        }

        $this->info(date('Y-m-d H:i:s') . ' FINISHED');


    }
}
