<?php
/**
 * cron_get_locations_from_shopify.php
 * Fetch Shopify Locations into shopify_locations and shopify_location_mappings.
 */
require_once __DIR__ . '/includes/cron_shopify_core.php';
core_secret_check();
try {
    $limit = core_int_param('limit', 500, 1, 5000);
    $first = core_int_param('first', 100, 1, 250);
    $onlyActive = core_bool_param('only_active', false);
    $summary = ['ok' => true, 'message' => 'Shopify locations fetch completed.', 'pages' => 0, 'seen' => 0, 'saved' => 0, 'errors' => [], 'items' => []];
    $after = null;
    do {
        $remaining = $limit - $summary['seen'];
        if ($remaining <= 0) break;
        $currentFirst = min($first, $remaining);
        $data = shopify_graphql(shopify_locations_query(), [
            'first' => $currentFirst,
            'after' => $after,
            'includeInactive' => !$onlyActive,
            'includeLegacy' => true,
        ]);
        $block = is_array($data['locations'] ?? null) ? $data['locations'] : [];
        $edges = is_array($block['edges'] ?? null) ? $block['edges'] : [];
        $summary['pages']++;
        foreach ($edges as $edge) {
            $loc = is_array($edge['node'] ?? null) ? $edge['node'] : [];
            $summary['seen']++;
            try {
                upsert_shopify_location($loc);
                $summary['saved']++;
                $summary['items'][] = ['shopify_location_id' => $loc['legacyResourceId'] ?? null, 'name' => $loc['name'] ?? null, 'status' => 'saved'];
            } catch (Throwable $e) {
                $summary['errors'][] = ['location' => $loc, 'message' => $e->getMessage()];
            }
            if ($summary['seen'] >= $limit) break;
        }
        $pageInfo = is_array($block['pageInfo'] ?? null) ? $block['pageInfo'] : [];
        $hasNext = !empty($pageInfo['hasNextPage']);
        $after = (string)($pageInfo['endCursor'] ?? '');
        if ($after === '') $hasNext = false;
    } while ($hasNext);
    $summary['error_count'] = count($summary['errors']);
    core_json($summary);
} catch (Throwable $e) {
    core_fail('Shopify locations fetch failed.', ['error' => $e->getMessage()], 500);
}
