<?php

namespace Hilco\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Hilco\Models\KlaviyoListSubscriptionResult
 * @property string $klaviyo_list
 * @property int $customer_id
 * @property bool $is_subscribed
 * @property string $expiration_date
 * @property int $webuser_id
 * @property string $result
 * @method static Builder byKlaviyoListAndCustomer($klaviyoListId, $customerId)
 */
class KlaviyoListSubscriptionResult extends WebModel {
    protected $table = "KlaviyoListSubscriptionResults";
    protected $fillable = ["klaviyo_list", "customer_id", "is_subscribed", "expiration_date", "webuser_id", "result"];
    protected $casts = ["is_subscribed" => "boolean", "expiration_date" => "datetime:Y-m-d H:i:s"];

    /**
     * @param string $klaviyoListId
     * @param Customer $customer
     * @param bool $isSubscribed
     * @param WebUser|null $webUser
     * @param string|null $result
     * @return Model|KlaviyoListSubscriptionResult
     */
    public static function createAndSave (string $klaviyoListId,
                                          Customer $customer,
                                          bool $isSubscribed,
                                          string $result = null,
                                          WebUser $webUser = null): KlaviyoListSubscriptionResult {
        $matchBy = [
            'klaviyo_list' => $klaviyoListId,
            'customer_id' => $customer->id,
        ];

        $values = $matchBy;
        $values['is_subscribed'] = $isSubscribed;

        $expDate = Carbon::now()->addHour();
        $expDateStr = $expDate->toDateTimeString();
        $values['expiration_date'] = $expDateStr;

        if (!empty($result)) {
            $values['result'] = $result;
        }

        if (!is_null($webUser)) {
            $values['webuser_id'] = $webUser->id;
        }

        return KlaviyoListSubscriptionResult::updateOrCreate($matchBy, $values);
    }

    /**
     * @return bool
     */
    public function isSubscribed(): bool {
        return $this->is_subscribed;
    }

    /**
     * @return bool
     */
    public function isExpired(): bool {
        // see $casts at top of class, Laravel uses Carbon to cast datetime:<format>
        return Carbon::now()->greaterThanOrEqualTo($this->expiration_date);
    }

    /**
     * @param Builder $query
     * @param $klaviyoListId
     * @param $customerId
     * @return Builder
     */
    public function scopeByKlaviyoListAndCustomer (Builder $query, $klaviyoListId, $customerId): Builder {
        return $query->where('klaviyo_list', $klaviyoListId)->where('customer_id', $customerId);
    }
}