<?php

namespace SEOAIC\resources;


class ContentAlertSettings
{
    public string $status;
    public int $clicks;
    public int $timeframe;
    public array $emails;

    private array $errors;

    public function __construct()
    {
        $this->status = 'disabled';
    }

    public static function fromBackendResponse(array $response = []): ContentAlertSettings
    {
        $self = new self();

        if (!empty($response['data']['status'])) {
            $self->status = $response['data']['status'];
        }

        if (!empty($response['data']['clicks'])) {
            $self->clicks = $response['data']['clicks'];
        }

        if (!empty($response['data']['timeframe'])) {
            $self->timeframe = $response['data']['timeframe'];
        }

        if (!empty($response['data']['emails'])) {
            $self->emails = $response['data']['emails'];
        }

        return $self;
    }

    public static function fromAjaxRequest(array $request = []): ContentAlertSettings
    {
        $self = new self();

        if (!empty($request['seoaic_enable_content_alerts'])) {
            $self->status = 'enabled';
        }

        if (!empty($request['content_alert_clicks_threshold'])) {
            $self->clicks = intval($request['content_alert_clicks_threshold']);
        }

        if (!empty($request['content_alert_days_timeframe'])) {
            $self->timeframe = intval($request['content_alert_days_timeframe']);
        }

        if (!empty($request['content_alert_emails'])) {
            if (is_array($request['content_alert_emails'])) {
                $self->emails = $request['content_alert_emails'];
            } else {
                $self->emails = [$request['content_alert_emails']];
            }
        }

        return $self;
    }

    public function isValid()
    {
        return
            !empty($this->clicks)
            && !empty($this->timeframe)
            && !empty($this->emails)
            && $this->areEmailsValid();
    }

    private function areEmailsValid()
    {
        $valid = true;

        foreach ($this->emails as $email) {
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $valid = false;
                $this->errors[] = ('"' . $email . '" must be a valid email');
            }
        }

        return $valid;
    }

    public function toArray()
    {
        if (PHP_VERSION_ID < 80100) {
            return \Closure::fromCallable("get_object_vars")->__invoke($this);
        } else {
            return call_user_func('get_object_vars', $this);
        }
    }

    public function getErrors(string $separator = ', '): string
    {
        return implode($separator, $this->errors);
    }
}
