<?php
/**
 * Admin: Upload CSV to update config_choice prices (price_value and price_overrides).
 * CSV columns: option_name, price_value, then optional override sets (1 to N):
 *   price_when_key, price_when_value, price_when_type, price_when_value_number  [set 1]
 *   price_when_key2, price_when_value2, price_when_type2, price_when_value_number2 [set 2]
 *   ... price_when_key8, ... etc. (as many as needed).
 * Requires SHOPIFY_STORE and SHOPIFY_ADMIN_ACCESS_TOKEN (write_metaobjects and read_metaobjects scopes).
 */

 header_remove('X-Frame-Options');
header('Content-Security-Policy: frame-ancestors https://admin.shopify.com https://*.myshopify.com');
  
require __DIR__ . '/config.php';

if (isset($_GET['download']) && $_GET['download'] === '1') {
    $maxSets = 8;
    $sampleHeaders = ['option_name', 'price_value'];
    for ($s = 1; $s <= $maxSets; $s++) {
        $suffix = $s === 1 ? '' : (string)$s;
        $sampleHeaders[] = 'price_when_key' . $suffix;
        $sampleHeaders[] = 'price_when_value' . $suffix;
        $sampleHeaders[] = 'price_when_type' . $suffix;
        $sampleHeaders[] = 'price_when_value_number' . $suffix;
    }
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="config_prices_sample.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, $sampleHeaders);
    $emptySets = array_fill(0, ($maxSets - 1) * 4, '');
    fputcsv($out, array_merge(['premium-lever', '15', 'material', 'steel', 'fixed', '20'], $emptySets));
    fputcsv($out, array_merge(['frosted', '12', 'material', 'steel', 'fixed', '20', 'material', 'wood', 'fixed', '27'], array_fill(0, ($maxSets - 2) * 4, '')));
    fputcsv($out, array_merge(['clear', '10', 'material', 'steel', 'fixed', '25'], $emptySets));
    fclose($out);
    exit;
}

if (!function_exists('h')) {
    function h($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}

// Get Shopify store and API access token from environment variables.
// You can set these in your server environment, .env file, or before running the script like:
//   export SHOPIFY_STORE="your-store.myshopify.com"
//   export SHOPIFY_ADMIN_ACCESS_TOKEN="shpat_xxxxx"
// Alternatively, you can set them using ini_set or $_ENV, but environment variables are standard.
// Ask your Shopify admin (or the person who set up the app) for the correct values.
$store =  'g1hj10-vk.myshopify.com';
$token =  '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';
$store = preg_replace('#^https?://#', '', rtrim($store, '/'));
$apiUrl = $store && $token ? 'https://' . $store . '/admin/api/2024-01/graphql.json' : '';

$updated = 0;
$errors = [];
$done = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $apiUrl && !empty($_FILES['csv']['tmp_name']) && is_uploaded_file($_FILES['csv']['tmp_name'])) {
    $fh = fopen($_FILES['csv']['tmp_name'], 'r');
    if ($fh) {
        $header = fgetcsv($fh);
        if ($header !== false) {
            $header = array_map('trim', $header);
            $need = ['option_name', 'price_value'];
            $hasNeed = true;
            foreach ($need as $c) {
                if (!in_array($c, $header, true)) { $hasNeed = false; break; }
            }
            if ($hasNeed) {
                $rows = [];
                while (($line = fgetcsv($fh)) !== false) {
                    $row = array_combine($header, array_pad($line, count($header), ''));
                    if ($row !== false && trim((string)($row['option_name'] ?? '')) !== '') {
                        $rows[] = $row;
                    }
                }
                fclose($fh);

                // Detect max override set from header (price_when_key, price_when_key2, ... price_when_key8, etc.)
                $maxOverrideSets = 0;
                foreach ($header as $h) {
                    if ($h === 'price_when_key') {
                        $maxOverrideSets = max($maxOverrideSets, 1);
                    } elseif (preg_match('/^price_when_key(\d+)$/', $h, $m)) {
                        $maxOverrideSets = max($maxOverrideSets, (int)$m[1]);
                    }
                }

                // Pre-fetch all config_choice metaobjects once (for fallback lookup by "value" field). Requires read_metaobjects scope.
                $configChoiceList = null;
                $listQuery = json_encode([
                    'query' => 'query { metaobjects(first: 250, type: "config_choice") { nodes { id handle valueField: field(key: "value") { value } } } }',
                ]);
                $ch = curl_init($apiUrl);
                curl_setopt_array($ch, [
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => $listQuery,
                    CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'X-Shopify-Access-Token: ' . $token],
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_TIMEOUT => 30,
                ]);
                $res = curl_exec($ch);
                curl_close($ch);
                $listData = $res ? json_decode($res, true) : null;
                $listFailed = false;
                if (isset($listData['errors']) && is_array($listData['errors'])) {
                    $errMsg = implode(' ', array_map(function ($e) { return $e['message'] ?? json_encode($e); }, $listData['errors']));
                    $errors[] = 'Could not list config_choice entries from Shopify: ' . $errMsg . ' Ensure the API token has read_metaobjects scope.';
                    $listFailed = true;
                } else {
                    $configChoiceList = $listData['data']['metaobjects']['nodes'] ?? [];
                }

                foreach ($rows as $i => $row) {
                    $optionName = trim((string)($row['option_name'] ?? ''));
                    $priceValue = trim((string)($row['price_value'] ?? ''));
                    $overrides = [];
                    for ($s = 1; $s <= $maxOverrideSets; $s++) {
                        $suffix = $s === 1 ? '' : (string)$s;
                        $key = trim((string)($row['price_when_key' . $suffix] ?? ''));
                        $val = trim((string)($row['price_when_value' . $suffix] ?? ''));
                        if ($key !== '' && $val !== '') {
                            $type = trim((string)($row['price_when_type' . $suffix] ?? 'fixed'));
                            $num = trim((string)($row['price_when_value_number' . $suffix] ?? '0'));
                            $overrides[] = [
                                'price_when_key' => $key,
                                'price_when_value' => $val,
                                'price_when_type' => $type ?: 'fixed',
                                'price_when_value_number' => $num !== '' ? $num : '0',
                            ];
                        }
                    }

                    $id = null;
                    // 1) Try by handle (exact match)
                    $query = json_encode([
                        'query' => 'query($handle: MetaobjectHandleInput!) { metaobjectByHandle(handle: $handle) { id } }',
                        'variables' => ['handle' => ['handle' => $optionName, 'type' => 'config_choice']],
                    ]);
                    $ch = curl_init($apiUrl);
                    curl_setopt_array($ch, [
                        CURLOPT_POST => true,
                        CURLOPT_POSTFIELDS => $query,
                        CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'X-Shopify-Access-Token: ' . $token],
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_TIMEOUT => 30,
                    ]);
                    $res = curl_exec($ch);
                    curl_close($ch);
                    $data = $res ? json_decode($res, true) : null;
                    $meta = $data['data']['metaobjectByHandle'] ?? null;
                    if ($meta && !empty($meta['id'])) {
                        $id = $meta['id'];
                    }
                    // 2) Fallback: find by "value" field using pre-fetched list
                    if (!$id && is_array($configChoiceList)) {
                        foreach ($configChoiceList as $node) {
                            $val = isset($node['valueField']['value']) ? (string)$node['valueField']['value'] : '';
                            if ($val === (string)$optionName) {
                                $id = $node['id'];
                                break;
                            }
                        }
                    }
                    if (!$id) {
                        if (!$listFailed) {
                            $errors[] = 'Row ' . ($i + 2) . " ({$optionName}): not found in Shopify (option_name must match handle or the 'value' field of a config_choice).";
                        }
                        continue;
                    }

                    $fields = [
                        ['key' => 'price_value', 'value' => $priceValue !== '' ? $priceValue : '0'],
                    ];
                    if (count($overrides) > 0) {
                        $fields[] = ['key' => 'price_overrides', 'value' => json_encode($overrides)];
                    }

                    $mutation = [
                        'query' => 'mutation($id: ID!, $metaobject: MetaobjectUpdateInput!) { metaobjectUpdate(id: $id, metaobject: $metaobject) { metaobject { id } userErrors { message } } }',
                        'variables' => [
                            'id' => $id,
                            'metaobject' => ['fields' => $fields],
                        ],
                    ];
                    $ch = curl_init($apiUrl);
                    curl_setopt_array($ch, [
                        CURLOPT_POST => true,
                        CURLOPT_POSTFIELDS => json_encode($mutation),
                        CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'X-Shopify-Access-Token: ' . $token],
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_TIMEOUT => 30,
                    ]);
                    $res = curl_exec($ch);
                    curl_close($ch);
                    $data = $res ? json_decode($res, true) : null;
                    $payload = $data['data']['metaobjectUpdate'] ?? null;
                    $userErrors = $payload['userErrors'] ?? [];
                    if (!empty($userErrors)) {
                        $errors[] = 'Row ' . ($i + 2) . " ({$optionName}): " . implode('; ', array_column($userErrors, 'message'));
                    } else {
                        $updated++;
                    }
                }
                $done = true;
            } else {
                $errors[] = 'CSV must have columns: option_name, price_value.';
            }
        } else {
            fclose($fh);
            $errors[] = 'Could not read CSV header.';
        }
    } else {
        $errors[] = 'Could not open uploaded file.';
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && !$apiUrl) {
    $errors[] = 'SHOPIFY_STORE and SHOPIFY_ADMIN_ACCESS_TOKEN must be set (env) for updates.';
}

$admin_current_nav = 'prices_csv';
$admin_app_title = 'Door Configurator';
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Update prices (CSV) · Door Configurator</title>
  <?php include __DIR__ . '/includes/admin_layout_styles.php'; ?>
</head>
<body>
  <?php include __DIR__ . '/includes/admin_sidebar.php'; ?>
  <main class="admin-main">
  <div class="admin-wrap">
    <h1 class="admin-page-title">Update config choice prices from CSV</h1>
    <p class="admin-page-meta">Upload a CSV to update <strong>price_value</strong> and <strong>price_overrides</strong> for config_choice entries in Shopify. Use <strong>option name</strong> (e.g. <code>premium-lever</code>) to identify each row; it must match the choice’s <strong>value</strong> or <strong>handle</strong> in Shopify.</p>

    <?php if ($done): ?>
    <div class="admin-alert admin-alert-success">
      <strong>Done.</strong> Updated <?= (int)$updated ?> row(s).<?= !empty($errors) ? ' Some rows had errors (see below).' : '' ?>
    </div>
    <?php endif; ?>
    <?php if (!empty($errors)): ?>
    <div class="admin-alert admin-alert-danger">
      <strong>Errors</strong><ul class="admin-list"><?php foreach ($errors as $e): ?> <li><?= h($e) ?></li><?php endforeach; ?></ul>
    </div>
    <?php endif; ?>

    <div class="admin-card">
      <p class="admin-card-title">CSV columns (non-technical)</p>
      <p class="admin-form-hint">First row must be headers. Required: <strong>option_name</strong>, <strong>price_value</strong>. Override columns are optional; leave blank if not used. You can have as many override sets as you need (8, 10, etc.) by adding columns with the same pattern.</p>
      <table class="admin-table" style="margin-top:0.75rem;">
        <thead>
          <tr>
            <th>Column</th>
            <th>Meaning</th>
          </tr>
        </thead>
        <tbody>
          <tr><td><code>option_name</code></td><td>Choice identifier (e.g. premium-lever, frosted, clear)</td></tr>
          <tr><td><code>price_value</code></td><td>Default price (number)</td></tr>
          <tr><td><code>price_when_key</code>, <code>price_when_value</code>, <code>price_when_type</code>, <code>price_when_value_number</code></td><td>Override 1 (e.g. material=steel → 20)</td></tr>
          <tr><td><code>price_when_key2</code>, <code>price_when_value2</code>, <code>price_when_type2</code>, <code>price_when_value_number2</code></td><td>Override 2</td></tr>
          <tr><td><code>price_when_key3</code> … <code>price_when_value_number3</code></td><td>Override 3</td></tr>
          <tr><td><code>price_when_key4</code> … <code>price_when_value_number4</code></td><td>Override 4</td></tr>
          <tr><td><code>price_when_key5</code> … <code>price_when_value_number5</code></td><td>Override 5</td></tr>
          <tr><td><code>price_when_key6</code> … <code>price_when_value_number6</code></td><td>Override 6</td></tr>
          <tr><td><code>price_when_key7</code> … <code>price_when_value_number7</code></td><td>Override 7</td></tr>
          <tr><td><code>price_when_key8</code> … <code>price_when_value_number8</code></td><td>Override 8</td></tr>
          <tr><td colspan="2"><em>Same pattern for 9, 10, … (e.g. price_when_key9, price_when_value9, …)</em></td></tr>
        </tbody>
      </table>
      <p style="margin-top:1rem;"><a href="update_config_prices.php?download=1" class="admin-btn admin-btn-secondary">Download sample CSV</a></p>
    </div>

    <div class="admin-card" style="margin-top:1.25rem;">
      <p class="admin-card-title">Upload CSV</p>
      <form method="post" enctype="multipart/form-data" class="admin-form">
        <div class="admin-form-group">
          <label for="csv">CSV file</label>
          <input type="file" id="csv" name="csv" accept=".csv,text/csv" required>
        </div>
        <button type="submit" class="admin-btn admin-btn-primary">Update prices</button>
      </form>
    </div>
  </div>
  </main>
</body>
</html>
