<?php

namespace SEOAIC\patterns;

class LeadsFormPattern
{
    const PATTERN_NAME = 'seoaic/leads-form-pattern';
    const CATEGORY_SLUG = 'leads-forms';

    public $name;
    public $content;

    public function __construct($name, $content)
    {
        $this->name = $name;
        $this->content = $content;
    }

    public function save()
    {
        $patternID = wp_insert_post([
            'post_title'    => $this->name,
            'post_content'  => $this->content,
            'post_status'   => 'publish',
            'comment_status' => 'closed',
            'ping_status'   => 'closed',
            'post_type'     => 'wp_block',
        ]);

        add_post_meta($patternID, 'wp_pattern_sync_status', 'unsynced');
        $this->setCategory($patternID);
    }

    private function setCategory($patternID)
    {
        $exists = term_exists(self::CATEGORY_SLUG, 'wp_pattern_category' ); // array is returned if taxonomy is given

        if (!$exists) {
            wp_insert_term(
                'Leads Forms', // the term
                'wp_pattern_category', // the taxonomy
                array(
                    'description'   => 'Multistep Leads Forms.',
                    'slug'          => self::CATEGORY_SLUG,
                )
            );
        }

        wp_set_object_terms($patternID, self::CATEGORY_SLUG, 'wp_pattern_category' );
    }
}
