<?php

declare(strict_types=1);

namespace GroundLevel\Testing\Factories\MemberPress;

use MeprProduct;
use WP_UnitTest_Factory_For_Post;
use WP_UnitTest_Generator_Sequence;

class ProductFactory 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 Product %s'),
            'post_type'  => MeprProduct::$cpt,
        ];
    }

    /**
     * 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);
        $product = new MeprProduct($post_id);
        foreach ($args as $key => $value) {
            $product->$key = $value;
        }
        $product->store_meta();
        return $product->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)
    {
        $product = new MeprProduct($id);
        foreach ($fields as $key => $value) {
            $product->$key = $value;
        }

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

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