<?php
/**
 * Puts the withdrawal button where the customer expects it.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Wc;

use SkyServers\Retragere\Wp\Settings;
use WC_Order;

/**
 * The public page stays the legally required, permanently available function.
 * These buttons are convenience on top of it.
 */
final class MyAccount
{
    public static function register(): void
    {
        add_filter('woocommerce_my_account_my_orders_actions', [self::class, 'actions'], 10, 2);
        add_action('wp_enqueue_scripts', [self::class, 'styles']);
    }

    /**
     * The account pages never render the shortcode, so the plugin stylesheet
     * would not load there on its own.
     */
    public static function styles(): void
    {
        if (!function_exists('is_account_page') || !is_account_page()) {
            return;
        }

        wp_enqueue_style('ssrc-form', SSRC_URL . 'assets/form.css', [], SSRC_VERSION);
    }

    /**
     * @param array<string,array<string,string>> $actions
     * @param WC_Order                           $order
     *
     * @return array<string,array<string,string>>
     */
    public static function actions(array $actions, $order): array
    {
        // The thank you page renders the same order details template, so this
        // filter fires there too. Offering a withdrawal seconds after checkout
        // is absurd, and reads as an invitation to change your mind.
        if (function_exists('is_order_received_page') && is_order_received_page()) {
            return $actions;
        }

        // One filter feeds two screens: the order list and, on themes that
        // render an actions row, the single order page. The setting is meant
        // for the list alone, so the endpoint decides.
        if (
            function_exists('is_wc_endpoint_url')
            && is_wc_endpoint_url('orders')
            && !Settings::get('orders_list_button')
        ) {
            return $actions;
        }

        if (!self::isEligible($order)) {
            return $actions;
        }

        $actions['ssrc_withdraw'] = [
            'url'  => self::url($order),
            'name' => (string) Settings::get('button_label'),
        ];

        return $actions;
    }

    /**
     * @param WC_Order $order
     */
    public static function isEligible($order): bool
    {
        if (!$order instanceof WC_Order) {
            return false;
        }

        $evaluation = OrderEvaluation::forOrder($order);

        return (bool) $evaluation['eligible'];
    }

    /**
     * @param WC_Order $order
     */
    private static function url($order): string
    {
        $pageId = (int) Settings::get('page_id');
        $base   = $pageId > 0 ? (string) get_permalink($pageId) : home_url('/');

        return add_query_arg('ssrc_order', (int) $order->get_id(), $base);
    }
}
