<?php

namespace WeDevs\AppBridge\Integrations\WooCommerce\StoreApi;

use Automattic\WooCommerce\StoreApi\Schemas\ExtendSchema;
use Automattic\WooCommerce\StoreApi\Schemas\V1\CartSchema;
use Exception;

class CartPaymentExtension {

    /**
     * Stores Rest Extending instance.
     *
     * @var ExtendSchema
     */
    protected static $extend;

    /**
     * Plugin Identifier, unique to each plugin.
     *
     * @var string
     */
    const IDENTIFIER = 'dokan_payments';

    /**
     * Bootstraps the class and hooks required data.
     *
     * @param ExtendSchema $extend_rest_api An instance of the ExtendSchema class.
     *
     * @throws Exception
     */
    public static function init( ExtendSchema $extend_rest_api ) {
        self::$extend = $extend_rest_api;
        self::extend_store();
    }

    /**
     * @throws Exception
     */
    public static function extend_store() {
        // Register into `checkout`
        self::$extend->register_endpoint_data(
            [
                'endpoint'          => CartSchema::IDENTIFIER,
                'namespace'         => self::IDENTIFIER,
                'data_callback'     => [ self::class, 'extend_cart_data' ],
                'schema_callback'   => [ self::class, 'extend_cart_schema' ],
                'schema_type'       => ARRAY_A,
            ]
        );
    }

    /**
     * Get available payment gateways
     *
     * @return array
     */
    public static function extend_cart_data() {
        $available_gateways = WC()->payment_gateways->get_available_payment_gateways();

        $payment_methods = [];

        foreach ( $available_gateways as $gateway ) {
            /** @var $gateway WC_Payment_Gateway */
            $payment_methods[] = [
                'id'          => $gateway->id,
                'title'       => $gateway->get_title(),
                'description' => $gateway->get_description(),
                'icon'        => $gateway->get_icon(),
            ];
        }
        return $payment_methods;
    }

    /**
     * Register subscription product schema into checkout endpoint.
     *
     * @return array Registered schema.
     */
    public static function extend_cart_schema() {
        return [
            'properties' => [
                [
                    'id' => 'string',
                    'title' => 'string',
                    'description' => 'string',
                    'icon' => 'string',
                ],
            ],
        ];
    }
}
