<?php

declare(strict_types=1);

namespace GroundLevel\Testing\Factories\MemberPress;

use MeprRule;
use WP_UnitTest_Factory_For_Post;
use WP_UnitTest_Generator_Sequence;

class RuleFactory extends WP_UnitTest_Factory_For_Post
{
    /**
     * Constructor
     *
     * @param object|null $factory Optional factory object.
     */
    public function __construct($factory = null)
    {
        parent::__construct($factory);
        $this->default_generation_definitions = [
            'post_title'   => new WP_UnitTest_Generator_Sequence('Test Rule %s'),
            'post_type'    => MeprRule::$cpt,
            'post_status'  => 'publish',
            'mepr_type'    => 'all',
            'mepr_content' => '',
        ];
    }

    /**
     * Creates a new object.
     *
     * @param  array $args Array of coupon creation arguments.
     * @return integer
     */
    public function create_object($args)
    {
        $post_id = wp_insert_post($args);
        $rule    = new MeprRule($post_id);
        foreach ($args as $key => $value) {
            $rule->$key = $value;
        }
        $rule->store_meta();
        return $rule->ID;
    }

    /**
     * Updates an object.
     *
     * @param  integer $id     The object ID.
     * @param  array   $fields Field data to update.
     * @return integer
     */
    public function update_object($id, $fields)
    {
        $rule = new MeprRule($id);
        foreach ($fields as $key => $value) {
            $rule->$key = $value;
        }

        $rule->store_meta();
        return $rule->ID;
    }

    /**
     * Retrieves the object by ID.
     *
     * @param  integer $id The object ID.
     * @return MeprRule
     */
    public function get_object_by_id($id)
    {
        return new MeprRule($id);
    }
}
