<?php

namespace WeDevs\AppBridge\Integrations\WooCommerce;

use WeDevs\AppBridge\Core\Contracts\Hookable;
use WP_REST_Response;

class OrderHooks implements Hookable {
    public function register_hooks(): void {
        add_filter( 'woocommerce_rest_prepare_shop_order_object', [ $this, 'add_invoices_to_rest_api' ], 10, 1 );
        add_filter( 'woocommerce_rest_prepare_shop_order_object', [ $this, 'add_status_name_to_rest_api' ] );
    }

    /**
     * Add pdf invoice download link as metadata
     *
     * @since 1.2.2
     *
     * @param WP_REST_Response $response
     *
     * @return mixed
     */
    public function add_invoices_to_rest_api( $response ) {
        // Check if response has data
        if ( empty( $response->data ) || ! class_exists( 'WPO_WCPDF' ) ) {
            return $response;
        }

        $debug_settings = get_option( 'wpo_wcpdf_settings_debug', [] );
        if ( ! isset( $debug_settings['document_link_access_type'] ) ) {
            return $response;
        }

        // get pdf url
        $pdf_url = admin_url( 'admin-ajax.php?action=generate_wpo_wcpdf&template_type=invoice&order_ids=' . $response->data['id'] . '&order_key=' . $response->data['order_key'] );

        // Add _wcpdf_document_link value to response
        $response->data['_wcpdf_document_link'] = esc_url_raw( $pdf_url );

        return $response;
    }
    /**
     * Add status name or title in response.
     *
     * @since 1.2.3
     *
     * @param WP_REST_Response $response Rest Response.
     *
     * @return WP_REST_Response
     */
    public function add_status_name_to_rest_api( $response ) {
        $response->data['status_title'] = wc_get_order_status_name( $response->data['status'] );

        return $response;
    }
}
