<?php
/**
 * GGM Commerce Order Resources
 *
 * MCP Resources for exposing order data to AI assistants
 * Resources are read-only data sources
 *
 * @package GGM_Commerce
 * @since 1.0.0
 */

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

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter

class GGM_Commerce_Order_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 all order resources
     */
    private function register_resources() {
        // All orders
        $this->server->register_resource(
            'order://list',
            'Orders List',
            'List of all orders with basic information',
            [$this, 'get_orders_list']
        );

        // Single order by ID
        $this->server->register_resource(
            'order://{order_id}',
            'Order Details',
            'Complete order information including items and customer details',
            [$this, 'get_order']
        );

        // Orders by status
        $this->server->register_resource(
            'order://status/{status}',
            'Orders by Status',
            'All orders with a specific status (pending, processing, completed, cancelled)',
            [$this, 'get_orders_by_status']
        );

        // Orders by customer email
        $this->server->register_resource(
            'order://customer/{email}',
            'Customer Orders',
            'All orders for a specific customer by email',
            [$this, 'get_customer_orders']
        );

        // Recent orders
        $this->server->register_resource(
            'order://recent',
            'Recent Orders',
            'Most recent orders (last 50)',
            [$this, 'get_recent_orders']
        );

        // Order statistics
        $this->server->register_resource(
            'order://statistics',
            'Order Statistics',
            'Order statistics and analytics',
            [$this, 'get_order_statistics']
        );
    }

    /**
     * Get list of all orders
     *
     * @param array $params URI parameters
     * @return array Orders list data
     */
    public function get_orders_list($params = []) {
        global $wpdb;

        $orders = $wpdb->get_results(
            "SELECT
                id,
                order_number,
                customer_email,
                total_amount,
                status,
                payment_status,
                created_at,
                updated_at
            FROM {$wpdb->prefix}ggmc_orders
            ORDER BY created_at DESC
            LIMIT 100"
        );

        // Format data
        foreach ($orders as &$order) {
            $order->id = (int) $order->id;
            $order->total_amount = (float) $order->total_amount;
        }

        return [
            'orders' => $orders,
            'count' => count($orders),
            'timestamp' => current_time('mysql')
        ];
    }

    /**
     * Get single order details
     *
     * @param array $params URI parameters (expects 'order_id')
     * @return array Order data
     */
    public function get_order($params) {
        if (!isset($params['order_id'])) {
            return ['error' => 'Order ID is required'];
        }

        global $wpdb;

        // Get order data
        $order = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}ggmc_orders WHERE id = %d",
            intval($params['order_id'])
        ));

        if (!$order) {
            return ['error' => 'Order not found'];
        }

        // Get order items
        $items = $wpdb->get_results($wpdb->prepare(
            "SELECT
                oi.*,
                p.name as product_name,
                p.sku as product_sku,
                p.image_url as product_image
            FROM {$wpdb->prefix}ggmc_order_items oi
            LEFT JOIN {$wpdb->prefix}ggmc_products p ON oi.product_id = p.id
            WHERE oi.order_id = %d",
            intval($params['order_id'])
        ));

        // Format item data
        foreach ($items as &$item) {
            $item->id = (int) $item->id;
            $item->product_id = (int) $item->product_id;
            $item->quantity = (int) $item->quantity;
            $item->price = (float) $item->price;
            $item->subtotal = (float) $item->subtotal;
        }

        // Format order data
        $order->id = (int) $order->id;
        $order->total_amount = (float) $order->total_amount;
        $order->subtotal = isset($order->subtotal) ? (float) $order->subtotal : null;
        $order->tax_amount = isset($order->tax_amount) ? (float) $order->tax_amount : null;
        $order->shipping_amount = isset($order->shipping_amount) ? (float) $order->shipping_amount : null;
        $order->discount_amount = isset($order->discount_amount) ? (float) $order->discount_amount : null;

        $order->items = $items;
        $order->item_count = count($items);

        return [
            'order' => $order,
            'timestamp' => current_time('mysql')
        ];
    }

    /**
     * Get orders by status
     *
     * @param array $params URI parameters (expects 'status')
     * @return array Orders data
     */
    public function get_orders_by_status($params) {
        if (!isset($params['status'])) {
            return ['error' => 'Status is required'];
        }

        $status = sanitize_text_field($params['status']);
        $valid_statuses = ['pending', 'processing', 'completed', 'cancelled'];

        if (!in_array($status, $valid_statuses)) {
            return [
                'error' => 'Invalid status. Valid values: ' . implode(', ', $valid_statuses)
            ];
        }

        global $wpdb;

        $orders = $wpdb->get_results($wpdb->prepare(
            "SELECT
                id,
                order_number,
                customer_email,
                customer_first_name,
                customer_last_name,
                total_amount,
                status,
                payment_status,
                created_at
            FROM {$wpdb->prefix}ggmc_orders
            WHERE status = %s
            ORDER BY created_at DESC",
            $status
        ));

        // Format data
        foreach ($orders as &$order) {
            $order->id = (int) $order->id;
            $order->total_amount = (float) $order->total_amount;
        }

        return [
            'status' => $status,
            'orders' => $orders,
            'count' => count($orders),
            'timestamp' => current_time('mysql')
        ];
    }

    /**
     * Get orders for a specific customer
     *
     * @param array $params URI parameters (expects 'email')
     * @return array Customer orders data
     */
    public function get_customer_orders($params) {
        if (!isset($params['email'])) {
            return ['error' => 'Customer email is required'];
        }

        $email = sanitize_email($params['email']);

        if (!is_email($email)) {
            return ['error' => 'Invalid email address'];
        }

        global $wpdb;

        $orders = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}ggmc_orders
            WHERE customer_email = %s
            ORDER BY created_at DESC",
            $email
        ));

        // Get order items for each order
        foreach ($orders as &$order) {
            $items = $wpdb->get_results($wpdb->prepare(
                "SELECT
                    oi.*,
                    p.name as product_name
                FROM {$wpdb->prefix}ggmc_order_items oi
                LEFT JOIN {$wpdb->prefix}ggmc_products p ON oi.product_id = p.id
                WHERE oi.order_id = %d",
                $order->id
            ));

            // Format data
            $order->id = (int) $order->id;
            $order->total_amount = (float) $order->total_amount;
            $order->items = $items;
            $order->item_count = count($items);
        }

        // Calculate customer statistics
        $total_spent = array_sum(array_column($orders, 'total_amount'));
        $total_orders = count($orders);

        return [
            'customer_email' => $email,
            'orders' => $orders,
            'statistics' => [
                'total_orders' => $total_orders,
                'total_spent' => $total_spent,
                'average_order_value' => $total_orders > 0 ? $total_spent / $total_orders : 0
            ],
            'timestamp' => current_time('mysql')
        ];
    }

    /**
     * Get recent orders
     *
     * @param array $params URI parameters
     * @return array Recent orders data
     */
    public function get_recent_orders($params = []) {
        global $wpdb;

        $limit = isset($params['limit']) ? intval($params['limit']) : 50;
        $limit = min($limit, 100); // Max 100

        $orders = $wpdb->get_results($wpdb->prepare(
            "SELECT
                id,
                order_number,
                customer_email,
                customer_first_name,
                customer_last_name,
                total_amount,
                status,
                payment_status,
                created_at
            FROM {$wpdb->prefix}ggmc_orders
            ORDER BY created_at DESC
            LIMIT %d",
            $limit
        ));

        // Format data
        foreach ($orders as &$order) {
            $order->id = (int) $order->id;
            $order->total_amount = (float) $order->total_amount;
        }

        return [
            'orders' => $orders,
            'count' => count($orders),
            'limit' => $limit,
            'timestamp' => current_time('mysql')
        ];
    }

    /**
     * Get order statistics
     *
     * @param array $params URI parameters
     * @return array Order statistics
     */
    public function get_order_statistics($params = []) {
        global $wpdb;

        // Overall statistics
        $total_orders = $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_orders"
        );

        $total_revenue = $wpdb->get_var(
            "SELECT SUM(total_amount) FROM {$wpdb->prefix}ggmc_orders
            WHERE status != 'cancelled'"
        );

        $average_order_value = $total_orders > 0
            ? $wpdb->get_var("SELECT AVG(total_amount) FROM {$wpdb->prefix}ggmc_orders WHERE status != 'cancelled'")
            : 0;

        // Orders by status
        $status_counts = $wpdb->get_results(
            "SELECT status, COUNT(*) as count, SUM(total_amount) as total
            FROM {$wpdb->prefix}ggmc_orders
            GROUP BY status"
        );

        $by_status = [];
        foreach ($status_counts as $row) {
            $by_status[$row->status] = [
                'count' => (int) $row->count,
                'total' => (float) $row->total
            ];
        }

        // Payment status
        $payment_counts = $wpdb->get_results(
            "SELECT payment_status, COUNT(*) as count
            FROM {$wpdb->prefix}ggmc_orders
            GROUP BY payment_status"
        );

        $by_payment_status = [];
        foreach ($payment_counts as $row) {
            $by_payment_status[$row->payment_status] = (int) $row->count;
        }

        // Recent activity (last 30 days)
        $recent_orders = $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_orders
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"
        );

        $recent_revenue = $wpdb->get_var(
            "SELECT SUM(total_amount) FROM {$wpdb->prefix}ggmc_orders
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
            AND status != 'cancelled'"
        );

        // Top products
        $top_products = $wpdb->get_results(
            "SELECT
                p.id,
                p.name,
                p.sku,
                SUM(oi.quantity) as total_quantity,
                SUM(oi.subtotal) as total_revenue
            FROM {$wpdb->prefix}ggmc_order_items oi
            INNER JOIN {$wpdb->prefix}ggmc_products p ON oi.product_id = p.id
            INNER JOIN {$wpdb->prefix}ggmc_orders o ON oi.order_id = o.id
            WHERE o.status != 'cancelled'
            GROUP BY p.id
            ORDER BY total_quantity DESC
            LIMIT 10"
        );

        return [
            'overall' => [
                'total_orders' => (int) $total_orders,
                'total_revenue' => (float) $total_revenue,
                'average_order_value' => (float) $average_order_value
            ],
            'by_status' => $by_status,
            'by_payment_status' => $by_payment_status,
            'last_30_days' => [
                'orders' => (int) $recent_orders,
                'revenue' => (float) $recent_revenue
            ],
            'top_products' => $top_products,
            'timestamp' => current_time('mysql')
        ];
    }
}
