<?php

namespace CouponsPlus\App\Handlers;

use CouponsPlus\App\Offers\DiscountState;
use CouponsPlus\Original\Events\Handler\EventHandler;

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

    public function execute()
    {
        // Check if the Store API function exists
        if (!function_exists('woocommerce_store_api_register_endpoint_data')) {
            return;
        }

        // Register the extension data for cart items
        woocommerce_store_api_register_endpoint_data(
            array(
                'endpoint'        => 'cart-item',
                'namespace'       => 'coupons-plus',
                'data_callback'   => array($this, 'extend_cart_item_data'),
                'schema_callback' => array($this, 'extend_cart_item_schema'),
                'schema_type'     => ARRAY_A,
            )
        );
    }

    /**
     * Register custom data for cart items
     *
     * @param array $cart_item Cart item array
     * @return array Custom data to be exposed to the Store API
     */
    public function extend_cart_item_data($cart_item)
    {
        // here look for the cart state to see i this cart item has been discounted
        $discountState = DiscountState::getInstance();

        if (!$discountState->cartItemHasBeenDiscounted($cart_item['key'])) {
            return array(
                'has_discount' => false,
            );
        }

        $discountData = $discountState->getDiscountDataForCartItem($cart_item['key']);

        return array(
            'has_discount'      => true,
            'discount_amount'   => $discountData['amount'],
/*            'discount_quantity' => $discountData['quantity'],*/
            'discount_amount_formatted' => wc_price($discountData['amount']),
        );
    }

    /**
     * Register schema for custom cart item data
     *
     * @return array Schema for the custom data
     */
    public function extend_cart_item_schema()
    {
        return array(
            'has_discount' => array(
                'description' => 'If this item has been discounted by us',
                'type'        => 'boolean',
                'readonly'    => true,
            ),
            'discount_amount' => array(
                'description' => 'The amount applied to this item',
                'type'        => 'integer',
                'readonly'    => true,
            ),
            'discount_amount_formatted' => array(
                'description' => 'The amount applied to this item, formatted',
                'type'        => 'integer',
                'readonly'    => true,
            ),
/*            'discount_quantity' => array(
                'description' => 'The number of items of this line item that the discount was applied to',
                'type'        => 'integer',
                'readonly'    => true,
            ),*/
        );
    }
}
