<?php

declare(strict_types=1);

namespace GroundLevel\Testing\Factories\MemberPress;

use MeprCoupon;
use WP_UnitTest_Factory_For_Post;
use WP_UnitTest_Generator_Sequence;

class CouponFactory 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('DISCOUNTCOUPON%s'),
            'post_type'  => MeprCoupon::$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);
        $coupon  = new MeprCoupon($post_id);
        foreach ($args as $key => $value) {
            $coupon->$key = $value;
        }
        $coupon->store_meta();
        return $coupon->ID;
    }

    /**
     * Updates a coupon object by ID.
     *
     * @param integer $id     The coupon's ID.
     * @param array   $fields An array of data to update.
     */
    public function update_object($id, $fields)
    {
        $coupon = new MeprCoupon($id);
        foreach ($fields as $key => $value) {
            $coupon->$key = $value;
        }

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

    /**
     * Retrieves a coupon object by ID.
     *
     * @param  integer $id The coupon's ID.
     * @return MeprCoupon
     */
    public function get_object_by_id($id)
    {
        return new MeprCoupon($id);
    }
}
