<?php
/**
 * GGM Commerce MCP Export Tools
 * Provides MCP tools for transaction export operations
 *
 * @package GGM_Commerce
 */

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

/**
 * MCP Export Tools class
 */
class GGM_Commerce_MCP_Export_Tools {

    /**
     * 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_tools();
    }

    /**
     * Register MCP tools
     */
    private function register_tools() {
        // Export transactions tool.
        $this->server->register_tool(
            'export_transactions',
            __( 'Generate a transaction export batch for accounting purposes. Exports sales and refunds with totals.', 'ggm-commerce' ),
            array(
                'type'       => 'object',
                'properties' => array(
                    'date_from' => array(
                        'type'        => 'string',
                        'description' => __( 'Start date in YYYY-MM-DD format', 'ggm-commerce' ),
                    ),
                    'date_to'   => array(
                        'type'        => 'string',
                        'description' => __( 'End date in YYYY-MM-DD format', 'ggm-commerce' ),
                    ),
                    'format'    => array(
                        'type'        => 'string',
                        'enum'        => array( 'csv', 'json' ),
                        'description' => __( 'Export format: csv or json', 'ggm-commerce' ),
                        'default'     => 'csv',
                    ),
                    'notes'     => array(
                        'type'        => 'string',
                        'description' => __( 'Optional notes for this export batch', 'ggm-commerce' ),
                    ),
                ),
                'required'   => array( 'date_from', 'date_to' ),
            ),
            array( $this, 'export_transactions' )
        );

        // Regenerate export tool.
        $this->server->register_tool(
            'regenerate_export',
            __( 'Regenerate an existing export batch file', 'ggm-commerce' ),
            array(
                'type'       => 'object',
                'properties' => array(
                    'batch_id' => array(
                        'type'        => 'integer',
                        'description' => __( 'ID of the export batch to regenerate', 'ggm-commerce' ),
                    ),
                ),
                'required'   => array( 'batch_id' ),
            ),
            array( $this, 'regenerate_export' )
        );

        // Mark orders unexported tool.
        $this->server->register_tool(
            'mark_orders_unexported',
            __( 'Mark orders as unexported so they can be included in a new export', 'ggm-commerce' ),
            array(
                'type'       => 'object',
                'properties' => array(
                    'order_ids' => array(
                        'type'        => 'array',
                        'items'       => array( 'type' => 'integer' ),
                        'description' => __( 'Array of order IDs to mark as unexported', 'ggm-commerce' ),
                    ),
                ),
                'required'   => array( 'order_ids' ),
            ),
            array( $this, 'mark_orders_unexported' )
        );

        // Download export file tool.
        $this->server->register_tool(
            'download_export',
            __( 'Download the file contents of an export batch as base64-encoded data', 'ggm-commerce' ),
            array(
                'type'       => 'object',
                'properties' => array(
                    'batch_id' => array(
                        'type'        => 'integer',
                        'description' => __( 'ID of the export batch to download', 'ggm-commerce' ),
                    ),
                ),
                'required'   => array( 'batch_id' ),
            ),
            array( $this, 'download_export' )
        );

        // Get unexported orders count tool.
        $this->server->register_tool(
            'get_unexported_orders_preview',
            __( 'Get a preview of unexported orders and their totals for a date range', 'ggm-commerce' ),
            array(
                'type'       => 'object',
                'properties' => array(
                    'date_from' => array(
                        'type'        => 'string',
                        'description' => __( 'Start date in YYYY-MM-DD format (optional)', 'ggm-commerce' ),
                    ),
                    'date_to'   => array(
                        'type'        => 'string',
                        'description' => __( 'End date in YYYY-MM-DD format (optional)', 'ggm-commerce' ),
                    ),
                ),
            ),
            array( $this, 'get_unexported_preview' )
        );
    }

    /**
     * Export transactions
     *
     * @param array $args Tool arguments.
     * @return array Result.
     */
    public function export_transactions( $args ) {
        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( $args['date_from'] ) ? sanitize_text_field( $args['date_from'] ) : '';
        $date_to = isset( $args['date_to'] ) ? sanitize_text_field( $args['date_to'] ) : '';
        $format = isset( $args['format'] ) ? sanitize_text_field( $args['format'] ) : 'csv';
        $notes = isset( $args['notes'] ) ? sanitize_textarea_field( $args['notes'] ) : '';

        if ( empty( $date_from ) || empty( $date_to ) ) {
            return array(
                'success' => false,
                'error'   => __( 'Both date_from and date_to are required', 'ggm-commerce' ),
            );
        }

        $result = $exporter->generate_export( $date_from, $date_to, $format, $notes );

        if ( $result['success'] ) {
            return array(
                'success'      => true,
                'batch_id'     => $result['batch_id'],
                'batch_number' => $result['batch_number'],
                'file_url'     => $result['file_url'],
                'summary'      => array(
                    'order_count'    => $result['totals']['order_count'],
                    'refund_count'   => $result['totals']['refund_count'],
                    'total_sales'    => $result['totals']['total_sales'],
                    'total_refunds'  => $result['totals']['total_refunds'],
                    'total_tax'      => $result['totals']['total_tax'],
                    'total_shipping' => $result['totals']['total_shipping'],
                    'net_total'      => $result['totals']['net_total'],
                ),
                'message'      => $result['message'],
            );
        }

        return array(
            'success' => false,
            'error'   => $result['message'],
        );
    }

    /**
     * Regenerate export
     *
     * @param array $args Tool arguments.
     * @return array Result.
     */
    public function regenerate_export( $args ) {
        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();

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

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

        $result = $exporter->regenerate_export( $batch_id );

        if ( $result['success'] ) {
            return array(
                'success'  => true,
                'file_url' => $result['file_url'],
                'message'  => $result['message'],
            );
        }

        return array(
            'success' => false,
            'error'   => $result['message'],
        );
    }

    /**
     * Mark orders as unexported
     *
     * @param array $args Tool arguments.
     * @return array Result.
     */
    public function mark_orders_unexported( $args ) {
        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();

        $order_ids = isset( $args['order_ids'] ) ? array_map( 'absint', (array) $args['order_ids'] ) : array();

        if ( empty( $order_ids ) ) {
            return array(
                'success' => false,
                'error'   => __( 'order_ids array is required', 'ggm-commerce' ),
            );
        }

        $result = $exporter->mark_orders_unexported( $order_ids );

        return array(
            'success'       => $result['success'],
            'orders_marked' => $result['count'],
            'message'       => $result['message'],
        );
    }

    /**
     * Download export file
     *
     * @param array $args Tool arguments.
     * @return array Result with base64 file content.
     */
    public function download_export( $args ) {
        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();

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

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

        $batch = $exporter->get_export_batch( $batch_id );

        if ( ! $batch || ! $batch->file_path || ! file_exists( $batch->file_path ) ) {
            return array(
                'success' => false,
                'error'   => __( 'Export file not found', 'ggm-commerce' ),
            );
        }

        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
        $content = file_get_contents( $batch->file_path );

        return array(
            'success'  => true,
            'filename' => basename( $batch->file_path ),
            'format'   => $batch->export_format ?? 'csv',
            'content'  => base64_encode( $content ),
        );
    }

    /**
     * Get unexported orders preview
     *
     * @param array $args Tool arguments.
     * @return array Result.
     */
    public function get_unexported_preview( $args ) {
        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( $args['date_from'] ) ? sanitize_text_field( $args['date_from'] ) : '';
        $date_to = isset( $args['date_to'] ) ? sanitize_text_field( $args['date_to'] ) : '';

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

        // Calculate totals.
        $totals = array(
            'order_count'    => 0,
            'refund_count'   => 0,
            'total_sales'    => 0.00,
            'total_refunds'  => 0.00,
            'total_tax'      => 0.00,
            'total_shipping' => 0.00,
            'net_total'      => 0.00,
        );

        foreach ( $orders as $order ) {
            $is_refund = 'refunded' === $order->payment_status;

            if ( $is_refund ) {
                $totals['refund_count']++;
                $totals['total_refunds'] += (float) $order->total_amount;
            } else {
                $totals['order_count']++;
                $totals['total_sales'] += (float) $order->total_amount;
            }

            $totals['total_tax'] += (float) $order->tax_amount;
            $totals['total_shipping'] += (float) $order->shipping_amount;
        }

        $totals['net_total'] = $totals['total_sales'] - $totals['total_refunds'];

        return array(
            'success'           => true,
            'unexported_count'  => count( $orders ),
            'date_range'        => array(
                'from' => $date_from ?: 'all',
                'to'   => $date_to ?: 'all',
            ),
            'totals'            => $totals,
        );
    }
}

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