<?php
/**
 * cron_get_orders_from_shopify.php
 * Fetch Shopify orders and save everything related locally:
 * orders, orders_info, order_payments, payment_methods, payment_method_mappings,
 * products, product_variant_mappings, sku_mappings, refund JSON/status.
 */
require_once __DIR__ . '/includes/cron_shopify_core.php';
core_secret_check();

try {
    core_ensure_runtime_columns();

    $limit = core_int_param('limit', 100, 1, 5000);
    $first = core_int_param('first', 100, 1, 250);
    $query = isset($_GET['query']) ? trim((string)$_GET['query']) : null;
    $specificOrderId = isset($_GET['shopify_order_id']) ? trim((string)$_GET['shopify_order_id']) : '';
    $fetchProducts = core_bool_param('fetch_products', true);
    $fetchRefunds = core_bool_param('fetch_refunds', true);

    $summary = [
        'ok' => true,
        'message' => 'Shopify orders fetch completed.',
        'filters' => [
            'shopify_order_id' => $specificOrderId ?: null,
            'query' => $query,
            'limit' => $limit,
            'first' => $first,
            'fetch_products' => $fetchProducts,
            'fetch_refunds' => $fetchRefunds,
        ],
        'pages' => 0,
        'seen' => 0,
        'saved_orders' => 0,
        'saved_lines' => 0,
        'saved_payments' => 0,
        'saved_payment_methods' => 0,
        'saved_products' => 0,
        'saved_variants' => 0,
        'saved_skus' => 0,
        'refund_orders_found' => 0,
        'errors' => [],
        'items' => [],
    ];

    $orderIds = [];
    if ($specificOrderId !== '') {
        $orderIds[] = $specificOrderId;
    } else {
        $after = null;
        do {
            $remaining = $limit - $summary['seen'];
            if ($remaining <= 0) break;
            $currentFirst = min($first, $remaining);
            $data = shopify_graphql(shopify_order_list_query(), ['first' => $currentFirst, 'after' => $after, 'query' => $query]);
            $ordersBlock = is_array($data['orders'] ?? null) ? $data['orders'] : [];
            $edges = is_array($ordersBlock['edges'] ?? null) ? $ordersBlock['edges'] : [];
            $summary['pages']++;
            foreach ($edges as $edge) {
                $node = is_array($edge['node'] ?? null) ? $edge['node'] : [];
                $sid = (string)($node['legacyResourceId'] ?? '');
                if ($sid !== '') {
                    $orderIds[] = $sid;
                    $summary['seen']++;
                }
                if ($summary['seen'] >= $limit) break;
            }
            $pageInfo = is_array($ordersBlock['pageInfo'] ?? null) ? $ordersBlock['pageInfo'] : [];
            $hasNext = !empty($pageInfo['hasNextPage']);
            $after = (string)($pageInfo['endCursor'] ?? '');
            if ($after === '') $hasNext = false;
        } while ($hasNext);
    }

    foreach ($orderIds as $sid) {
        try {
            $order = shopify_get_order_detail($sid);
            if (!$order) throw new RuntimeException('Empty Shopify order response.');
            $refunds = $fetchRefunds ? shopify_get_refunds_for_order($sid) : [];
            $orderRow = upsert_order($order, $refunds);
            if (!$orderRow || empty($orderRow['id'])) throw new RuntimeException('Order was not saved locally.');
            $orderDbId = (int)$orderRow['id'];
            $payments = upsert_payment_methods_and_transactions($orderDbId, $sid, $order);
            $lines = upsert_order_lines_and_catalog($orderDbId, $sid, $order, $fetchProducts);
            if (count($refunds) > 0) $summary['refund_orders_found']++;
            $summary['saved_orders']++;
            $summary['saved_payment_methods'] += (int)$payments['payment_methods'];
            $summary['saved_payments'] += (int)$payments['order_payments'];
            $summary['saved_lines'] += (int)$lines['orders_info'];
            $summary['saved_products'] += (int)$lines['products'];
            $summary['saved_variants'] += (int)$lines['product_variant_mappings'];
            $summary['saved_skus'] += (int)$lines['sku_mappings'];
            log_sync('info', 'shopify_orders', 'Shopify order saved to database.', ['shopify_order_id' => $sid, 'order_db_id' => $orderDbId]);
            $summary['items'][] = ['shopify_order_id' => $sid, 'order_db_id' => $orderDbId, 'refunds_count' => count($refunds), 'status' => 'saved'];
        } catch (Throwable $e) {
            $summary['errors'][] = ['shopify_order_id' => $sid, 'message' => $e->getMessage()];
            log_sync('error', 'shopify_orders', 'Failed to save Shopify order.', ['shopify_order_id' => $sid, 'error' => $e->getMessage()]);
        }
    }

    $summary['error_count'] = count($summary['errors']);
    core_json($summary);
} catch (Throwable $e) {
    core_fail('Shopify orders fetch failed.', ['error' => $e->getMessage()], 500);
}
