<?php

namespace ReviewX\Services;

\defined("ABSPATH") || exit;
use ReviewX\Api\OrderApi;
use ReviewX\Utilities\Auth\Client;
use ReviewX\Utilities\Helper;
use ReviewX\WPDrill\Response;
class OrderService extends \ReviewX\Services\Service
{
    public function __construct()
    {
    }
    public function updateOrder($order_id)
    {
        $order = wc_get_order($order_id);
        if (!$order) {
            return;
        }
        $payload = $this->prepareData($order);
        $uid = Client::getUid() . '-' . $order_id;
        $response = (new OrderApi())->update($payload, $uid);
        if ($response->getStatusCode() !== Response::HTTP_OK) {
            return \false;
        }
    }
    public function prepareData($order)
    {
        $status = $order->get_status();
        $status_mapping = $this->orderStatusArray();
        $date_created = $order->get_date_created();
        $created_at = $date_created ? \wp_date('Y-m-d H:i:s', $date_created->getTimestamp()) : null;
        $date_modified = $order->get_date_modified();
        $updated_at = $date_modified ? \wp_date('Y-m-d H:i:s', $date_modified->getTimestamp()) : \wp_date('Y-m-d H:i:s');
        // Get the order state, ensure a fallback if 'date_paid' doesn't exist
        $order_state = $this->wooOrderState($order);
        $paid_at = $order_state['date_paid'] ?? null;
        $orderData = ["wp_id" => (int) $order->get_id(), "customer_wp_unique_id" => Client::getUid() . '-' . (int) $order->get_customer_id(), "subtotal" => (float) $order->get_subtotal(), "tax" => (float) $order->get_total_tax(), "total" => (float) $order->get_total(), "status" => Helper::orderStatus($order->get_status()), "review_request_email_sent_at" => null, "review_reminder_email_sent_at" => null, "photo_review_email_sent_at" => null, "paid_at" => $paid_at, "created_at" => $created_at, "updated_at" => $updated_at];
        if (isset($status_mapping[$status])) {
            $orderData[$status_mapping[$status]] = \wp_date('Y-m-d H:i:s');
        }
        return ['order' => $orderData, 'order_items' => $this->orderItems($order, $orderData)];
    }
    public function orderStatusArray() : array
    {
        return ['processing' => 'processing_at', 'pending_payment' => 'pending_payment_at', 'on_hold' => 'on_hold_at', 'completed' => 'completed_at', 'cancelled' => 'cancelled_at', 'refunded' => 'refunded_at', 'failed' => 'failed_at', 'draft' => 'draft_at'];
    }
    public function wooOrderState($order)
    {
        if (!$order) {
            return ['date_paid' => null, 'date_completed' => null];
        }
        $date_paid = $order->get_date_paid();
        $date_completed = $order->get_date_completed();
        return ['date_paid' => $date_paid ? \wp_date('Y-m-d H:i:s', $date_paid->getTimestamp()) : null, 'date_completed' => $date_completed ? \wp_date('Y-m-d H:i:s', $date_completed->getTimestamp()) : null];
    }
    public function orderItems($order, $orderData = [])
    {
        $date = $this->wooOrderState($order);
        $items_data = [];
        $order_items = $order->get_items();
        foreach ($order_items as $order_item) {
            $product = $order_item->get_product();
            if ($product) {
                $item_data = ["wp_id" => (int) $order_item->get_id(), "wp_unique_id" => Client::getUid() . '-' . (int) $order_item->get_id(), "product_wp_unique_id" => Client::getUid() . '-' . (int) $product->get_id(), "review_id" => null, "site_id" => Client::getSiteId(), "name" => $product->get_name(), "quantity" => $order_item->get_quantity(), "price" => (float) $product->get_price(), "reviewed_at" => null, "fulfillment_status" => Helper::orderItemStatus($order->get_status())];
                if ($order->get_status() !== 'completed') {
                    $item_data['fulfilled_at'] = \wp_date('Y-m-d H:i:s');
                }
                if ($order->get_status() == 'completed') {
                    $item_data['fulfilled_at'] = !empty($date['date_completed']) && \strtotime($date['date_completed']) ? \wp_date('Y-m-d H:i:s', \strtotime($date['date_completed'])) : \wp_date('Y-m-d H:i:s');
                }
                $items_data[] = $item_data;
            }
        }
        return $items_data;
    }
}
