<?php

namespace SEOAIC\resources;

class InteractiveArticleResource
{
    public int $id;
    public int $postId;
    public int $blocksCount;
    public string $data;
    public string $date;

    public function __construct() {
        $this->date = time();
    }

    public static function fromRESTRequest($data)
    {
        $interactiveArticle = new self();
        $interactiveArticle->postId = !empty($data->post_id) ? $data->post_id : null;
        $interactiveArticle->data = !empty($data->data) ? $data->data : [];

        return $interactiveArticle;
    }

    public static function fromDBRecord($data)
    {
        $interactiveArticle = new self();

        foreach ($data as $key => $value) {
            $keyWords = explode('_', $key);
            $words = array_map('ucfirst', $keyWords);
            $keyWord = implode('', $words);
            $keyWord = lcfirst($keyWord);
            $interactiveArticle->$keyWord = $value;
        }

        return $interactiveArticle;
    }

    public function toArray()
    {
        return [
            'id'        => !empty($this->id) ? $this->id : null,
            'post_id'   => !empty($this->postId) ? $this->postId : null,
            'blocks_count' => !empty($this->blocksCount) ? $this->blocksCount : 0,
            'data'      => !empty($this->data) ? $this->data : '',
            'date'      => !empty($this->date) ? wp_date('Y-m-d H:i:s', $this->date) : null,
        ];
    }
}
