ldc-crm/app/Jobs/SyncEmailOptOuts.php
2026-05-26 14:58:35 +02:00

58 lines
2 KiB
PHP

<?php
namespace App\Jobs;
use App\Lib\Helpers\MailjetHelper;
use App\Models\Brand;
use App\Models\CustomerInfo;
use App\Models\SingleOptin;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class SyncEmailOptOuts implements ShouldQueue
{
use Queueable;
/**
* Execute the job.
*/
public function handle(): void
{
$campaigns = MailjetHelper::getCampaigns();
foreach ($campaigns as $campaign) {
$contactListId = $campaign['ListID'];
$brand = Brand::query()->where('newsletter_email', $campaign['FromEmail'])->first();
$unsubscribedContacts = MailjetHelper::getUnsubscribedContacts($contactListId, Carbon::now()->subDay());
if (empty($unsubscribedContacts)) {
continue;
}
foreach ($unsubscribedContacts as $unsubscribedContact) {
$contact = MailjetHelper::getContact($unsubscribedContact['ContactID']);
$crmCustomer = CustomerInfo::getFromEmail($brand, $contact[0]["Email"])->first();
if ($crmCustomer) {
$crmCustomer->opt_in = false;
if (!$crmCustomer->saveOrFail()) {
throw new \Exception(sprintf('Optin status not changed for customer (%s) and brand (%d).', $crmCustomer->getKey()));
}
} else {
$singleOptin = SingleOptin::query()->where('email', $contact[0]['Email'])
->whereHas('brand', function ($q) use ($brand) {
$q->whereId($brand->getKey());
})->first();
if ($singleOptin) {
if (!$singleOptin->delete()) {
throw new \Exception(sprintf('SingleOptin (%s) not deleted for brand (%d).', $singleOptin->hashcode, $brand->name));
}
}
}
}
}
}
}