<?php namespace Newsletter\Model;

use Intellex\MailChimp\Resource\ResourceSubscriber;

class SubscriberModel {

	/** @var array The data for this model. */
	public $data;

	/** @var string[] The list of errors for each field. */
	public $errors = [];

	/** @var string[] The list of all fields. */
	private $fields = [
		'id',
		'email',
		'status',
		'fields',
	];

	/**
	 * CampaignModel constructor.
	 *
	 * @param array $data The data for the model.
	 */
	public function __construct($data = []) {

		// Set default values
		foreach ($this->fields as $field) {
			if (!key_exists($field, $data)) {
				$data[$field] = null;
			}
		}

		$this->data = $data;
		$this->validate();
	}

	/**
	 * Create the model from the resource.
	 *
	 * @param ResourceSubscriber $subscriber The campaign to build from.
	 *
	 * @return SubscriberModel The initialize model.
	 */
	public static function build(ResourceSubscriber $subscriber) {
		return new SubscriberModel([
			'id'        => $subscriber->id,
			'email'     => $subscriber->email,
			'status'    => $subscriber->status,
			'name'      => $subscriber->fields['FNAME'],
			'last_name' => $subscriber->fields['LNAME'],
		]);
	}

	/**
	 * Validate the current state.
	 *
	 * @return bool True if there are no errors, false otherwise.
	 */
	private function validate() {
		$this->errors = [];

		return empty($this->errors);
	}

}