<?php

namespace CouponsPlus\App\Handlers;

use WP_Post;
use CouponsPlus\App\Data\Store\StorerComposite;
use CouponsPlus\App\Data\Store\SimpleKeyStorer;
use CouponsPlus\App\Data\Store\CouponRowsStorer;
use CouponsPlus\App\Data\Store\CouponModelStorer;
use CouponsPlus\App\Data\Store\CouponAutoApplyStorer;
use CouponsPlus\Original\Events\Handler\EventHandler;

#[\AllowDynamicProperties]
Class CouponSaveHandler extends EventHandler
{
    protected $numberOfArguments = 2;
    protected $priority = 10;

    public function execute(int $postId, WP_Post $post)
    {
        $storer = new StorerComposite([
            // bc-compat
            new CouponRowsStorer($post),
            // tree
            SimpleKeyStorer::create('grove', $post),
            SimpleKeyStorer::create('preloaded_data', $post),
            SimpleKeyStorer::create('testable_partial_relations', $post),
            SimpleKeyStorer::create('preconditions', $post, true),
            SimpleKeyStorer::create('predates', $post, true),
            //SimpleKeyStorer::create('model', $post),
            new CouponModelStorer($post),
            // meta
            new CouponAutoApplyStorer($post),
        ]);

        $storer->store();

        $this->clearShippingCache();
    }

    /**
     * When we update a coupon, we need to make sure to destroy the shipping session
     * since Woo caches it and won't update it after the cart contents change.
     *
     * If the store manager just changed the shipping discount and we don't clear the cache, 
     * customers that have already applied this coupon won't have the changes refelcted if they don't 
     * change their cart. We don't want that.
     */
    protected function clearShippingCache()
    {
        \WC_Cache_Helper::get_transient_version(
            $group = 'shipping', 
            $regenerate = true
        );
    }
}