<?php
if (!defined('ABSPATH')) exit;

/** On order completion, post it back to RecordGod so it marks the SKUs sold + logs the online sale. */
class RG_Orders {

    static function init() {
        add_action('woocommerce_order_status_completed', [__CLASS__, 'push'], 10, 1);
    }

    static function push($order_id) {
        $order = wc_get_order($order_id);
        if (!$order || $order->get_meta('_rg_synced')) return;   // idempotent (RecordGod also dedups on WC-<id>)

        $items = [];
        foreach ($order->get_items() as $line) {
            $product = $line->get_product();
            $sku = $product ? $product->get_sku() : '';
            if (!$sku) continue;
            $items[] = [
                'sku'   => $sku,
                'name'  => $line->get_name(),
                'qty'   => (int) $line->get_quantity(),
                'price' => (float) $order->get_item_total($line, false),
            ];
        }
        if (!$items) return;

        [$code, $body] = RG_API::post('/shop/woo-order', [
            'order_number' => (string) $order->get_order_number(),
            'email' => $order->get_billing_email(),
            'name'  => trim($order->get_formatted_billing_full_name()),
            'total' => (float) $order->get_total(),
            'items' => $items,
        ]);

        if ($code === 200) {
            $order->update_meta_data('_rg_synced', current_time('mysql'));
        } else {
            $order->update_meta_data('_rg_sync_error', "HTTP $code");
            $order->add_order_note('RecordGod sync failed (HTTP ' . $code . ') — retry from order actions.');
        }
        $order->save();
    }
}
