<?php

namespace Kanzu\StoreVoiceAI\ResponseHandlers;

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

use Kanzu\StoreVoiceAI\Services\Account_Info;
use Kanzu\StoreVoiceAI\Services\Discount_Offers;
use Kanzu\StoreVoiceAI\Services\Order_Search;
use Kanzu\StoreVoiceAI\Services\Product_Search;

class Voice_Response_Handler
{

    public function handle_get_order_details_tool_call(\WP_REST_Request $request)
    {
        if (!isset($request['message']['toolCalls'][0]['function']['name'])) {
            return new \WP_Error('invalid_payload', 'Function name not found in payload', ['status' => 400]);
        }

        if (!isset($request['message']['toolCalls'][0]['function']['arguments']['orderId'])) {
            return new \WP_Error('invalid_payload', 'Order ID not found in payload', ['status' => 400]);
        }

        $tool_call_id = sanitize_text_field($request['message']['toolCalls'][0]['id']);

        $order_search     = new Order_Search();
        $response_message = $order_search->get_order_details($request['message']['toolCalls'][0]['function']['arguments']['orderId']);
        return rest_ensure_response(array(
            'results' => array(
                array(
                    'toolCallId' => $tool_call_id,
                    'result'     => $response_message,
                ),
            ),
        ));
    }

    // Callback function to handle the offer search
    public function handle_get_user_info_tool_call(\WP_REST_Request $request)
    {
        if (!isset($request['message']['toolCalls'][0]['function']['name'])) {
            return new \WP_Error('invalid_payload', 'Function name not found in payload', ['status' => 400]);
        }

        if (!isset($request['message']['toolCalls'][0]['function']['arguments']['userEmail'])) {
            return new \WP_Error('invalid_payload', 'Email not found in payload', ['status' => 400]);
        }
        $tool_call_id = sanitize_text_field($request['message']['toolCalls'][0]['id']);

        $user_info = new Account_Info();
        $user_data = $user_info->get_user_account_details($request['message']['toolCalls'][0]['function']['arguments']['userEmail']);
        if (!$user_data) {
            return new \WP_Error('user_not_found', 'No user found with this email address.', array('status' => 404));
        }
        return rest_ensure_response([
            'results' => [
                [
                    'toolCallId' => $tool_call_id,
                    'result'     => $user_data,
                ],
            ],
        ]);
    }

    // Callback function to handle the offer search
    public function handle_offer_search_tool_call(\WP_REST_Request $request)
    {
        if (!isset($request['message']['toolCalls'][0]['function']['name'])) {
            return new \WP_Error('invalid_payload', 'Function name not found in payload', ['status' => 400]);
        }

        $voice_coupons = new Discount_Offers();
        $tool_call_id  = sanitize_text_field($request['message']['toolCalls'][0]['id']);

        // Get active coupons
        $coupons = $voice_coupons->get_active_coupons();

        // Get products on sale
        $sale_products = $voice_coupons->get_sale_products();

        // Create a response message
        $response_message = '';

        if (!empty($coupons)) {
            $response_message .= "We currently have the following discount coupons available:\n";
            foreach ($coupons as $coupon) {
                $response_message .= "- {$coupon['code']} ({$coupon['description']})\n";
            }
        }

        if (!empty($sale_products)) {
            if (!empty($coupons)) {
                $response_message .= "\nAdditionally, here are some products on sale:\n";
            } else {
                $response_message .= "Here are some products on sale:\n";
            }

            foreach ($sale_products as $product) {
                $response_message .= "- {$product['name']} (Was {$product['regular_price']}, now {$product['sale_price']})\n";
            }
        }

        // If there are no offers or discounts, inform the user
        if (empty($coupons) && empty($sale_products)) {
            $response_message = "Currently, there are no offers or discounts available.";
        }

        return rest_ensure_response([
            'results' => [
                [
                    'toolCallId' => $tool_call_id,
                    'result'     => $response_message,
                ],
            ],
        ]);
    }

    // Callback function to handle the product search
    public function handle_product_search_tool_call(\WP_REST_Request $request)
    {

        if (!isset($request['message']['toolCalls'][0]['function']['arguments']['productName'])) {
            return new \WP_Error('invalid_payload', 'Product name not found in payload', ['status' => 400]);
        }

        // Extract search term and toolCallId from the request payload
        $search_term  = sanitize_text_field($request['message']['toolCalls'][0]['function']['arguments']['productName']);
        $tool_call_id = sanitize_text_field($request['message']['toolCalls'][0]['id']);

        // Query WooCommerce for products matching the search term
        $product_search        = new Product_Search();
        $product_results_query = $product_search->search_products_by_name($search_term);

        // Prepare response structure
        $results = [];
        if ($product_results_query->have_posts()) {
            while ($product_results_query->have_posts()) {
                $product_results_query->the_post();

                // Get product details (you can adjust this based on what data you need)
                $product   = wc_get_product(get_the_ID());
                $options   = $this->get_available_colors($product); // public function to retrieve product options (colors, etc.)
                $results[] = [
                    'toolCallId' => $tool_call_id,
                    'result'     => [
                        'name'         => $product->get_name(),
                        'price'        => $product->get_price(),
                        'sale_price'   => $product->get_sale_price(),
                        'description'  => $product->get_short_description(),
                        'availability' => $product->is_in_stock() ? "In Stock" : "Out of Stock",
                        'link'         => get_permalink($product->get_id()),
                        'options'      => $options, // Include available color options
                    ],
                ];
            }
            wp_reset_postdata();
        }

        if (empty($results)) {
            return rest_ensure_response([
                'message' => 'Sorry, no products found matching that name.',
            ]);
        }

        $response_message = $this->generate_conversational_prompt($results);

        // Return the results
        return rest_ensure_response([
            'results' => [
                [
                    'toolCallId' => $tool_call_id,
                    'result'     => $response_message,
                ],
            ],
        ]);
    }

    private function generate_conversational_prompt($results)
    {
        if (count($results) > 1) {
            $product_details = [];
            foreach ($results as $result) {
                $name              = $result['result']['name'];
                $price             = $result['result']['price'];
                $availability      = $result['result']['availability'];
                $options           = implode(", ", $result['result']['options']);
                $product_details[] = "The $name, priced at $$price, is available in $options and is $availability.";
            }

            $response_message = implode(" ", $product_details);
            $response_message .= " Would you like more details on any of these or view more options?";
            return $response_message;

        } else {
            // If only one product is found, offer it immediately
            $product_name        = $results[0]['result']['name'];
            $product_description = $results[0]['result']['description'];
            $price               = $results[0]['result']['price'];
            $availability        = $results[0]['result']['availability'];
            $options             = implode(", ", $results[0]['result']['options']);
            $response_message    = "I found the product '$product_name',  priced at $$price. It is available in $options and is $availability. $product_description. Would you like any more details or to make a purchase?";
            return $response_message;
        }
    }

    // Get available color options for a product
    private function get_available_colors($product)
    {
        // This is a placeholder for how you might retrieve product options (e.g., colors)
        // Assume that "colors" are stored as product attributes (you can customize this based on your product setup)
        $colors = $product->get_attribute('color');
        return $colors ? explode(',', $colors) : [];
    }

    // Permission callback to check the secret key
    public function check_secret_key_permission()
    {
        $headers    = getallheaders();
        $secret_key = isset($headers['X-Vapi-Secret']) ? $headers['X-Vapi-Secret'] : '';

        $valid_secret_key = get_option('_storevoiceai_serversecret');

        if (hash_equals((string) $valid_secret_key, (string) $secret_key)) {
            return true;
        }

        return new \WP_Error('forbidden', 'Invalid secret key', ['status' => 403]);
    }

}
