<?php
/**
 * Read-only diagnostic: dump the Shopify metaobject definitions, a product's
 * options/metafields, and (optionally) all entries of a metaobject type so we can
 * discover the exact Wood / Length / Thickness option lists used by the storefront
 * millwork configurator.
 *
 * Usage (open in browser, same host as the admin app):
 *   /admin/millwork_choices_probe.php
 *   /admin/millwork_choices_probe.php?handle=base-2215-for-flat-sawn-baluster
 *   /admin/millwork_choices_probe.php?type=<metaobject_type>      (dump all entries of a type)
 *
 * This page performs NO writes. Delete it once the lists are captured.
 */
require __DIR__ . '/config.php';
require_once __DIR__ . '/admin_config_helpers-dp.php';

header('Content-Type: text/plain; charset=utf-8');

function probe_out($label, $data) {
    echo "==== {$label} ====\n";
    echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n\n";
}

if (!function_exists('admin_shopify_gql_request')) {
    echo "admin_shopify_gql_request() not available.\n";
    exit;
}
if (!admin_shopify_is_configured()) {
    echo "Shopify API is not configured (SHOPIFY_SHOP / SHOPIFY_ACCESS_TOKEN missing in config.php).\n";
    exit;
}

$handle = isset($_GET['handle']) && $_GET['handle'] !== ''
    ? (string) $_GET['handle']
    : 'base-2215-for-flat-sawn-baluster';
$type = isset($_GET['type']) ? trim((string) $_GET['type']) : '';

// Fetch one metaobject by GID and expand any reference fields one level (the choices).
function probe_fetch_metaobject($gid) {
    $q = <<<'GQL'
query($id: ID!) {
  metaobject(id: $id) {
    id
    type
    handle
    displayName
    fields {
      key
      value
      type
      references(first: 100) {
        nodes {
          __typename
          ... on Metaobject { id type handle displayName fields { key value } }
        }
      }
    }
  }
}
GQL;
    $res = admin_shopify_gql_request($q, ['id' => $gid]);
    if (empty($res['ok'])) {
        return ['error' => $res['error'] ?? 'unknown', 'id' => $gid];
    }
    $mo = $res['data']['metaobject'] ?? null;
    if (!$mo) return ['error' => 'not found', 'id' => $gid];
    $out = [
        'id' => $mo['id'] ?? '',
        'type' => $mo['type'] ?? '',
        'handle' => $mo['handle'] ?? '',
        'displayName' => $mo['displayName'] ?? '',
        'fields' => [],
    ];
    foreach (($mo['fields'] ?? []) as $f) {
        $entry = ['key' => $f['key'] ?? '', 'type' => $f['type'] ?? '', 'value' => $f['value'] ?? null];
        $refs = $f['references']['nodes'] ?? [];
        if (!empty($refs)) {
            $entry['references'] = [];
            foreach ($refs as $r) {
                $rf = [];
                foreach (($r['fields'] ?? []) as $rfld) {
                    $rf[$rfld['key']] = $rfld['value'];
                }
                $entry['references'][] = [
                    'type' => $r['type'] ?? '',
                    'handle' => $r['handle'] ?? '',
                    'displayName' => $r['displayName'] ?? '',
                    'fields' => $rf,
                ];
            }
        }
        $out['fields'][] = $entry;
    }
    return $out;
}

// 2) Product options + metafields (Length / Thickness often live here).
$prodQuery = <<<'GQL'
query($q: String!) {
  products(first: 1, query: $q) {
    nodes {
      id
      title
      handle
      options { name optionValues { name } }
      metafields(first: 50) {
        nodes { namespace key type value }
      }
    }
  }
}
GQL;
$prod = admin_shopify_gql_request($prodQuery, ['q' => 'handle:' . $handle]);
$productNode = null;
if (!empty($prod['ok'])) {
    $productNode = $prod['data']['products']['nodes'][0] ?? null;
    probe_out("PRODUCT (handle: {$handle})", $productNode);
} else {
    probe_out('PRODUCT — ERROR', $prod['error'] ?? 'unknown');
}

// 2b) Auto-follow custom.door_config_options -> the Wood / Length / Thickness option
//     metaobjects, expanding their choices. This is the direct source of the dropdowns.
$configOptionGids = [];
if (is_array($productNode)) {
    foreach (($productNode['metafields']['nodes'] ?? []) as $mf) {
        if (($mf['key'] ?? '') === 'door_config_options') {
            $decoded = json_decode((string) ($mf['value'] ?? ''), true);
            if (is_array($decoded)) {
                foreach ($decoded as $gid) {
                    if (is_string($gid) && $gid !== '') $configOptionGids[] = $gid;
                }
            }
        }
    }
}
// Allow overriding / adding explicit GIDs via ?gid=gid1,gid2
if (isset($_GET['gid']) && $_GET['gid'] !== '') {
    foreach (explode(',', (string) $_GET['gid']) as $g) {
        $g = trim($g);
        if ($g !== '') $configOptionGids[] = $g;
    }
}
$configOptionGids = array_values(array_unique($configOptionGids));
foreach ($configOptionGids as $gid) {
    probe_out("CONFIG OPTION METAOBJECT {$gid}", probe_fetch_metaobject($gid));
}

// 3) Optionally dump all entries of a metaobject type (e.g. the wood list).
if ($type !== '') {
    $entriesQuery = <<<'GQL'
query($type: String!, $after: String) {
  metaobjects(type: $type, first: 100, after: $after) {
    nodes { handle displayName fields { key value } }
    pageInfo { hasNextPage endCursor }
  }
}
GQL;
    $all = [];
    $after = null;
    $guard = 0;
    do {
        $res = admin_shopify_gql_request($entriesQuery, ['type' => $type, 'after' => $after]);
        if (empty($res['ok'])) {
            probe_out("METAOBJECTS type={$type} — ERROR", $res['error'] ?? 'unknown');
            break;
        }
        $node = $res['data']['metaobjects'] ?? [];
        foreach (($node['nodes'] ?? []) as $n) {
            $f = [];
            foreach (($n['fields'] ?? []) as $fld) {
                $f[$fld['key']] = $fld['value'];
            }
            $all[] = ['handle' => $n['handle'] ?? '', 'displayName' => $n['displayName'] ?? '', 'fields' => $f];
        }
        $hasNext = !empty($node['pageInfo']['hasNextPage']);
        $after = $node['pageInfo']['endCursor'] ?? null;
        $guard++;
    } while ($hasNext && $guard < 20);

    if (!empty($all)) {
        probe_out("METAOBJECTS type={$type} (" . count($all) . ' entries)', $all);
    }
}

echo "Done. The CONFIG OPTION METAOBJECT blocks above hold the Wood / Length / Thickness\n";
echo "choices used by the storefront. If a choice list lives in a separate metaobject type,\n";
echo "reload with ?type=<that type> to dump every entry.\n";
