<?php

/**
 * Subscription Admin Hooks
 *
 * Registers WordPress hooks for admin subscription management.
 *
 * @package ArraySubs\Features\SubscriptionAdmin\Services
 * @since 1.0.0
 */

namespace ArraySubs\Features\SubscriptionAdmin\Services;

defined('ABSPATH') || exit;

/**
 * Admin hooks integration
 */
class Hooks
{
    /**
     * Enable auto-loading via AbstractLoader
     *
     * @var bool
     */
    public static $loadable = true;

    /**
     * Initialize hooks
     */
    public function __construct()
    {
        // Add subscription management capabilities
        add_action('init', [$this, 'addCapabilities']);

        // Format subscription REST API response for admin list
        add_filter('rest_prepare_arraysubs_data', [$this, 'formatSubscriptionRestResponse'], 10, 3);
    }

    /**
     * Add subscription management capabilities to admin role
     *
     * @return void
     */
    public function addCapabilities(): void
    {
        $role = get_role('administrator');

        if ($role) {
            $role->add_cap('manage_subscriptions');
            $role->add_cap('edit_subscriptions');
            $role->add_cap('delete_subscriptions');
        }

        // Add to shop_manager role if WooCommerce is active
        $shop_manager = get_role('shop_manager');
        if ($shop_manager) {
            $shop_manager->add_cap('manage_subscriptions');
            $shop_manager->add_cap('edit_subscriptions');
        }
    }

    /**
     * Format subscription REST API response with additional display data
     *
     * @param \WP_REST_Response $response The response object.
     * @param \WP_Post          $post     The post object.
     * @param \WP_REST_Request  $request  The request object.
     * @return \WP_REST_Response Modified response
     */
    public function formatSubscriptionRestResponse($response, $post, $request)
    {
        $data = $response->get_data();
        $subscription_id = $post->ID;
        $wp_admin_url = admin_url();

        // Get customer data
        $customer_id = (int) get_post_meta($subscription_id, '_customer_id', true);
        $customer_data = [
            'text'    => __('Guest', 'arraysubs'),
            'subtext' => '',
            'href'    => '',
        ];

        if ($customer_id) {
            $user = get_userdata($customer_id);
            if ($user) {
                $full_name = trim($user->first_name . ' ' . $user->last_name);
                $customer_href = $wp_admin_url . 'admin.php?page=wc-admin&path=%2Fcustomers&filter=advanced&username_includes=' . $customer_id;

                /**
                 * Filter the customer link shown in the subscriptions admin list.
                 *
                 * Allows addon features such as member insight to redirect the
                 * customer link to a richer member details screen while keeping
                 * core's WooCommerce customer page as the fallback.
                 *
                 * @param string   $customer_href    Default admin URL.
                 * @param int      $customer_id      WordPress user ID.
                 * @param int      $subscription_id  Subscription post ID.
                 * @param \WP_User $user            Customer user object.
                 */
                $customer_href = apply_filters(
                    'arraysubs_subscription_admin_customer_link',
                    $customer_href,
                    $customer_id,
                    $subscription_id,
                    $user
                );

                $customer_data = [
                    'text'    => $full_name ?: $user->display_name,
                    'subtext' => $user->user_email,
                    'href'    => $customer_href,
                ];
            }
        }
        $data['_customer_display'] = $customer_data;

        // Get product data
        $product_id = (int) get_post_meta($subscription_id, '_product_id', true);
        $billing_interval = (int) get_post_meta($subscription_id, '_billing_interval', true) ?: 1;
        $billing_period = get_post_meta($subscription_id, '_billing_period', true) ?: 'month';

        $period_labels = [
            'day'   => _n('day', 'days', $billing_interval, 'arraysubs'),
            'week'  => _n('week', 'weeks', $billing_interval, 'arraysubs'),
            'month' => _n('month', 'months', $billing_interval, 'arraysubs'),
            'year'  => _n('year', 'years', $billing_interval, 'arraysubs'),
        ];
        $billing_cycle = sprintf(
            /* translators: 1: billing interval number, 2: period name in plural (e.g., "weeks", "months") */
            __('Every %1$d %2$s', 'arraysubs'),
            $billing_interval,
            $period_labels[$billing_period] ?? $billing_period
        );

        $product_data = [
            'text'    => __('No product', 'arraysubs'),
            'subtext' => $billing_cycle,
            'href'    => '',
        ];

        if ($product_id && function_exists('wc_get_product')) {
            $product = wc_get_product($product_id);
            if ($product) {
                $product_data = [
                    'text'    => arraysubs_get_subscription_product_name_by_subscription($subscription_id),
                    'subtext' => $billing_cycle,
                    'href'    => $wp_admin_url . 'post.php?post=' . $product_id . '&action=edit',
                ];
            }
        }
        $data['_product_display'] = $product_data;

        // Get next payment date with subscription start date as subtext
        $next_payment_date = get_post_meta($subscription_id, '_next_payment_date', true);
        $start_date = get_post_meta($subscription_id, '_start_date', true);

        $next_payment_data = [
            'text'    => $next_payment_date && $next_payment_date !== '0000-00-00 00:00:00'
                ? arraysubs_format_date_local($next_payment_date, \get_option('date_format'))
                : __('—', 'arraysubs'),
            'subtext' => $start_date
                /* translators: %s: subscription start date */
                ? sprintf(__('Since %s', 'arraysubs'), arraysubs_format_date_local($start_date, \get_option('date_format')))
                : '',
            'href'    => '',
        ];
        $data['_next_payment_display'] = $next_payment_data;

        $response->set_data($data);

        return $response;
    }
}
