<?php
/**
 * App config: DB + Shopify API.
 *
 * SHOPIFY SETUP (do once):
 * 1. In Shopify Admin: Products → Add product "Custom Door" → one variant (e.g. "Default") → Save.
 * 2. Get variant ID: Product page → variant ID is in the URL or use Admin API GET /products.json and read first variant id.
 * 3. Custom app: Settings → Apps and sales channels → Develop apps → Your app → API credentials.
 *    Create Admin API access token with scopes: read_customers, write_draft_orders, read_products.
 * 4. Set SHOPIFY_SHOP (e.g. rice-123.myshopify.com), SHOPIFY_ACCESS_TOKEN, and DOOR_VARIANT_ID below.
 */

// Database
$pdo = new PDO('mysql:host=localhost;dbname=espirevo_vintage;charset=utf8mb4', 'espirevo_vintage', 'P8llN^?,dR3-z!}F', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

// Shopify Admin API (for draft orders)
define('SHOPIFY_SHOP', 'g1hj10-vk.myshopify.com');        // your store
define('SHOPIFY_ACCESS_TOKEN', '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');    // Admin API token
define('SHOPIFY_API_VERSION', '2026-01');

// The single variant to use for "Custom Door" draft order line items
define('DOOR_VARIANT_ID', null);   // replace with real variant ID


function calculateDoorPrice(float $basePrice, array $options): float {
    // Pricing from metaobject schema only (no static rules)
    if (!empty($options['_pricing_schema']) && is_array($options['_pricing_schema'])) {
        $schema = $options['_pricing_schema'];
        $total = $basePrice;

        foreach ($schema as $opt) {
            if (!is_array($opt) || empty($opt['id']) || empty($opt['type'])) continue;
            $id = $opt['id'];
            $type = $opt['type'];
            $choices = isset($opt['options']) && is_array($opt['options']) ? $opt['options'] : [];
            $selected = $options[$id] ?? null;

            $applyChoice = function ($choice) use (&$total, $basePrice, $options) {
                if (!is_array($choice)) return;
                $t = $choice['priceType'] ?? null;
                $v = (float)($choice['priceValue'] ?? 0);
                $norm = function ($x) { return strtolower(trim((string)$x)); };
                $oneMatch = function ($key, $val) use ($options, $norm) {
                    if (!isset($options[$key])) return false;
                    $other = $options[$key];
                    return is_array($other)
                        ? (count(array_filter($other, function ($ov) use ($val, $norm) { return $norm($ov) === $norm($val); })) > 0)
                        : $norm($other) === $norm($val);
                };
                $checkOverride = function ($o) use ($options, $norm, $oneMatch) {
                    if (!is_array($o)) return false;
                    // Compound: price_when = [{key, value}, ...] — all must match
                    $whenArr = $o['price_when'] ?? $o['priceWhen'] ?? null;
                    if (is_array($whenArr) && count($whenArr) > 0) {
                        foreach ($whenArr as $cond) {
                            $k = is_array($cond) ? ($cond['key'] ?? $cond['price_when_key'] ?? null) : null;
                            $v = is_array($cond) ? ($cond['value'] ?? $cond['price_when_value'] ?? null) : null;
                            if ($k === null || $k === '' || $v === null || !$oneMatch($k, $v)) return false;
                        }
                        return true;
                    }
                    // Single: price_when_key + price_when_value
                    $whenKey = $o['priceWhenKey'] ?? $o['price_when_key'] ?? null;
                    $whenVal = $o['priceWhenValue'] ?? $o['price_when_value'] ?? null;
                    if ($whenKey === null || $whenKey === '' || $whenVal === null || $whenVal === '' || !isset($options[$whenKey])) return false;
                    return $oneMatch($whenKey, $whenVal);
                };
                // Overrides: from array (set 1/2/3) or from priceOverridesRaw JSON (unlimited). First match wins.
                $overrides = $choice['priceOverrides'] ?? null;
                if (!is_array($overrides) && isset($choice['priceOverridesRaw'])) {
                    $raw = $choice['priceOverridesRaw'];
                    $overrides = is_string($raw) ? json_decode($raw, true) : $raw;
                }
                if (!is_array($overrides)) $overrides = [];
                if (count($overrides) > 0) {
                    foreach ($overrides as $o) {
                        if ($checkOverride($o)) {
                            $t = $o['priceWhenType'] ?? $o['price_when_type'] ?? 'fixed';
                            $v = (float)($o['priceWhenValueNumber'] ?? $o['price_when_value_number'] ?? 0);
                            break;
                        }
                    }
                } else {
                    // Single override (backward compatible)
                    $whenKey = $choice['priceWhenKey'] ?? $choice['price_when_key'] ?? null;
                    $whenVal = $choice['priceWhenValue'] ?? $choice['price_when_value'] ?? null;
                    if ($whenKey !== null && $whenKey !== '' && $whenVal !== null && $whenVal !== '' && isset($options[$whenKey])) {
                        $other = $options[$whenKey];
                        $match = is_array($other)
                            ? (count(array_filter($other, function ($ov) use ($whenVal, $norm) { return $norm($ov) === $norm($whenVal); })) > 0)
                            : $norm($other) === $norm($whenVal);
                        if ($match) {
                            $t = $choice['priceWhenType'] ?? $choice['price_when_type'] ?? 'fixed';
                            $v = (float)($choice['priceWhenValueNumber'] ?? $choice['price_when_value_number'] ?? 0);
                        }
                    }
                }
                if ($t === 'fixed') $total += $v;
                elseif ($t === 'percent') $total += ($basePrice * $v);
            };

            if ($type === 'select') {
                foreach ($choices as $c) {
                    if (($c['value'] ?? null) === $selected) { $applyChoice($c); break; }
                }
            } elseif ($type === 'checkbox') {
                $arr = is_array($selected) ? $selected : [];
                foreach ($arr as $val) {
                    foreach ($choices as $c) {
                        if (($c['value'] ?? null) === $val) { $applyChoice($c); break; }
                    }
                }
            }
        }
        return $total;
    }

    // No schema: options and pricing come from metaobjects only; return base price.
    return $basePrice;
}
