<?php
/**
 * GGM Commerce MCP Export Resources
 * Provides MCP resources for export batch data
 *
 * @package GGM_Commerce
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * MCP Export Resources class
 */
class GGM_Commerce_MCP_Export_Resources {

    /**
     * MCP Server instance
     *
     * @var GGM_Commerce_MCP_Server
     */
    private $server;

    /**
     * Constructor
     *
     * @param GGM_Commerce_MCP_Server $server MCP Server instance.
     */
    public function __construct( $server ) {
        $this->server = $server;
        $this->register_resources();
    }

    /**
     * Register MCP resources
     */
    private function register_resources() {
        // Export batches list.
        $this->server->register_resource(
            'export_batches',
            __( 'Export Batches List', 'ggm-commerce' ),
            __( 'List of all transaction export batches', 'ggm-commerce' ),
            array( $this, 'get_export_batches' )
        );

        // Single export batch.
        $this->server->register_resource(
            'export_batch://{id}',
            __( 'Export Batch Details', 'ggm-commerce' ),
            __( 'Detailed information about a specific export batch', 'ggm-commerce' ),
            array( $this, 'get_export_batch' )
        );

        // Unexported orders.
        $this->server->register_resource(
            'unexported_orders',
            __( 'Unexported Orders', 'ggm-commerce' ),
            __( 'List of orders that have not been exported yet', 'ggm-commerce' ),
            array( $this, 'get_unexported_orders' )
        );

        // Export statistics.
        $this->server->register_resource(
            'export_statistics',
            __( 'Export Statistics', 'ggm-commerce' ),
            __( 'Overall statistics about transaction exports', 'ggm-commerce' ),
            array( $this, 'get_export_statistics' )
        );
    }

    /**
     * Get export batches list
     *
     * @param array $params Resource parameters.
     * @return array Resource data.
     */
    public function get_export_batches( $params ) {
        if ( ! class_exists( 'GGM_Commerce_Transaction_Export' ) ) {
            require_once plugin_dir_path( dirname( __FILE__ ) ) . 'class-transaction-export.php';
        }

        $exporter = GGM_Commerce_Transaction_Export::get_instance();

        $page = isset( $params['page'] ) ? absint( $params['page'] ) : 1;
        $per_page = isset( $params['per_page'] ) ? min( absint( $params['per_page'] ), 100 ) : 20;

        $data = $exporter->list_export_batches( $page, $per_page );

        $batches = array();
        foreach ( $data['batches'] as $batch ) {
            $batches[] = array(
                'id'            => (int) $batch->id,
                'batch_number'  => $batch->batch_number,
                'export_type'   => $batch->export_type,
                'date_range'    => array(
                    'from' => $batch->date_from,
                    'to'   => $batch->date_to,
                ),
                'order_count'   => (int) $batch->order_count,
                'refund_count'  => (int) $batch->refund_count,
                'totals'        => array(
                    'sales'    => (float) $batch->total_sales,
                    'refunds'  => (float) $batch->total_refunds,
                    'tax'      => (float) $batch->total_tax,
                    'shipping' => (float) $batch->total_shipping,
                    'net'      => (float) $batch->net_total,
                ),
                'format'        => $batch->export_format,
                'has_file'      => ! empty( $batch->download_url ),
                'created_by'    => $batch->created_by_name,
                'created_at'    => $batch->created_at,
            );
        }

        return array(
            'batches'     => $batches,
            'pagination'  => array(
                'total'       => $data['total'],
                'page'        => $data['page'],
                'per_page'    => $data['per_page'],
                'total_pages' => $data['total_pages'],
            ),
        );
    }

    /**
     * Get single export batch
     *
     * @param array $params Resource parameters.
     * @return array Resource data.
     */
    public function get_export_batch( $params ) {
        if ( ! class_exists( 'GGM_Commerce_Transaction_Export' ) ) {
            require_once plugin_dir_path( dirname( __FILE__ ) ) . 'class-transaction-export.php';
        }

        $batch_id = isset( $params['id'] ) ? absint( $params['id'] ) : 0;

        if ( ! $batch_id ) {
            return array( 'error' => __( 'Batch ID is required', 'ggm-commerce' ) );
        }

        $exporter = GGM_Commerce_Transaction_Export::get_instance();
        $batch = $exporter->get_export_batch( $batch_id );

        if ( ! $batch ) {
            return array( 'error' => __( 'Export batch not found', 'ggm-commerce' ) );
        }

        // Get orders in this batch.
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $orders = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT order_number, customer_email, customer_first_name, customer_last_name,
                        total_amount, tax_amount, shipping_amount, payment_status, payment_method, created_at
                 FROM {$wpdb->prefix}ggmc_orders
                 WHERE export_batch_id = %d
                 ORDER BY created_at ASC",
                $batch_id
            )
        );

        $transactions = array();
        foreach ( $orders as $order ) {
            $transactions[] = array(
                'order_number'   => $order->order_number,
                'customer_email' => $order->customer_email,
                'customer_name'  => trim( $order->customer_first_name . ' ' . $order->customer_last_name ),
                'type'           => 'refunded' === $order->payment_status ? 'refund' : 'sale',
                'total'          => (float) $order->total_amount,
                'tax'            => (float) $order->tax_amount,
                'shipping'       => (float) $order->shipping_amount,
                'payment_method' => $order->payment_method,
                'date'           => $order->created_at,
            );
        }

        return array(
            'id'               => (int) $batch->id,
            'batch_number'     => $batch->batch_number,
            'export_type'      => $batch->export_type,
            'date_range'       => array(
                'from' => $batch->date_from,
                'to'   => $batch->date_to,
            ),
            'summary'          => array(
                'order_count'   => (int) $batch->order_count,
                'refund_count'  => (int) $batch->refund_count,
                'total_sales'   => (float) $batch->total_sales,
                'total_refunds' => (float) $batch->total_refunds,
                'total_tax'     => (float) $batch->total_tax,
                'total_shipping' => (float) $batch->total_shipping,
                'net_total'     => (float) $batch->net_total,
            ),
            'payment_breakdown' => $batch->payment_method_breakdown,
            'format'           => $batch->export_format,
            'notes'            => $batch->notes,
            'created_by'       => array(
                'id'   => (int) $batch->created_by,
                'name' => $batch->created_by_name,
            ),
            'created_at'       => $batch->created_at,
            'transactions'     => $transactions,
        );
    }

    /**
     * Get unexported orders
     *
     * @param array $params Resource parameters.
     * @return array Resource data.
     */
    public function get_unexported_orders( $params ) {
        if ( ! class_exists( 'GGM_Commerce_Transaction_Export' ) ) {
            require_once plugin_dir_path( dirname( __FILE__ ) ) . 'class-transaction-export.php';
        }

        $exporter = GGM_Commerce_Transaction_Export::get_instance();

        $date_from = isset( $params['date_from'] ) ? sanitize_text_field( $params['date_from'] ) : '';
        $date_to = isset( $params['date_to'] ) ? sanitize_text_field( $params['date_to'] ) : '';
        $limit = isset( $params['limit'] ) ? min( absint( $params['limit'] ), 100 ) : 50;

        $orders = $exporter->get_unexported_orders( $date_from, $date_to );

        // Limit results.
        $orders = array_slice( $orders, 0, $limit );

        $result = array();
        foreach ( $orders as $order ) {
            $result[] = array(
                'id'             => (int) $order->id,
                'order_number'   => $order->order_number,
                'customer_email' => $order->customer_email,
                'customer_name'  => trim( $order->customer_first_name . ' ' . $order->customer_last_name ),
                'type'           => 'refunded' === $order->payment_status ? 'refund' : 'sale',
                'total'          => (float) $order->total_amount,
                'tax'            => (float) $order->tax_amount,
                'shipping'       => (float) $order->shipping_amount,
                'payment_method' => $order->payment_method,
                'payment_status' => $order->payment_status,
                'created_at'     => $order->created_at,
            );
        }

        return array(
            'orders'      => $result,
            'total_count' => count( $orders ),
            'filters'     => array(
                'date_from' => $date_from ?: null,
                'date_to'   => $date_to ?: null,
            ),
        );
    }

    /**
     * Get export statistics
     *
     * @param array $params Resource parameters.
     * @return array Resource data.
     */
    public function get_export_statistics( $params ) {
        global $wpdb;

        // Get total batches.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $total_batches = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_export_batches" );

        // Get totals across all batches.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $totals = $wpdb->get_row(
            "SELECT
                SUM(order_count) as total_orders,
                SUM(refund_count) as total_refunds,
                SUM(total_sales) as total_sales,
                SUM(total_refunds) as total_refund_amount,
                SUM(total_tax) as total_tax,
                SUM(total_shipping) as total_shipping,
                SUM(net_total) as total_net
             FROM {$wpdb->prefix}ggmc_export_batches"
        );

        // Get unexported orders count.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $unexported_count = $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_orders
             WHERE (export_batch_id IS NULL OR export_batch_id = 0)
             AND payment_status IN ('paid', 'refunded')"
        );

        // Get recent batches.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $recent_batches = $wpdb->get_results(
            "SELECT batch_number, order_count, net_total, created_at
             FROM {$wpdb->prefix}ggmc_export_batches
             ORDER BY created_at DESC
             LIMIT 5"
        );

        return array(
            'total_batches'    => (int) $total_batches,
            'unexported_orders' => (int) $unexported_count,
            'lifetime_totals'  => array(
                'orders'         => (int) ( $totals->total_orders ?? 0 ),
                'refunds'        => (int) ( $totals->total_refunds ?? 0 ),
                'sales_amount'   => (float) ( $totals->total_sales ?? 0 ),
                'refund_amount'  => (float) ( $totals->total_refund_amount ?? 0 ),
                'tax_amount'     => (float) ( $totals->total_tax ?? 0 ),
                'shipping_amount' => (float) ( $totals->total_shipping ?? 0 ),
                'net_amount'     => (float) ( $totals->total_net ?? 0 ),
            ),
            'recent_batches'   => array_map(
                function ( $batch ) {
                    return array(
                        'batch_number' => $batch->batch_number,
                        'order_count'  => (int) $batch->order_count,
                        'net_total'    => (float) $batch->net_total,
                        'created_at'   => $batch->created_at,
                    );
                },
                $recent_batches
            ),
        );
    }
}

// Initialize if MCP server is available.
add_action(
    'ggmc_mcp_register_components',
    function ( $server ) {
        new GGM_Commerce_MCP_Export_Resources( $server );
    }
);
