<?php
/**
 * Profit Warden — Order List Enhancements
 *
 * Adds a "💰 Profit" column to the WooCommerce order list (Legacy + HPOS)
 * and a "Recalculate Profit" bulk action.
 *
 * @package ProfitWarden
 * @since   3.2.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// ============================================================
// FEATURE 1: PROFIT COLUMN
// ============================================================

/**
 * Returns the HTML for the profit cell given a WC_Order object.
 *
 * @param WC_Order $order The WooCommerce order.
 * @return string HTML string.
 */
function profwabr_get_profit_column_html( $order ) {
    if ( ! $order instanceof WC_Abstract_Order ) {
        return '<span style="color:#ccc;" title="' . esc_attr__( 'Invalid order', 'profit-warden' ) . '">–</span>';
    }

    $data = $order->get_meta( '_profwabr_profit_analysis_data', true );

    if ( empty( $data ) || ! is_array( $data ) || empty( $data['summary'] ) ) {
        return '<span style="color:#ccc; cursor:help;" title="' . esc_attr__( 'Sync required — place a new order or use Bulk Recalculate.', 'profit-warden' ) . '">–</span>';
    }

    $summary    = $data['summary'];
    $net_profit = isset( $summary['net_profit'] ) ? (float) $summary['net_profit'] : 0.0;
    $margin     = isset( $summary['margin_percentage'] ) ? (float) $summary['margin_percentage'] : 0.0;

    if ( $net_profit > 0 ) {
        $color = '#00a32a'; // green
    } elseif ( $net_profit < 0 ) {
        $color = '#d63638'; // red
    } else {
        $color = '#6c757d'; // grey
    }

    return sprintf(
        '<div style="font-weight:600; color:%s; white-space:nowrap;">%s <small style="opacity:0.75; font-weight:400;">(%s%%)</small></div>',
        esc_attr( $color ),
        wp_kses_post( wc_price( $net_profit ) ),
        esc_html( number_format( $margin, 1 ) )
    );
}

/**
 * Adds the Profit column header — shared callback for both Legacy and HPOS.
 *
 * @param array $columns Existing columns.
 * @return array Modified columns.
 */
function profwabr_add_order_profit_column( $columns ) {
    $columns['profwabr_profit'] = esc_html__( '💰 Profit', 'profit-warden' );
    return $columns;
}

// Legacy orders table (CPT-based)
add_filter( 'manage_edit-shop_order_columns', 'profwabr_add_order_profit_column' );
// HPOS orders table
add_filter( 'manage_woocommerce_page_wc-orders_columns', 'profwabr_add_order_profit_column' );

/**
 * Renders the Profit cell — Legacy (CPT) version.
 *
 * @param string $column  Column ID.
 * @param int    $post_id Post / Order ID.
 */
function profwabr_render_profit_column_legacy( $column, $post_id ) {
    if ( 'profwabr_profit' !== $column ) {
        return;
    }
    $order = wc_get_order( $post_id );
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML produced by helper already escaped
    echo profwabr_get_profit_column_html( $order );
}
add_action( 'manage_shop_order_posts_custom_column', 'profwabr_render_profit_column_legacy', 10, 2 );

/**
 * Renders the Profit cell — HPOS version.
 *
 * @param string    $column Column ID.
 * @param WC_Order  $order  WooCommerce order object.
 */
function profwabr_render_profit_column_hpos( $column, $order ) {
    if ( 'profwabr_profit' !== $column ) {
        return;
    }
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML produced by helper already escaped
    echo profwabr_get_profit_column_html( $order );
}
add_action( 'manage_woocommerce_page_wc-orders_custom_column', 'profwabr_render_profit_column_hpos', 10, 2 );


// ============================================================
// FEATURE 2: BULK ACTION — RECALCULATE PROFIT
// ============================================================

/**
 * Adds the bulk action to order list — Legacy.
 *
 * @param array $actions Existing bulk actions.
 * @return array Modified bulk actions.
 */
function profwabr_add_bulk_action_legacy( $actions ) {
    $actions['profwabr_recalculate'] = __( 'Recalculate Profit (Profit Warden)', 'profit-warden' );
    return $actions;
}
add_filter( 'bulk_actions-edit-shop_order', 'profwabr_add_bulk_action_legacy' );

/**
 * Adds the bulk action to order list — HPOS.
 *
 * @param array $actions Existing bulk actions.
 * @return array Modified bulk actions.
 */
function profwabr_add_bulk_action_hpos( $actions ) {
    $actions['profwabr_recalculate'] = __( 'Recalculate Profit (Profit Warden)', 'profit-warden' );
    return $actions;
}
add_filter( 'bulk_actions-woocommerce_page_wc-orders', 'profwabr_add_bulk_action_hpos' );

/**
 * Central handler for the bulk recalculate action.
 * Queues each selected order for background profit recalculation via Action Scheduler.
 *
 * @param string $redirect_url Redirect URL after bulk action.
 * @param string $action       Bulk action name.
 * @param array  $order_ids    Array of selected order IDs.
 * @return string Modified redirect URL.
 */
function profwabr_handle_bulk_recalculate( $redirect_url, $action, $order_ids ) {
    if ( 'profwabr_recalculate' !== $action ) {
        return $redirect_url;
    }

    if ( ! current_user_can( 'manage_woocommerce' ) ) {
        return $redirect_url;
    }

    if ( ! function_exists( 'as_schedule_single_action' ) ) {
        // Action Scheduler not available — skip silently.
        return add_query_arg( 'profwabr_bulk_error', '1', $redirect_url );
    }

    $queued = 0;
    foreach ( $order_ids as $order_id ) {
        $order_id = absint( $order_id );
        if ( $order_id <= 0 ) {
            continue;
        }
        as_schedule_single_action(
            time() + 5,
            'profwabr_run_background_analysis',
            array( 'order_id' => $order_id ),
            'profit-warden'
        );
        ++$queued;
    }

    return add_query_arg( 'profwabr_bulk_queued', $queued, $redirect_url );
}
add_filter( 'handle_bulk_actions-edit-shop_order', 'profwabr_handle_bulk_recalculate', 10, 3 );
add_filter( 'handle_bulk_actions-woocommerce_page_wc-orders', 'profwabr_handle_bulk_recalculate', 10, 3 );

/**
 * Displays an admin notice after the bulk recalculate action has been performed.
 */
function profwabr_bulk_recalculate_admin_notice() {
    if ( ! isset( $_GET['profwabr_bulk_queued'] ) && ! isset( $_GET['profwabr_bulk_error'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        return;
    }

    if ( isset( $_GET['profwabr_bulk_error'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        echo '<div class="notice notice-error is-dismissible"><p>';
        echo '<strong>Profit Warden:</strong> ' . esc_html__( 'Bulk recalculation failed — Action Scheduler not available. Make sure WooCommerce is up to date.', 'profit-warden' );
        echo '</p></div>';
        return;
    }

    $queued = absint( $_GET['profwabr_bulk_queued'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    echo '<div class="notice notice-success is-dismissible"><p>';
    echo '<strong>🛡️ Profit Warden:</strong> ';
    /* translators: %d: number of orders queued for recalculation */
    echo esc_html( sprintf( _n( '%d order queued for profit recalculation.', '%d orders queued for profit recalculation.', $queued, 'profit-warden' ), $queued ) );
    echo '</p></div>';
}
add_action( 'admin_notices', 'profwabr_bulk_recalculate_admin_notice' );
