<?php

namespace Hilco\Models;

use Klaviyo\Exception\KlaviyoException;
use Klaviyo\Klaviyo;
use Log;

/**
 * Class PromotionKlaviyoListTrigger
 * @package Hilco\Models
 * @property string $klaviyo_list
 * @property bool $check_legacy_rewards
 */
class PromotionKlaviyoListTrigger extends PromotionTriggerDetails {
    protected $table = "PromotionKlaviyoListTriggers";
    protected $fillable = ['klaviyo_list', 'check_legacy_rewards'];
    protected $casts = ['check_legacy_rewards' => 'boolean'];

    public function isTriggered (Customer $soldToCustomer, $webCartItems, $distinctPartInfo = []): bool {
        if ($this->check_legacy_rewards && isset($soldToCustomer->legacyRewardsCustomer)) {
            return true;
        }

        $webSilo = $soldToCustomer->webSilo;
        $klaviyoClient = new Klaviyo($webSilo->klaviyo_api_key, $webSilo->klaviyo_company_id);

        // filter_var() with FILTER_VALIDATE_EMAIL will at least strip out any webuser emails that get returned that
        // aren't actually valid formatted email addresses.
        // array_values() is because the toArray() on the result of filter() creates an array with explicitly keys, e.g.,
        // [ 0 => "email", 1 => "email2", ...] rather than what we want, which is implicity keys, e.g., ["email", "email2", ...]
        $userEmailsArray = array_values($soldToCustomer->webUsers()->pluck('email')->filter(function ($email) {
            return filter_var($email, FILTER_VALIDATE_EMAIL);
        })->toArray());
        $membershipsArray = [];
        try {
            foreach (array_chunk($userEmailsArray, 100) as $userEmailsArrayChunk) {
                $membershipsArray = $klaviyoClient->Lists->checkListSubscriptions($this->klaviyo_list, $userEmailsArrayChunk);
                if (count($membershipsArray)) {
                    break;
                }
            }
        } catch (KlaviyoException $klaviyoException) {
            Log::error($klaviyoException->getMessage(), $klaviyoException->getTrace());
        }

        return count($membershipsArray) > 0;
    }

    public function postTriggerOperation($soldToCustomer){}
}