<?php

namespace App\Console\Commands\Jobs;

use App\Core\Service\JobsService;
use Illuminate\Console\Command;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Artisan;

class MailJobs extends Command
{
    /*
     * The name and signature of the console command.
     *
     * @var string
     */

    protected $signature = 'cron:mail-jobs';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $mailJobs =
        [
            "default",
            "userCreateMail",
            "UserForgotPassword",
            "slackLog",
            "newBookingMail",
            "contactFormMail",
            "manualPaymentMail",
            "logMail",
            "inventoryActionMail",
            "bookingTicketMail",
            "enwContactFormMail",
            "trialFirstMail",
            "trialSecondMail",
            "cancelBookingMail",
            "modifiedBookingMail",
            "inventoryPdfLinkMail",
            "dailyReportMail",
            "bookingPaymentDataCode",
            "bookingPropertyAddonUpdateMail",
            "offerAcceptMail",
            "offerPreConfirmCustomerMail",
            "offerPreConfirmPropertyMail",
            "bookingEngineSearchReportMail",
            "channelManagerNotificationMail",
            "bookingInvoiceUpdateMail",
            "offerSendMail",
            "dailyReportSalesMail",
            "affiliateRequestMail",
            "propertyProductOfferMail"
        ];
    protected $description = 'Calls All Mail Jobs';
    private $jobsService;

    public function __construct(JobsService $jobsService)
    {
        parent::__construct();
        $this->jobsService = $jobsService;
    }

    public function handle()
    {

        $mailJobsCriteria =
            [
                "whereIn" =>
                    [
                        ["field" => "queue", "value" => $this->mailJobs]
                    ],
                "orderBy" =>
                    [
                        ["field" => "id", "value" => "ASC"]
                    ],
                "take" => 20
            ];

        $mailJobs = $this->jobsService->getJobsList($mailJobsCriteria, ["queue"]);

        foreach ($mailJobs as $perJob) {

            try {
                Artisan::call("queue:work --queue=" . $perJob["queue"]." --tries=5");
            } catch (Exception $e) {
                $message = "Mail Job Fail --- Failed Mail : " . $perJob . " ErrorDetail : " . $e->getLine() . " " . $e->getLine() . " " . $e->getMessage();
                Log::error($message);
                continue;
            }
            sleep(1);
        }
    }

}
