<?php

namespace Kanzu\StoreVoiceAI\Services;

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

class Order_Search
{

    public function get_order_details($order_id)
    {
    
        // Fetch the order object using WooCommerce's WC_Order class
        $order = wc_get_order($order_id);

        // If the order is not found, return an error
        if (!$order) {
            return new \WP_Error('order_not_found', 'Sorry, I couldn’t find an order with that ID.', array('status' => 404));
        }

        // Get order data
        $order_status        = $order->get_status();
        $order_total         = $order->get_total();
        $order_currency      = $order->get_currency();
        $customer_first_name = $order->get_billing_first_name();
        $customer_last_name  = $order->get_billing_last_name();
        $customer_email      = $order->get_billing_email();
        $customer_phone      = $order->get_billing_phone();

        // Build the conversational response
        $response_message = "Here’s the information for order #{$order_id}. ";

        $response_message .= "The order is currently {$order_status}. ";

        $response_message .= "The total amount is {$order_total} {$order_currency}. ";

        $response_message .= "The customer is {$customer_first_name} {$customer_last_name}, you can reach them by email at {$customer_email} or by phone at {$customer_phone}. ";

        // Loop through order items and summarize them for the voice assistant
        $response_message .= "This order includes the following items: ";

        $items      = $order->get_items();
        $item_count = 0;

        foreach ($items as $item_id => $item) {
            $product = $item->get_product();
            $item_count++;
            $response_message .= "{$item->get_quantity()} of {$item->get_name()}, ";
            if ($item_count == count($items) - 1) {
                $response_message .= "and ";
            }
        }

        $response_message .= "This should give you everything you need. Is there anything else I can help you with?";

        // Return the response in a voice-friendly format
        return $response_message;
       
    }

}
