<?php
/**
 * Admin Dashboard — Return Requests list with filters, inline status update, CSV export.
 *
 * @package WPNest_Returns_For_WooCommerce
 */

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

class WPNest_RFW_Admin_Dashboard {

    const PAGE_SLUG          = 'wpnest-rfw-requests';
    const PENDING_TRANSIENT  = 'wpnest_rfw_pending_count';

    private static $instance = null;

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action( 'admin_menu', array( $this, 'register_menu' ), 60 );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );

        // Refresh the pending count badge whenever the underlying data changes.
        add_action( 'wpnest_rfw_status_changed', array( __CLASS__, 'bust_pending_cache' ) );
        add_action( 'wpnest_rfw_request_submitted', array( __CLASS__, 'bust_pending_cache' ) );
    }

    public function register_menu() {
        $pending     = self::get_pending_count();
        $base_label  = __( 'Return Requests', 'wpnest-returns-for-woocommerce' );
        $menu_label  = $pending > 0
            ? sprintf(
                '%s <span class="awaiting-mod count-%d"><span class="pending-count">%s</span></span>',
                esc_html( $base_label ),
                (int) $pending,
                esc_html( number_format_i18n( $pending ) )
            )
            : $base_label;

        add_submenu_page(
            'woocommerce',
            $base_label,
            $menu_label,
            'manage_woocommerce',
            self::PAGE_SLUG,
            array( $this, 'render' )
        );
    }

    /**
     * Cached count of return requests in the "pending" status. Cache TTL 5 minutes;
     * busted on every status change via `wpnest_rfw_status_changed` and on submit.
     */
    public static function get_pending_count() {
        $cached = get_transient( self::PENDING_TRANSIENT );
        if ( false !== $cached ) {
            return (int) $cached;
        }
        $count = (int) WPNest_RFW_Request_Model::get_total( array( 'status' => WPNest_RFW_Request_Model::STATUS_PENDING ) );
        set_transient( self::PENDING_TRANSIENT, $count, 5 * MINUTE_IN_SECONDS );
        return $count;
    }

    public static function bust_pending_cache() {
        delete_transient( self::PENDING_TRANSIENT );
    }

    public function enqueue_assets( $hook ) {
        if ( 'woocommerce_page_' . self::PAGE_SLUG !== $hook ) {
            return;
        }
        wp_enqueue_style( 'wpnest-rfw-admin', WPNEST_RFW_PLUGIN_URL . 'assets/css/admin.css', array(), WPNEST_RFW_VERSION );
        wp_enqueue_script( 'wpnest-rfw-admin', WPNEST_RFW_PLUGIN_URL . 'assets/js/admin.js', array( 'jquery' ), WPNEST_RFW_VERSION, true );
        wp_localize_script(
            'wpnest-rfw-admin',
            'wpnest_rfw_admin',
            array(
                'rest_url' => esc_url_raw( rest_url( 'wpnest-rfw/v1' ) ),
                'nonce'    => wp_create_nonce( 'wp_rest' ),
                'i18n'     => array(
                    'updating'    => __( 'Updating…', 'wpnest-returns-for-woocommerce' ),
                    'update'      => __( 'Update', 'wpnest-returns-for-woocommerce' ),
                    'update_ok'   => __( 'Status updated.', 'wpnest-returns-for-woocommerce' ),
                    'update_fail' => __( 'Could not update status.', 'wpnest-returns-for-woocommerce' ),
                    'no_results'  => __( 'No return requests yet.', 'wpnest-returns-for-woocommerce' ),
                ),
            )
        );
    }

    public function render() {
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only routing parameter on admin list page.
        $detail_id = isset( $_GET['request_id'] ) ? (int) $_GET['request_id'] : 0;
        if ( $detail_id > 0 ) {
            $this->render_detail( $detail_id );
            return;
        }

        $args = $this->parse_filters();
        $items = WPNest_RFW_Request_Model::get_list( $args );
        $total = WPNest_RFW_Request_Model::get_total( $args );
        $pages = max( 1, (int) ceil( $total / $args['per_page'] ) );
        ?>
        <div class="wrap wpnph-app">
            <div class="wpnph-hero">
                <div class="wpnph-hero__brand">
                    <span class="dashicons dashicons-list-view"></span>
                    <h1 class="wpnph-hero__title"><?php esc_html_e( 'Return Requests', 'wpnest-returns-for-woocommerce' ); ?></h1>
                </div>
                <p class="wpnph-hero__lede">
                    <?php
                    /* translators: %d: total */
                    echo esc_html( sprintf( _n( '%d request total.', '%d requests total.', (int) $total, 'wpnest-returns-for-woocommerce' ), (int) $total ) );
                    ?>
                </p>
            </div>

            <div class="wpnph-card">
                <div class="wpnph-card__body">
                    <form method="get" class="wpnest-rfw-filters">
                        <input type="hidden" name="page" value="<?php echo esc_attr( self::PAGE_SLUG ); ?>">

                        <select name="status">
                            <option value=""><?php esc_html_e( 'All statuses', 'wpnest-returns-for-woocommerce' ); ?></option>
                            <?php foreach ( WPNest_RFW_Request_Model::get_statuses() as $key => $label ) : ?>
                                <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $args['status'], $key ); ?>><?php echo esc_html( $label ); ?></option>
                            <?php endforeach; ?>
                        </select>

                        <input type="date" name="date_from" value="<?php echo esc_attr( (string) $args['date_from'] ); ?>" placeholder="<?php esc_attr_e( 'From', 'wpnest-returns-for-woocommerce' ); ?>">
                        <input type="date" name="date_to" value="<?php echo esc_attr( (string) $args['date_to'] ); ?>" placeholder="<?php esc_attr_e( 'To', 'wpnest-returns-for-woocommerce' ); ?>">
                        <input type="number" name="order_id" value="<?php echo esc_attr( $args['order_id'] ? (int) $args['order_id'] : '' ); ?>" placeholder="<?php esc_attr_e( 'Order ID', 'wpnest-returns-for-woocommerce' ); ?>" min="1" class="small-text">

                        <button type="submit" class="button"><?php esc_html_e( 'Filter', 'wpnest-returns-for-woocommerce' ); ?></button>
                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=' . self::PAGE_SLUG ) ); ?>" class="button"><?php esc_html_e( 'Reset', 'wpnest-returns-for-woocommerce' ); ?></a>
                        <button type="button" class="button button-secondary" id="wpnest-rfw-export-csv"><?php esc_html_e( 'Export CSV', 'wpnest-returns-for-woocommerce' ); ?></button>
                    </form>
                </div>
            </div>

            <table class="wp-list-table widefat striped wpnest-rfw-list">
                <thead>
                    <tr>
                        <th></th>
                        <th><?php esc_html_e( '#', 'wpnest-returns-for-woocommerce' ); ?></th>
                        <th><?php esc_html_e( 'Order', 'wpnest-returns-for-woocommerce' ); ?></th>
                        <th><?php esc_html_e( 'Customer', 'wpnest-returns-for-woocommerce' ); ?></th>
                        <th><?php esc_html_e( 'Submitted', 'wpnest-returns-for-woocommerce' ); ?></th>
                        <th><?php esc_html_e( 'Status', 'wpnest-returns-for-woocommerce' ); ?></th>
                        <th><?php esc_html_e( 'Actions', 'wpnest-returns-for-woocommerce' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ( empty( $items ) ) : ?>
                        <tr><td colspan="7" class="wpnph-empty"><?php esc_html_e( 'No return requests match the current filters.', 'wpnest-returns-for-woocommerce' ); ?></td></tr>
                    <?php else : foreach ( $items as $row ) : $this->render_row( $row ); endforeach; endif; ?>
                </tbody>
            </table>

            <?php if ( $pages > 1 ) : ?>
                <div class="tablenav bottom">
                    <div class="tablenav-pages">
                        <?php
                        echo wp_kses_post( paginate_links( array(
                            'base'      => add_query_arg( 'paged', '%#%' ),
                            'format'    => '',
                            'current'   => $args['page'],
                            'total'     => $pages,
                            'prev_text' => '&laquo;',
                            'next_text' => '&raquo;',
                        ) ) );
                        ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }

    private function render_row( $row ) {
        $order        = wc_get_order( (int) $row->order_id );
        $order_number = $order instanceof WC_Order ? $order->get_order_number() : (string) $row->order_id;
        $billing_name = '';
        $billing_mail = '';
        if ( $order instanceof WC_Order ) {
            $billing_name = trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() );
            $billing_mail = (string) $order->get_billing_email();
        }
        $statuses = WPNest_RFW_Request_Model::get_statuses();
        $pdf_url  = $row->pdf_path ? WPNest_RFW_PDF_Generator::get_confirmation_url( (int) $row->id ) : '';
        ?>
        <?php $detail_url = admin_url( 'admin.php?page=' . self::PAGE_SLUG . '&request_id=' . (int) $row->id ); ?>
        <tr class="wpnest-rfw-list__row" data-request-id="<?php echo esc_attr( (int) $row->id ); ?>">
            <td>
                <a class="button button-small" href="<?php echo esc_url( $detail_url ); ?>" aria-label="<?php esc_attr_e( 'Open request details', 'wpnest-returns-for-woocommerce' ); ?>">
                    <?php esc_html_e( 'View →', 'wpnest-returns-for-woocommerce' ); ?>
                </a>
            </td>
            <td><a href="<?php echo esc_url( $detail_url ); ?>">#<?php echo esc_html( (int) $row->id ); ?></a></td>
            <td>
                <?php if ( $order ) : ?>
                    <a href="<?php echo esc_url( $order->get_edit_order_url() ); ?>">#<?php echo esc_html( $order_number ); ?></a>
                <?php else : ?>
                    #<?php echo esc_html( $order_number ); ?>
                <?php endif; ?>
            </td>
            <td>
                <?php echo esc_html( $billing_name ); ?>
                <?php if ( $billing_mail ) : ?>
                    <br><small><?php echo esc_html( $billing_mail ); ?></small>
                <?php endif; ?>
            </td>
            <td><?php echo esc_html( mysql2date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), (string) $row->created_at, true ) ); ?></td>
            <td>
                <span class="wpnph-badge wpnph-badge--<?php echo esc_attr( $this->status_badge_class( (string) $row->status ) ); ?>">
                    <?php echo esc_html( isset( $statuses[ $row->status ] ) ? $statuses[ $row->status ] : ucfirst( (string) $row->status ) ); ?>
                </span>
            </td>
            <td>
                <select class="wpnest-rfw-list__status">
                    <?php foreach ( $statuses as $key => $label ) : ?>
                        <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $row->status, $key ); ?>><?php echo esc_html( $label ); ?></option>
                    <?php endforeach; ?>
                </select>
                <button type="button" class="button button-small wpnest-rfw-list__update"><?php esc_html_e( 'Update', 'wpnest-returns-for-woocommerce' ); ?></button>
            </td>
        </tr>
        <?php
    }

    private function render_items_table( $order, $request_id ) {
        $items = WPNest_RFW_Request_Item_Model::get_for_request( (int) $request_id );
        if ( empty( $items ) ) {
            ?>
            <p><em><?php esc_html_e( 'No itemized data — see the linked order.', 'wpnest-returns-for-woocommerce' ); ?></em></p>
            <?php
            return;
        }
        ?>
        <table class="widefat striped wpnest-rfw-list__items">
            <thead>
                <tr>
                    <th style="width:60px"><?php esc_html_e( 'Qty', 'wpnest-returns-for-woocommerce' ); ?></th>
                    <th><?php esc_html_e( 'Item', 'wpnest-returns-for-woocommerce' ); ?></th>
                    <th><?php esc_html_e( 'Reason', 'wpnest-returns-for-woocommerce' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $items as $ir ) :
                    $name = '';
                    if ( $order instanceof WC_Order ) {
                        $oi = $order->get_item( (int) $ir->order_item_id );
                        if ( $oi ) { $name = $oi->get_name(); }
                    }
                    if ( '' === $name && $ir->product_id ) {
                        $p = wc_get_product( (int) $ir->product_id );
                        $name = $p ? $p->get_name() : ( '#' . (int) $ir->product_id );
                    }
                    $reason_label = WPNest_RFW_Reason_Codes::get_label( (string) $ir->reason_code );
                ?>
                    <tr>
                        <td><?php echo esc_html( (int) $ir->qty ); ?></td>
                        <td><?php echo esc_html( $name ); ?></td>
                        <td>
                            <?php echo esc_html( $reason_label ); ?>
                            <?php if ( $ir->reason_text ) : ?>
                                <br><small><em>&ldquo;<?php echo esc_html( (string) $ir->reason_text ); ?>&rdquo;</em></small>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php
    }

    private function status_badge_class( $status ) {
        switch ( $status ) {
            case WPNest_RFW_Request_Model::STATUS_ACCEPTED: return 'accent';
            case WPNest_RFW_Request_Model::STATUS_REJECTED: return 'err';
            case WPNest_RFW_Request_Model::STATUS_REFUNDED: return 'ok';
            case WPNest_RFW_Request_Model::STATUS_PENDING:
            default: return 'warn';
        }
    }

    private function parse_filters() {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only filter on admin list.
        return array(
            'status'    => isset( $_GET['status'] ) ? sanitize_key( wp_unslash( $_GET['status'] ) ) : '',
            'date_from' => isset( $_GET['date_from'] ) ? sanitize_text_field( wp_unslash( $_GET['date_from'] ) ) : '',
            'date_to'   => isset( $_GET['date_to'] ) ? sanitize_text_field( wp_unslash( $_GET['date_to'] ) ) : '',
            'order_id'  => isset( $_GET['order_id'] ) ? (int) $_GET['order_id'] : 0,
            'page'      => isset( $_GET['paged'] ) ? max( 1, (int) $_GET['paged'] ) : 1,
            'per_page'  => 20,
        );
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
    }

    /**
     * Full detail page for a single return request — everything an admin needs
     * to act on a return without opening the WC order edit screen.
     */
    public function render_detail( $request_id ) {
        $request = WPNest_RFW_Request_Model::get( (int) $request_id );
        $list_url = admin_url( 'admin.php?page=' . self::PAGE_SLUG );
        if ( ! $request ) {
            ?>
            <div class="wrap wpnph-app">
                <p><a href="<?php echo esc_url( $list_url ); ?>">&larr; <?php esc_html_e( 'Back to all requests', 'wpnest-returns-for-woocommerce' ); ?></a></p>
                <div class="wpnph-empty"><?php esc_html_e( 'Return request not found.', 'wpnest-returns-for-woocommerce' ); ?></div>
            </div>
            <?php
            return;
        }

        $order        = wc_get_order( (int) $request->order_id );
        $order_number = $order instanceof WC_Order ? $order->get_order_number() : (string) $request->order_id;
        $statuses     = WPNest_RFW_Request_Model::get_statuses();
        $status_label = isset( $statuses[ $request->status ] ) ? $statuses[ $request->status ] : ucfirst( (string) $request->status );
        $badge_class  = $this->status_badge_class( (string) $request->status );
        ?>
        <div class="wrap wpnph-app wpnest-rfw-detail" data-request-id="<?php echo esc_attr( (int) $request->id ); ?>">
            <p class="wpnest-rfw-detail__back">
                <a href="<?php echo esc_url( $list_url ); ?>">&larr; <?php esc_html_e( 'Back to all requests', 'wpnest-returns-for-woocommerce' ); ?></a>
            </p>

            <div class="wpnph-hero wpnest-rfw-detail__hero">
                <div class="wpnph-hero__brand">
                    <span class="dashicons dashicons-update"></span>
                    <h1 class="wpnph-hero__title">
                        <?php
                        printf(
                            /* translators: 1: return request ID, 2: order number */
                            esc_html__( 'Request #%1$d for Order #%2$s', 'wpnest-returns-for-woocommerce' ),
                            (int) $request->id,
                            esc_html( $order_number )
                        );
                        ?>
                    </h1>
                </div>
                <p class="wpnph-hero__lede">
                    <span class="wpnph-badge wpnph-badge--<?php echo esc_attr( $badge_class ); ?>"><?php echo esc_html( $status_label ); ?></span>
                    <?php if ( $order ) : ?>
                        &nbsp;·&nbsp;<a href="<?php echo esc_url( $order->get_edit_order_url() ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Open order in WooCommerce →', 'wpnest-returns-for-woocommerce' ); ?></a>
                    <?php endif; ?>
                </p>
            </div>

            <div class="wpnest-rfw-detail__grid">
                <div class="wpnest-rfw-detail__main">
                    <?php $this->render_detail_items( $order, $request ); ?>
                    <?php $this->render_detail_status_form( $request, $statuses ); ?>
                    <?php $this->render_detail_refund( $order, $request ); ?>
                    <?php $this->render_detail_notes( $order, $request ); ?>
                    <?php $this->render_detail_history( $request ); ?>
                    <?php
                    /**
                     * Slot for Pro / third-party modules to append UI to the request detail page
                     * (threaded messages metabox, courier label panel, etc.).
                     */
                    do_action( 'wpnest_rfw_request_detail_after', (int) $request->id, $request, $order );
                    ?>
                </div>
                <aside class="wpnest-rfw-detail__side">
                    <?php $this->render_detail_customer( $order, $request ); ?>
                </aside>
            </div>
        </div>
        <?php
    }

    private function render_detail_customer( $order, $request ) {
        ?>
        <div class="wpnph-card">
            <div class="wpnph-card__header"><h2 class="wpnph-card__title"><?php esc_html_e( 'Customer & order', 'wpnest-returns-for-woocommerce' ); ?></h2></div>
            <div class="wpnph-card__body wpnest-rfw-detail__customer">
                <?php if ( ! $order instanceof WC_Order ) : ?>
                    <p><em><?php esc_html_e( 'The linked order is missing.', 'wpnest-returns-for-woocommerce' ); ?></em></p>
                    <?php return; ?>
                <?php endif; ?>

                <p class="wpnest-rfw-detail__customer-name"><strong><?php echo esc_html( trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ) ); ?></strong></p>
                <?php if ( $order->get_billing_email() ) : ?>
                    <p><a href="mailto:<?php echo esc_attr( $order->get_billing_email() ); ?>"><?php echo esc_html( $order->get_billing_email() ); ?></a></p>
                <?php endif; ?>
                <?php if ( $order->get_billing_phone() ) : ?>
                    <p><a href="tel:<?php echo esc_attr( preg_replace( '/[^0-9+]/', '', $order->get_billing_phone() ) ); ?>"><?php echo esc_html( $order->get_billing_phone() ); ?></a></p>
                <?php endif; ?>

                <h3><?php esc_html_e( 'Billing address', 'wpnest-returns-for-woocommerce' ); ?></h3>
                <address><?php echo wp_kses_post( $order->get_formatted_billing_address() ?: '—' ); ?></address>

                <?php if ( $order->get_formatted_shipping_address() && $order->get_formatted_shipping_address() !== $order->get_formatted_billing_address() ) : ?>
                    <h3><?php esc_html_e( 'Shipping address', 'wpnest-returns-for-woocommerce' ); ?></h3>
                    <address><?php echo wp_kses_post( $order->get_formatted_shipping_address() ); ?></address>
                <?php endif; ?>

                <h3><?php esc_html_e( 'Order summary', 'wpnest-returns-for-woocommerce' ); ?></h3>
                <ul class="wpnest-rfw-detail__order-summary">
                    <li><strong><?php esc_html_e( 'Date:', 'wpnest-returns-for-woocommerce' ); ?></strong> <?php echo esc_html( wc_format_datetime( $order->get_date_created() ) ); ?></li>
                    <li><strong><?php esc_html_e( 'Total:', 'wpnest-returns-for-woocommerce' ); ?></strong> <?php echo wp_kses_post( $order->get_formatted_order_total() ); ?></li>
                    <li><strong><?php esc_html_e( 'Refunded:', 'wpnest-returns-for-woocommerce' ); ?></strong> <?php echo wp_kses_post( wc_price( $order->get_total_refunded(), array( 'currency' => $order->get_currency() ) ) ); ?></li>
                    <li><strong><?php esc_html_e( 'Payment:', 'wpnest-returns-for-woocommerce' ); ?></strong> <?php echo esc_html( $order->get_payment_method_title() ?: $order->get_payment_method() ?: '—' ); ?></li>
                    <li><strong><?php esc_html_e( 'Order status:', 'wpnest-returns-for-woocommerce' ); ?></strong> <?php echo esc_html( wc_get_order_status_name( $order->get_status() ) ); ?></li>
                </ul>
            </div>
        </div>
        <?php
    }

    private function render_detail_items( $order, $request ) {
        $items = WPNest_RFW_Request_Item_Model::get_for_request( (int) $request->id );
        ?>
        <div class="wpnph-card">
            <div class="wpnph-card__header"><h2 class="wpnph-card__title"><?php esc_html_e( 'Returned items', 'wpnest-returns-for-woocommerce' ); ?></h2></div>
            <div class="wpnph-card__body">
                <?php if ( empty( $items ) ) : ?>
                    <p><em><?php esc_html_e( 'No itemized data for this request.', 'wpnest-returns-for-woocommerce' ); ?></em></p>
                <?php else : ?>
                    <table class="widefat striped wpnest-rfw-detail__items">
                        <thead>
                            <tr>
                                <th><?php esc_html_e( 'Item', 'wpnest-returns-for-woocommerce' ); ?></th>
                                <th style="width:80px"><?php esc_html_e( 'Qty', 'wpnest-returns-for-woocommerce' ); ?></th>
                                <th><?php esc_html_e( 'Reason', 'wpnest-returns-for-woocommerce' ); ?></th>
                                <th style="width:120px"><?php esc_html_e( 'Refundable', 'wpnest-returns-for-woocommerce' ); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ( $items as $ir ) :
                                $product_name = '';
                                $remaining_total = 0.0;
                                $remaining_qty = 0;
                                if ( $order instanceof WC_Order ) {
                                    $oi = $order->get_item( (int) $ir->order_item_id );
                                    if ( $oi instanceof WC_Order_Item_Product ) {
                                        $product_name = $oi->get_name();
                                        $remaining_total = WPNest_RFW_Refund_Service::remaining_total( $order, (int) $ir->order_item_id );
                                        $remaining_qty = WPNest_RFW_Refund_Service::remaining_qty( $order, (int) $ir->order_item_id );
                                    }
                                }
                                $reason_label = WPNest_RFW_Reason_Codes::get_label( (string) $ir->reason_code );
                            ?>
                                <tr>
                                    <td><?php echo esc_html( $product_name ?: ( '#' . (int) $ir->product_id ) ); ?></td>
                                    <td><?php echo esc_html( (int) $ir->qty ); ?></td>
                                    <td>
                                        <?php echo esc_html( $reason_label ); ?>
                                        <?php if ( $ir->reason_text ) : ?>
                                            <br><small><em>&ldquo;<?php echo esc_html( (string) $ir->reason_text ); ?>&rdquo;</em></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ( $order instanceof WC_Order ) : ?>
                                            <?php echo wp_kses_post( wc_price( $remaining_total, array( 'currency' => $order->get_currency() ) ) ); ?>
                                            <br><small><?php
                                            /* translators: %d: remaining refundable quantity */
                                            printf( esc_html__( '%d left', 'wpnest-returns-for-woocommerce' ), (int) $remaining_qty ); ?></small>
                                        <?php else : ?> — <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>

                <?php
                $pdf_url = $request->pdf_path ? WPNest_RFW_PDF_Generator::get_confirmation_url( (int) $request->id ) : '';
                if ( $pdf_url ) :
                ?>
                    <p style="margin-top:14px"><a class="button" href="<?php echo esc_url( $pdf_url ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Download confirmation PDF', 'wpnest-returns-for-woocommerce' ); ?></a></p>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }

    private function render_detail_status_form( $request, $statuses ) {
        ?>
        <div class="wpnph-card">
            <div class="wpnph-card__header"><h2 class="wpnph-card__title"><?php esc_html_e( 'Status & quick actions', 'wpnest-returns-for-woocommerce' ); ?></h2></div>
            <div class="wpnph-card__body wpnest-rfw-detail__status">
                <form class="wpnest-rfw-detail__status-form">
                    <div class="wpnph-row">
                        <div class="wpnph-row__label"><?php esc_html_e( 'New status', 'wpnest-returns-for-woocommerce' ); ?></div>
                        <div class="wpnph-row__control">
                            <select name="new_status" class="wpnest-rfw-detail__status-select">
                                <?php foreach ( $statuses as $key => $label ) : ?>
                                    <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $request->status, $key ); ?>><?php echo esc_html( $label ); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label"><?php esc_html_e( 'Notify customer', 'wpnest-returns-for-woocommerce' ); ?></div>
                        <div class="wpnph-row__control">
                            <?php $global_on = (bool) get_option( 'wpnest_rfw_notify_customer_on_status', 1 ); ?>
                            <label class="wpnph-toggle">
                                <input type="checkbox" name="notify_customer" value="1" <?php checked( $global_on ); ?>>
                                <span class="wpnph-toggle__switch"></span>
                                <span class="wpnph-toggle__text"><?php esc_html_e( 'Email the customer about this status change', 'wpnest-returns-for-woocommerce' ); ?></span>
                            </label>
                            <p class="wpnph-row__hint">
                                <?php
                                if ( $global_on ) {
                                    esc_html_e( 'On by default for every change. Un-check to save this update silently (no email sent).', 'wpnest-returns-for-woocommerce' );
                                } else {
                                    esc_html_e( 'Automatic notifications are globally disabled in Settings → General. Check to send the email for this change only.', 'wpnest-returns-for-woocommerce' );
                                }
                                ?>
                            </p>
                        </div>
                    </div>

                    <div class="wpnph-row">
                        <div class="wpnph-row__label">
                            <label for="wpnest-rfw-status-note"><?php esc_html_e( 'Internal note', 'wpnest-returns-for-woocommerce' ); ?></label>
                        </div>
                        <div class="wpnph-row__control">
                            <textarea id="wpnest-rfw-status-note" name="note" rows="2" class="large-text" placeholder="<?php esc_attr_e( 'Optional — only visible to admins in the history below', 'wpnest-returns-for-woocommerce' ); ?>"></textarea>
                        </div>
                    </div>

                    <p>
                        <button type="submit" class="button button-primary wpnph-btn wpnph-btn--primary"><?php esc_html_e( 'Save status', 'wpnest-returns-for-woocommerce' ); ?></button>
                        <span class="wpnest-rfw-detail__quick" style="margin-left:8px">
                            <button type="button" class="button" data-rfw-quick="accepted"><?php esc_html_e( 'Accept', 'wpnest-returns-for-woocommerce' ); ?></button>
                            <button type="button" class="button" data-rfw-quick="rejected"><?php esc_html_e( 'Reject', 'wpnest-returns-for-woocommerce' ); ?></button>
                            <button type="button" class="button" data-rfw-quick="refunded"><?php esc_html_e( 'Mark refunded', 'wpnest-returns-for-woocommerce' ); ?></button>
                        </span>
                    </p>
                    <div class="wpnest-rfw-detail__feedback" role="status" aria-live="polite"></div>
                </form>
            </div>
        </div>
        <?php
    }

    private function render_detail_refund( $order, $request ) {
        if ( ! $order instanceof WC_Order ) {
            return;
        }
        $remaining = WPNest_RFW_Refund_Service::remaining_refundable( $order );
        $currency  = $order->get_currency();
        $items     = WPNest_RFW_Request_Item_Model::get_for_request( (int) $request->id );
        $refunds   = $order->get_refunds();
        ?>
        <div class="wpnph-card">
            <div class="wpnph-card__header"><h2 class="wpnph-card__title"><?php esc_html_e( 'Issue refund', 'wpnest-returns-for-woocommerce' ); ?></h2></div>
            <div class="wpnph-card__body wpnest-rfw-detail__refund">
                <p class="wpnph-row__hint" style="margin-top:0">
                    <?php
                    printf(
                        /* translators: %s: formatted maximum refundable amount */
                        esc_html__( 'Refundable balance: %s. Refunds are recorded against the WooCommerce order; payment gateways are not contacted automatically.', 'wpnest-returns-for-woocommerce' ),
                        wp_kses_post( wc_price( $remaining, array( 'currency' => $currency ) ) )
                    );
                    ?>
                </p>

                <?php if ( $remaining <= 0 ) : ?>
                    <div class="wpnph-banner wpnph-banner--success">
                        <span class="wpnph-banner__icon">✓</span>
                        <div>
                            <p class="wpnph-banner__title"><?php esc_html_e( 'This order has been fully refunded.', 'wpnest-returns-for-woocommerce' ); ?></p>
                            <p class="wpnph-banner__msg"><?php esc_html_e( 'No further refunds can be issued from here.', 'wpnest-returns-for-woocommerce' ); ?></p>
                        </div>
                    </div>
                <?php else : ?>
                    <form class="wpnest-rfw-detail__refund-form">
                        <table class="widefat wpnest-rfw-detail__refund-items">
                            <thead>
                                <tr>
                                    <th><?php esc_html_e( 'Item', 'wpnest-returns-for-woocommerce' ); ?></th>
                                    <th style="width:80px"><?php esc_html_e( 'Qty', 'wpnest-returns-for-woocommerce' ); ?></th>
                                    <th style="width:160px"><?php esc_html_e( 'Refund', 'wpnest-returns-for-woocommerce' ); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ( $items as $ir ) :
                                    $oi = $order->get_item( (int) $ir->order_item_id );
                                    if ( ! $oi instanceof WC_Order_Item_Product ) {
                                        continue;
                                    }
                                    $remaining_qty   = WPNest_RFW_Refund_Service::remaining_qty( $order, (int) $ir->order_item_id );
                                    $remaining_total = WPNest_RFW_Refund_Service::remaining_total( $order, (int) $ir->order_item_id );
                                    $default_qty     = min( (int) $ir->qty, $remaining_qty );
                                    $unit            = $remaining_qty > 0 ? round( $remaining_total / max( 1, $remaining_qty ), wc_get_price_decimals() ) : 0;
                                    $default_total   = round( $unit * $default_qty, wc_get_price_decimals() );
                                ?>
                                    <tr data-rfw-line="<?php echo esc_attr( (int) $ir->order_item_id ); ?>" data-rfw-unit="<?php echo esc_attr( $unit ); ?>" data-rfw-max-qty="<?php echo esc_attr( $remaining_qty ); ?>">
                                        <td><?php echo esc_html( $oi->get_name() ); ?></td>
                                        <td><input type="number" name="qty" min="0" max="<?php echo esc_attr( $remaining_qty ); ?>" value="<?php echo esc_attr( $default_qty ); ?>" class="small-text wpnest-rfw-detail__refund-qty"></td>
                                        <td><input type="text" name="refund_total" value="<?php echo esc_attr( $default_total ); ?>" class="regular-text wpnest-rfw-detail__refund-amount"></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>

                        <div class="wpnph-row">
                            <div class="wpnph-row__label">
                                <label for="wpnest-rfw-refund-amount"><?php esc_html_e( 'Total refund amount', 'wpnest-returns-for-woocommerce' ); ?></label>
                            </div>
                            <div class="wpnph-row__control">
                                <input type="text" id="wpnest-rfw-refund-amount" name="amount" value="" class="regular-text wpnest-rfw-detail__refund-total" placeholder="0.00">
                                <p class="wpnph-row__hint">
                                    <?php
                                    printf(
                                        /* translators: %s: formatted maximum refundable amount */
                                        esc_html__( 'Max %s. Leave per-line fields to recompute automatically.', 'wpnest-returns-for-woocommerce' ),
                                        wp_kses_post( wc_price( $remaining, array( 'currency' => $currency ) ) )
                                    );
                                    ?>
                                </p>
                            </div>
                        </div>

                        <div class="wpnph-row">
                            <div class="wpnph-row__label">
                                <label for="wpnest-rfw-refund-reason"><?php esc_html_e( 'Reason', 'wpnest-returns-for-woocommerce' ); ?></label>
                            </div>
                            <div class="wpnph-row__control">
                                <input type="text" id="wpnest-rfw-refund-reason" name="reason" class="regular-text">
                            </div>
                        </div>

                        <div class="wpnph-row">
                            <div class="wpnph-row__label"><?php esc_html_e( 'Restock items', 'wpnest-returns-for-woocommerce' ); ?></div>
                            <div class="wpnph-row__control">
                                <label class="wpnph-toggle">
                                    <input type="checkbox" name="restock" value="1">
                                    <span class="wpnph-toggle__switch"></span>
                                    <span class="wpnph-toggle__text"><?php esc_html_e( 'Add returned quantities back to product stock', 'wpnest-returns-for-woocommerce' ); ?></span>
                                </label>
                            </div>
                        </div>

                        <p>
                            <button type="submit" class="button button-primary wpnph-btn wpnph-btn--primary"><?php esc_html_e( 'Issue refund', 'wpnest-returns-for-woocommerce' ); ?></button>
                        </p>
                        <div class="wpnest-rfw-detail__feedback" role="status" aria-live="polite"></div>
                    </form>
                <?php endif; ?>

                <?php if ( ! empty( $refunds ) ) : ?>
                    <h3 style="margin-top:18px"><?php esc_html_e( 'Existing refunds', 'wpnest-returns-for-woocommerce' ); ?></h3>
                    <table class="widefat wpnest-rfw-detail__refund-list">
                        <thead>
                            <tr>
                                <th><?php esc_html_e( 'Date', 'wpnest-returns-for-woocommerce' ); ?></th>
                                <th><?php esc_html_e( 'Amount', 'wpnest-returns-for-woocommerce' ); ?></th>
                                <th><?php esc_html_e( 'Reason', 'wpnest-returns-for-woocommerce' ); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ( $refunds as $r ) : ?>
                                <tr>
                                    <td><?php echo esc_html( wc_format_datetime( $r->get_date_created() ) ); ?></td>
                                    <td><?php echo wp_kses_post( wc_price( $r->get_amount(), array( 'currency' => $currency ) ) ); ?></td>
                                    <td><?php echo esc_html( $r->get_reason() ); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }

    private function render_detail_notes( $order, $request ) {
        if ( ! $order instanceof WC_Order ) {
            return;
        }
        $notes = wc_get_order_notes( array( 'order_id' => $order->get_id(), 'order_by' => 'date_created', 'order' => 'DESC' ) );
        ?>
        <div class="wpnph-card">
            <div class="wpnph-card__header"><h2 class="wpnph-card__title"><?php esc_html_e( 'Notes', 'wpnest-returns-for-woocommerce' ); ?></h2></div>
            <div class="wpnph-card__body wpnest-rfw-detail__notes">
                <form class="wpnest-rfw-detail__note-form">
                    <textarea name="note" rows="3" class="large-text" placeholder="<?php esc_attr_e( 'Write a note…', 'wpnest-returns-for-woocommerce' ); ?>" required></textarea>
                    <div class="wpnest-rfw-detail__note-actions">
                        <label class="wpnph-toggle">
                            <input type="checkbox" name="customer_visible" value="1">
                            <span class="wpnph-toggle__switch"></span>
                            <span class="wpnph-toggle__text"><?php esc_html_e( 'Visible to customer', 'wpnest-returns-for-woocommerce' ); ?></span>
                        </label>
                        <button type="submit" class="button button-primary wpnph-btn wpnph-btn--primary"><?php esc_html_e( 'Add note', 'wpnest-returns-for-woocommerce' ); ?></button>
                    </div>
                    <div class="wpnest-rfw-detail__feedback" role="status" aria-live="polite"></div>
                </form>

                <ul class="wpnest-rfw-detail__notes-list">
                    <?php if ( empty( $notes ) ) : ?>
                        <li class="wpnest-rfw-detail__notes-empty"><?php esc_html_e( 'No notes yet.', 'wpnest-returns-for-woocommerce' ); ?></li>
                    <?php else : ?>
                        <?php foreach ( $notes as $note ) : ?>
                            <li class="wpnest-rfw-detail__note wpnest-rfw-detail__note--<?php echo $note->customer_note ? 'customer' : 'private'; ?>">
                                <div class="wpnest-rfw-detail__note-body"><?php echo wp_kses_post( wpautop( $note->content ) ); ?></div>
                                <div class="wpnest-rfw-detail__note-meta">
                                    <?php echo esc_html( $note->date_created instanceof WC_DateTime ? wc_format_datetime( $note->date_created ) : (string) $note->date_created ); ?>
                                    <?php if ( $note->customer_note ) : ?>
                                        · <span class="wpnph-badge wpnph-badge--accent"><?php esc_html_e( 'Customer-visible', 'wpnest-returns-for-woocommerce' ); ?></span>
                                    <?php else : ?>
                                        · <span class="wpnph-badge"><?php esc_html_e( 'Internal', 'wpnest-returns-for-woocommerce' ); ?></span>
                                    <?php endif; ?>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
        <?php
    }

    private function render_detail_history( $request ) {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table read for audit display.
        $rows = $wpdb->get_results(
            $wpdb->prepare(
                'SELECT * FROM %i WHERE request_id = %d ORDER BY id ASC',
                wpnest_rfw_status_log_table(),
                (int) $request->id
            )
        );
        $statuses = WPNest_RFW_Request_Model::get_statuses();
        ?>
        <div class="wpnph-card">
            <div class="wpnph-card__header"><h2 class="wpnph-card__title"><?php esc_html_e( 'Status history', 'wpnest-returns-for-woocommerce' ); ?></h2></div>
            <div class="wpnph-card__body">
                <?php if ( empty( $rows ) ) : ?>
                    <p><em><?php esc_html_e( 'No history yet.', 'wpnest-returns-for-woocommerce' ); ?></em></p>
                <?php else : ?>
                    <ol class="wpnest-rfw-detail__history">
                        <?php foreach ( $rows as $h ) :
                            $old_label = $h->old_status ? ( isset( $statuses[ $h->old_status ] ) ? $statuses[ $h->old_status ] : $h->old_status ) : __( 'created', 'wpnest-returns-for-woocommerce' );
                            $new_label = isset( $statuses[ $h->new_status ] ) ? $statuses[ $h->new_status ] : $h->new_status;
                            $user      = $h->changed_by ? get_user_by( 'id', (int) $h->changed_by ) : null;
                        ?>
                            <li class="wpnest-rfw-detail__history-entry">
                                <span class="wpnest-rfw-detail__history-when"><?php echo esc_html( mysql2date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), (string) $h->changed_at, true ) ); ?></span>
                                <span class="wpnest-rfw-detail__history-line">
                                    <strong><?php echo esc_html( $old_label ); ?></strong>
                                    →
                                    <strong><?php echo esc_html( $new_label ); ?></strong>
                                    <?php if ( $user ) : ?>
                                        <small>
                                            <?php
                                            /* translators: %s: user display name */
                                            printf( esc_html__( 'by %s', 'wpnest-returns-for-woocommerce' ), esc_html( $user->display_name ) );
                                            ?>
                                        </small>
                                    <?php endif; ?>
                                </span>
                                <?php if ( $h->note ) : ?>
                                    <div class="wpnest-rfw-detail__history-note"><?php echo esc_html( (string) $h->note ); ?></div>
                                <?php endif; ?>
                            </li>
                        <?php endforeach; ?>
                    </ol>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }
}
