<?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', '2024-10');
// The single variant to use for "Custom Door" draft order line items
define('DOOR_VARIANT_ID', null);   // replace with real variant ID

define('SHOPIFY_WEBHOOK_SECRET', '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');
 define('SKIP_SHOPIFY_WEBHOOK_HMAC', '1');
 
 define('PANDADOC_API_KEY', '4058a56a412ca54d96e7bb40dda7f91557bf52de'); 
 define('PANDADOC_WEBHOOK_SHARED_KEY', '85nDqUmchc5WQ7P9UUriTd'); 
 define('PANDADOC_DOC1_TEMPLATE_UUID', 'XLSzzUKW9gropqJmHVgj42'); 
 define('PANDADOC_DOC3_TEMPLATE_UUID', 'x6H5pCM7zm84T2DE4HhPAZ'); 
 define('PANDADOC_DRIVE_PDF_URL', 'https://drive.google.com/uc?export=download&id=1cfuXhzQKJYaWcxhTk1zZx69vlp4jjcsq');

define('HUBSPOT_ORDER_PROPERTY_SHOPIFY_ORDER_ID', 'hs_external_order_id');
define('HUBSPOT_QUOTE_SEND_MODE', 'workflow');  // optional but clear
//define('HUBSPOT_QUOTE_EMAIL_ID', 215064951722); // your HubSpot transactional email 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 = strtolower((string)($opt['type'] ?? $opt['input_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' || $type === 'radio') {
                $selectedStr = $selected !== null && $selected !== '' ? (string)$selected : '';
                foreach ($choices as $c) {
                    if ((string)($c['value'] ?? '') === $selectedStr) { $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;
}

