<?php
/**
 * GGM Commerce Shopping Prompts
 *
 * MCP Prompts for common shopping assistant scenarios
 * Prompts are templates that guide AI interactions
 *
 * @package GGM_Commerce
 * @since 1.0.0
 */

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

class GGM_Commerce_Shopping_Prompts {

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

    /**
     * Register all shopping prompts
     */
    private function register_prompts() {
        // Product recommendation prompt
        $this->server->register_prompt(
            'product_recommendation',
            'Help customer find products based on their needs and preferences',
            [$this, 'product_recommendation_prompt'],
            [
                [
                    'name' => 'category',
                    'description' => 'Product category customer is interested in',
                    'required' => false
                ],
                [
                    'name' => 'budget',
                    'description' => 'Customer budget or price range',
                    'required' => false
                ],
                [
                    'name' => 'preferences',
                    'description' => 'Customer preferences or requirements',
                    'required' => false
                ]
            ]
        );

        // Order summary prompt
        $this->server->register_prompt(
            'order_summary',
            'Generate a comprehensive summary of an order',
            [$this, 'order_summary_prompt'],
            [
                [
                    'name' => 'order_number',
                    'description' => 'Order number to summarize',
                    'required' => true
                ]
            ]
        );

        // Inventory alert prompt
        $this->server->register_prompt(
            'inventory_alert',
            'Alert about low stock situations and recommend actions',
            [$this, 'inventory_alert_prompt'],
            [
                [
                    'name' => 'threshold',
                    'description' => 'Stock threshold for alerts (default: 10)',
                    'required' => false
                ]
            ]
        );

        // Customer service prompt
        $this->server->register_prompt(
            'customer_service',
            'Assist with customer service inquiries and issues',
            [$this, 'customer_service_prompt'],
            [
                [
                    'name' => 'issue_type',
                    'description' => 'Type of customer issue (order, product, shipping, etc.)',
                    'required' => false
                ]
            ]
        );

        // Sales analysis prompt
        $this->server->register_prompt(
            'sales_analysis',
            'Analyze sales data and provide insights',
            [$this, 'sales_analysis_prompt'],
            [
                [
                    'name' => 'period',
                    'description' => 'Time period to analyze (e.g., "last 30 days", "this month")',
                    'required' => false
                ]
            ]
        );

        // Bulk product creation prompt
        $this->server->register_prompt(
            'bulk_product_creation',
            'Guide for creating multiple products for a store',
            [$this, 'bulk_product_creation_prompt'],
            [
                [
                    'name' => 'store_type',
                    'description' => 'Type of store (e.g., clothing, electronics, food, home goods)',
                    'required' => true
                ],
                [
                    'name' => 'product_count',
                    'description' => 'Number of products to create',
                    'required' => true
                ],
                [
                    'name' => 'price_range',
                    'description' => 'Price range for products (e.g., "10-50", "100-500")',
                    'required' => false
                ],
                [
                    'name' => 'include_sales',
                    'description' => 'Whether to include sale prices on some products',
                    'required' => false
                ]
            ]
        );
    }

    /**
     * Product recommendation prompt
     *
     * @param array $args Prompt arguments
     * @return array Prompt messages
     */
    public function product_recommendation_prompt($args) {
        $category = isset($args['category']) ? $args['category'] : null;
        $budget = isset($args['budget']) ? $args['budget'] : null;
        $preferences = isset($args['preferences']) ? $args['preferences'] : null;

        $system_prompt = "You are a helpful and knowledgeable shopping assistant for an e-commerce store. ";
        $system_prompt .= "Your goal is to help customers find the perfect products based on their needs. ";

        if ($category) {
            $system_prompt .= "The customer is interested in the '{$category}' category. ";
        }

        if ($budget) {
            $system_prompt .= "Their budget is approximately {$budget}. ";
        }

        if ($preferences) {
            $system_prompt .= "They mentioned these preferences: {$preferences}. ";
        }

        $system_prompt .= "\n\nWhen recommending products:\n";
        $system_prompt .= "- Use the 'search_products' tool to find relevant items\n";
        $system_prompt .= "- Consider product features, pricing, availability, and customer ratings\n";
        $system_prompt .= "- Explain why you're recommending each product\n";
        $system_prompt .= "- Check stock availability before recommending\n";
        $system_prompt .= "- Suggest 3-5 options when possible, with a range of price points\n";
        $system_prompt .= "- Be honest about product limitations\n";
        $system_prompt .= "- Help customers make informed decisions";

        return [
            'description' => 'Product recommendation assistant',
            'messages' => [
                [
                    'role' => 'user',
                    'content' => [
                        [
                            'type' => 'text',
                            'text' => $system_prompt
                        ]
                    ]
                ]
            ]
        ];
    }

    /**
     * Order summary prompt
     *
     * @param array $args Prompt arguments
     * @return array Prompt messages
     */
    public function order_summary_prompt($args) {
        if (!isset($args['order_number'])) {
            return [
                'error' => 'order_number is required'
            ];
        }

        $order_number = $args['order_number'];

        $system_prompt = "You are an order management assistant. ";
        $system_prompt .= "Generate a comprehensive summary of order {$order_number}. ";
        $system_prompt .= "\n\nInclude:\n";
        $system_prompt .= "- Order number and date\n";
        $system_prompt .= "- Order status and payment status\n";
        $system_prompt .= "- Customer information\n";
        $system_prompt .= "- Items ordered with quantities and prices\n";
        $system_prompt .= "- Subtotal, tax, shipping, and total\n";
        $system_prompt .= "- Shipping address\n";
        $system_prompt .= "- Any special notes or instructions\n";
        $system_prompt .= "\nFormat the summary in a clear, professional manner.";

        return [
            'description' => "Order summary for #{$order_number}",
            'messages' => [
                [
                    'role' => 'user',
                    'content' => [
                        [
                            'type' => 'text',
                            'text' => $system_prompt
                        ]
                    ]
                ]
            ]
        ];
    }

    /**
     * Inventory alert prompt
     *
     * @param array $args Prompt arguments
     * @return array Prompt messages
     */
    public function inventory_alert_prompt($args) {
        $threshold = isset($args['threshold']) ? intval($args['threshold']) : 10;

        $system_prompt = "You are an inventory management assistant. ";
        $system_prompt .= "Review the product inventory and identify items with stock levels below {$threshold} units. ";
        $system_prompt .= "\n\nProvide:\n";
        $system_prompt .= "- A formatted report of low stock items\n";
        $system_prompt .= "- Product names, SKUs, and current stock levels\n";
        $system_prompt .= "- Recommended reorder quantities based on:\n";
        $system_prompt .= "  * Historical sales data (if available)\n";
        $system_prompt .= "  * Current stock level\n";
        $system_prompt .= "  * Product popularity\n";
        $system_prompt .= "- Priority ranking (critical, high, medium, low)\n";
        $system_prompt .= "- Total estimated reorder cost\n";
        $system_prompt .= "\nFormat the report in a clear, actionable manner with bullet points or tables.";

        return [
            'description' => 'Inventory low stock alert',
            'messages' => [
                [
                    'role' => 'user',
                    'content' => [
                        [
                            'type' => 'text',
                            'text' => $system_prompt
                        ]
                    ]
                ]
            ]
        ];
    }

    /**
     * Customer service prompt
     *
     * @param array $args Prompt arguments
     * @return array Prompt messages
     */
    public function customer_service_prompt($args) {
        $issue_type = isset($args['issue_type']) ? $args['issue_type'] : 'general';

        $system_prompt = "You are a helpful and empathetic customer service assistant. ";
        $system_prompt .= "Your goal is to resolve customer issues quickly and professionally. ";

        if ($issue_type) {
            $system_prompt .= "The customer is contacting about: {$issue_type}. ";
        }

        $system_prompt .= "\n\nGuidelines:\n";
        $system_prompt .= "- Be polite, professional, and empathetic\n";
        $system_prompt .= "- Listen to the customer's concern carefully\n";
        $system_prompt .= "- Use available tools to look up order information, product details, etc.\n";
        $system_prompt .= "- Provide clear, accurate information\n";
        $system_prompt .= "- Offer solutions when possible\n";
        $system_prompt .= "- Escalate complex issues when necessary\n";
        $system_prompt .= "- Follow up to ensure satisfaction\n";
        $system_prompt .= "\nAvailable actions:\n";
        $system_prompt .= "- Look up orders by order number or customer email\n";
        $system_prompt .= "- Check product availability and stock\n";
        $system_prompt .= "- Verify order status and tracking\n";
        $system_prompt .= "- Provide product information and recommendations\n";
        $system_prompt .= "- Update order status (when authorized)";

        return [
            'description' => 'Customer service assistant',
            'messages' => [
                [
                    'role' => 'user',
                    'content' => [
                        [
                            'type' => 'text',
                            'text' => $system_prompt
                        ]
                    ]
                ]
            ]
        ];
    }

    /**
     * Sales analysis prompt
     *
     * @param array $args Prompt arguments
     * @return array Prompt messages
     */
    public function sales_analysis_prompt($args) {
        $period = isset($args['period']) ? $args['period'] : 'recent performance';

        $system_prompt = "You are a sales analytics assistant. ";
        $system_prompt .= "Analyze {$period} sales data and provide actionable insights. ";
        $system_prompt .= "\n\nYour analysis should include:\n";
        $system_prompt .= "- Overall sales performance (revenue, order count, average order value)\n";
        $system_prompt .= "- Top performing products\n";
        $system_prompt .= "- Sales trends and patterns\n";
        $system_prompt .= "- Customer behavior insights\n";
        $system_prompt .= "- Comparison to previous periods (if applicable)\n";
        $system_prompt .= "- Key performance indicators\n";
        $system_prompt .= "- Recommendations for improvement\n";
        $system_prompt .= "- Areas of concern that need attention\n";
        $system_prompt .= "\nUse charts, tables, and visual formatting where helpful. ";
        $system_prompt .= "Provide specific, data-driven recommendations.";

        return [
            'description' => 'Sales analysis and insights',
            'messages' => [
                [
                    'role' => 'user',
                    'content' => [
                        [
                            'type' => 'text',
                            'text' => $system_prompt
                        ]
                    ]
                ]
            ]
        ];
    }

    /**
     * Bulk product creation prompt
     *
     * @param array $args Prompt arguments
     * @return array Prompt messages
     */
    public function bulk_product_creation_prompt($args) {
        if (!isset($args['store_type']) || !isset($args['product_count'])) {
            return [
                'error' => 'store_type and product_count are required'
            ];
        }

        $store_type = sanitize_text_field($args['store_type']);
        $product_count = intval($args['product_count']);
        $price_range = isset($args['price_range']) ? $args['price_range'] : '10-100';
        $include_sales = isset($args['include_sales']) && $args['include_sales'];

        $system_prompt = "You are a product catalog assistant for a Goose Commerce store.\n\n";
        $system_prompt .= "## Your Task\n";
        $system_prompt .= "Create {$product_count} realistic products for a **{$store_type}** store.\n\n";

        $system_prompt .= "## Step 1: Fetch Available Categories and Tags\n";
        $system_prompt .= "FIRST, use these resources to see what categories and tags exist:\n";
        $system_prompt .= "- Resource: `product://categories` - Get all available categories\n";
        $system_prompt .= "- Resource: `product://tags` - Get all available tags\n\n";
        $system_prompt .= "If no categories exist yet, suggest creating appropriate ones first.\n\n";

        $system_prompt .= "## Step 2: Create Products\n";
        $system_prompt .= "Use the `create_product` tool for each product with these fields:\n\n";

        $system_prompt .= "### Required Fields:\n";
        $system_prompt .= "- `name`: Descriptive product name\n";
        $system_prompt .= "- `sku`: Unique SKU (format: {CATEGORY}-{NUMBER}, e.g., SHIRT-001)\n";
        $system_prompt .= "- `price`: Price within range {$price_range}\n";
        $system_prompt .= "- `stock`: Random stock between 10-100\n\n";

        $system_prompt .= "### Recommended Fields:\n";
        $system_prompt .= "- `description`: 2-3 sentences describing the product\n";
        $system_prompt .= "- `short_description`: 1 sentence summary\n";
        $system_prompt .= "- `category_ids`: Array of category IDs (from Step 1)\n";
        $system_prompt .= "- `tag_ids`: Array of tag IDs (from Step 1)\n";
        $system_prompt .= "- `featured`: Set true for 10-20% of products\n";
        $system_prompt .= "- `low_stock_threshold`: Default 10\n";

        if ($include_sales) {
            $system_prompt .= "- `sale_price`: Add sale prices to ~30% of products (must be less than regular price)\n";
        }

        $system_prompt .= "\n## Product Guidelines for {$store_type} Store:\n";

        // Add store-specific guidelines
        switch (strtolower($store_type)) {
            case 'clothing':
            case 'apparel':
            case 'fashion':
                $system_prompt .= "- Include variety: shirts, pants, dresses, jackets, accessories\n";
                $system_prompt .= "- Mention materials (cotton, polyester, wool, etc.)\n";
                $system_prompt .= "- Include color in product names\n";
                $system_prompt .= "- Consider seasonal items\n";
                break;

            case 'electronics':
            case 'tech':
                $system_prompt .= "- Include variety: phones, laptops, accessories, audio, home tech\n";
                $system_prompt .= "- Include key specs in description\n";
                $system_prompt .= "- Use brand-style naming\n";
                $system_prompt .= "- Higher price range is acceptable\n";
                break;

            case 'food':
            case 'grocery':
                $system_prompt .= "- Include variety: snacks, beverages, pantry items, fresh goods\n";
                $system_prompt .= "- Include weight/quantity in description\n";
                $system_prompt .= "- Note dietary info (organic, gluten-free, etc.)\n";
                $system_prompt .= "- Consider shelf life\n";
                break;

            case 'home':
            case 'furniture':
            case 'home goods':
                $system_prompt .= "- Include variety: furniture, decor, kitchen, bedding, storage\n";
                $system_prompt .= "- Include dimensions where relevant\n";
                $system_prompt .= "- Mention materials and colors\n";
                $system_prompt .= "- Consider room/area categories\n";
                break;

            case 'beauty':
            case 'cosmetics':
                $system_prompt .= "- Include variety: skincare, makeup, hair care, fragrances\n";
                $system_prompt .= "- Include size/volume\n";
                $system_prompt .= "- Mention key ingredients\n";
                $system_prompt .= "- Note skin types where applicable\n";
                break;

            default:
                $system_prompt .= "- Create diverse products appropriate for a {$store_type} store\n";
                $system_prompt .= "- Use realistic naming conventions\n";
                $system_prompt .= "- Include relevant product details\n";
                break;
        }

        $system_prompt .= "\n## Example create_product Call:\n";
        $system_prompt .= "```json\n";
        $system_prompt .= "{\n";
        $system_prompt .= "  \"name\": \"Classic Navy Cotton T-Shirt\",\n";
        $system_prompt .= "  \"sku\": \"TSH-NAV-001\",\n";
        $system_prompt .= "  \"description\": \"A comfortable everyday t-shirt made from 100% organic cotton. Features a classic crew neck and relaxed fit.\",\n";
        $system_prompt .= "  \"short_description\": \"Comfortable organic cotton t-shirt in navy blue.\",\n";
        $system_prompt .= "  \"price\": 29.99,\n";
        if ($include_sales) {
            $system_prompt .= "  \"sale_price\": 24.99,\n";
        }
        $system_prompt .= "  \"stock\": 75,\n";
        $system_prompt .= "  \"low_stock_threshold\": 10,\n";
        $system_prompt .= "  \"featured\": false,\n";
        $system_prompt .= "  \"category_ids\": [1],\n";
        $system_prompt .= "  \"tag_ids\": [2, 5]\n";
        $system_prompt .= "}\n";
        $system_prompt .= "```\n\n";

        $system_prompt .= "## Important Notes:\n";
        $system_prompt .= "- Create products ONE AT A TIME using the create_product tool\n";
        $system_prompt .= "- Each SKU must be unique\n";
        $system_prompt .= "- Verify category_ids and tag_ids exist before using them\n";
        $system_prompt .= "- Report progress after every 5 products\n";
        $system_prompt .= "- Provide a summary when complete\n\n";

        $system_prompt .= "Begin by fetching the available categories and tags, then start creating products.";

        return [
            'description' => "Bulk product creation for {$store_type} store ({$product_count} products)",
            'messages' => [
                [
                    'role' => 'user',
                    'content' => [
                        [
                            'type' => 'text',
                            'text' => $system_prompt
                        ]
                    ]
                ]
            ]
        ];
    }
}
