<?php
/**
 * Create one Shopify draft order from all configurations in the given folder(s).
 *
 * POST JSON: { "folder_ids": [1, 2], "config_ids": [10, 11] }  — config_ids optional; when set, only those configs are included.
 * Loads configs where folder_id IN (...), builds one line item per config (variant + priceOverride + customAttributes),
 * then one draftOrderCreate with all line items. Returns invoice_url.
 */
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
ini_set('display_errors', '0');

if (!defined('DRAFT_ORDER_FROM_FOLDERS_INCLUDED')) {
    header('Content-Type: application/json');
    header('Access-Control-Allow-Methods: POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
    $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
    $allowed_origins = ['https://shopify.vintagedoors.com', 'https://vintagedoors.com', 'https://rice-123.myshopify.com'];
    if (in_array($origin, $allowed_origins, true)) {
        header('Access-Control-Allow-Origin: ' . $origin);
    } else {
        header('Access-Control-Allow-Origin: *');
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// Browser test: GET ?folder_id=1&debug=1 (admin wrapper uses POST or local include).
if ($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['folder_id'])) {
    $GLOBALS['DRAFT_ORDER_FROM_FOLDERS_INPUT'] = json_encode([
        'folder_ids' => array_values(array_filter(array_map('intval', (array)$_GET['folder_id']))),
        'debug'      => !empty($_GET['debug']),
    ]);
    $_SERVER['REQUEST_METHOD'] = 'POST';
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST' && !isset($GLOBALS['DRAFT_ORDER_FROM_FOLDERS_INPUT'])) {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

$configPath = __DIR__ . '/../config.php';
if (!is_file($configPath)) {
    $configPath = __DIR__ . '/../admin/config.php';
}
if (!is_file($configPath)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Config not found']);
    exit;
}
require_once $configPath;

foreach ([
    __DIR__ . '/../admin_config_helpers.php',
    __DIR__ . '/../admin/admin_config_helpers.php',
] as $helpersPath) {
    if (is_file($helpersPath)) {
        require_once $helpersPath;
        break;
    }
}

$raw = isset($GLOBALS['DRAFT_ORDER_FROM_FOLDERS_INPUT'])
    ? $GLOBALS['DRAFT_ORDER_FROM_FOLDERS_INPUT']
    : file_get_contents('php://input');
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
$body = $raw ? json_decode($raw, true) : null;
if (!is_array($body) && $raw && (strpos($contentType, 'application/json') !== false || preg_match('/^\s*\{/', $raw))) {
    $body = json_decode($raw, true);
}
$folder_ids = isset($body['folder_ids']) && is_array($body['folder_ids']) ? array_map('intval', array_filter($body['folder_ids'])) : [];
$config_ids = isset($body['config_ids']) && is_array($body['config_ids'])
    ? array_values(array_unique(array_filter(array_map('intval', $body['config_ids']))))
    : [];
if (empty($folder_ids)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'folder_ids array is required']);
    exit;
}

$placeholders = implode(',', array_fill(0, count($folder_ids), '?'));
$stmt = $pdo->prepare("SELECT * FROM door_configurations WHERE folder_id IN ($placeholders) ORDER BY folder_id, id ASC");
$stmt->execute(array_values($folder_ids));
$configs = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($config_ids)) {
    $allowed = array_flip($config_ids);
    $configs = array_values(array_filter($configs, function ($row) use ($allowed) {
        return isset($allowed[(int) ($row['id'] ?? 0)]);
    }));
}
if (empty($configs)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'No configurations found for the selected project(s)']);
    exit;
}

$defaultVariantId = null;
if (defined('DOOR_VARIANT_ID') && DOOR_VARIANT_ID && (string)DOOR_VARIANT_ID !== '12345678901234') {
    $defaultVariantId = DOOR_VARIANT_ID;
}

function variantToGid($vid) {
    if ($vid === null || $vid === '' || (string)$vid === '12345678901234') return null;
    $s = (string)$vid;
    return (strpos($s, 'gid://') === 0) ? $s : ('gid://shopify/ProductVariant/' . $s);
}

/** Parse admin_line_item_properties_override → list of {key,value} for Shopify customAttributes. */
function appendAdminLineItemOverrideAttributes(array $customAttributes, array $options) {
    $raw = trim((string)($options['_admin_line_item_properties_override'] ?? ''));
    if ($raw === '') {
        return $customAttributes;
    }
    if ($raw[0] === '{') {
        $decoded = json_decode($raw, true);
        if (is_array($decoded)) {
            foreach ($decoded as $k => $v) {
                if ($k === '' || $v === null || $v === '') continue;
                $customAttributes[] = [
                    'key'   => (string)$k,
                    'value' => is_scalar($v) ? (string)$v : json_encode($v),
                ];
            }
        }
        return $customAttributes;
    }
    foreach (preg_split('/\r\n|\r|\n/', $raw) as $line) {
        $line = trim($line);
        if ($line === '') continue;
        if (preg_match('/^([^:]+):(.+)$/', $line, $m)) {
            $customAttributes[] = [
                'key'   => trim($m[1]),
                'value' => trim($m[2]),
            ];
        } else {
            $customAttributes[] = [
                'key'   => 'Admin override',
                'value' => $line,
            ];
        }
    }
    return $customAttributes;
}

/** Customer-facing config image only (internal images stay on configuration record). */
function buildConfigImageLineItemAttributes(array $options) {
    if (function_exists('admin_build_config_image_line_item_attributes')) {
        return admin_build_config_image_line_item_attributes($options);
    }
    $attrs = [];
    $customUrl = trim((string) ($options['_custom_image_url'] ?? ''));
    if ($customUrl !== '') {
        $attrs[] = ['key' => 'custom_image_url', 'value' => $customUrl];
    }
    return $attrs;
}

/** Remove internal-only image keys from Shopify line item properties. */
function stripInternalImageLineItemAttributes(array $customAttributes) {
    return array_values(array_filter($customAttributes, function ($attr) {
        $key = trim((string) ($attr['key'] ?? ''));
        return $key !== '' && preg_match('/^internal_image(_\d+)?$/i', $key) !== 1;
    }));
}

$lineItems = [];
$noteProductNames = [];
$lineItemsDebug = [];
$debug = !empty($body['debug']);
// TEMP TEST: custom draft line items (no Shopify variant). Set false to restore normal behavior.
$testCustomTitle = true;
foreach ($configs as $config) {
    $options = json_decode($config['options_json'], true) ?: [];
    $configId = (int)$config['id'];
    $qty = max(1, (int)($options['_quantity'] ?? 1));
    $unitPrice = (float)$config['computed_price'];
    if (function_exists('admin_get_order_total_price')) {
        $unitPrice = admin_get_order_total_price($options, $unitPrice) / $qty;
    } elseif (isset($options['_admin_order_total_override']) && is_numeric($options['_admin_order_total_override'])) {
        $unitPrice = round((float)$options['_admin_order_total_override'] / $qty, 2);
    }
    $priceStr = number_format($unitPrice, 2, '.', '');
    $productTitle = function_exists('admin_get_draft_order_line_item_title')
        ? admin_get_draft_order_line_item_title($options, $config)
        : (function_exists('admin_get_configuration_quote_title')
            ? admin_get_configuration_quote_title($options, $config)
            : (trim($options['_product_title'] ?? '') ?: ('Custom Door #' . $configId)));

    // Line item properties: quote_description only (no per-option key/value pairs).
    $customAttributes = [];
    if (function_exists('admin_build_quote_description_line_item_attribute')) {
        $quoteAttr = admin_build_quote_description_line_item_attribute($options, $config);
        if ($quoteAttr !== null) {
            $customAttributes[] = $quoteAttr;
        }
    }

    // Append admin override lines (saved as _admin_line_item_properties_override in options_json).
    $customAttributes = appendAdminLineItemOverrideAttributes($customAttributes, $options);
    // Image URLs last (customer custom image only; internal images excluded).
    $customAttributes = array_merge($customAttributes, buildConfigImageLineItemAttributes($options));
    $customAttributes = stripInternalImageLineItemAttributes($customAttributes);

    $variantRaw = function_exists('admin_resolve_config_variant_id')
        ? admin_resolve_config_variant_id($config, $options)
        : (string)($options['_variant_id'] ?? '');
    $variantIdGid = $testCustomTitle ? null : variantToGid($variantRaw !== '' ? $variantRaw : $defaultVariantId);

    if ($testCustomTitle) {
        $lineItem = [
            'title'                         => $productTitle,
            'quantity'                      => $qty,
            'originalUnitPriceWithCurrency' => ['amount' => $priceStr, 'currencyCode' => 'USD'],
            'priceOverride'                 => ['amount' => $priceStr, 'currencyCode' => 'USD'],
            'customAttributes'              => $customAttributes,
            'requiresShipping'              => true,
        ];
    } elseif ($variantIdGid) {
        $lineItem = [
            'variantId'        => $variantIdGid,
            'quantity'         => $qty,
            'priceOverride'    => ['amount' => $priceStr, 'currencyCode' => 'USD'],
            'customAttributes' => $customAttributes,
        ];
    } else {
        $lineItem = [
            'title'                         => $productTitle,
            'quantity'                      => $qty,
            'originalUnitPriceWithCurrency' => ['amount' => $priceStr, 'currencyCode' => 'USD'],
            'priceOverride'                 => ['amount' => $priceStr, 'currencyCode' => 'USD'],
            'customAttributes'              => $customAttributes,
        ];
    }
    $lineItems[] = $lineItem;
    if ($debug) {
        $lineItemsDebug[] = [
            'config_id' => $configId,
            'line_item_type' => $testCustomTitle ? 'custom' : ($variantIdGid ? 'variant' : 'custom'),
            'title' => $testCustomTitle ? ($lineItem['title'] ?? $productTitle) : null,
            'variant_id' => $variantIdGid,
            'quantity' => $qty,
            'unit_price' => $priceStr,
            'customAttributes' => $customAttributes,
            'custom_image_url' => trim((string) ($options['_custom_image_url'] ?? '')),
            'internal_images' => $options['_internal_images'] ?? null,
            'override_raw' => (string)($options['_admin_line_item_properties_override'] ?? ''),
            'order_total_override' => $options['_admin_order_total_override'] ?? null,
        ];
    }
    $noteProductNames[] = $productTitle;
}

$note = implode(', ', array_map(function ($name) {
    return '#' . $name;
}, $noteProductNames));
$email = !empty($configs[0]['customer_email']) ? $configs[0]['customer_email'] : null;

$mutation = <<<'GQL'
mutation draftOrderCreateWithPriceOverride($input: DraftOrderInput!) {
  draftOrderCreate(input: $input) {
    draftOrder {
      id
      invoiceUrl
      lineItems(first: 100) {
        edges {
          node {
            title
            quantity
            originalUnitPriceSet { shopMoney { amount } }
            priceOverride { amount }
            customAttributes { key value }
          }
        }
      }
    }
    userErrors { field message }
  }
}
GQL;

$input = [
    'note'      => $note,
    'lineItems' => $lineItems,
];
if ($email) {
    $input['email'] = $email;
}

$payload = ['query' => $mutation, 'variables' => ['input' => $input]];
$url = 'https://' . SHOPIFY_SHOP . '/admin/api/' . SHOPIFY_API_VERSION . '/graphql.json';
$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode($payload),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'X-Shopify-Access-Token: ' . SHOPIFY_ACCESS_TOKEN,
    ],
]);

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_err = curl_error($ch);
curl_close($ch);

if ($curl_err) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Shopify request failed: ' . $curl_err]);
    exit;
}

$data = json_decode($response, true);
$result = $data['data']['draftOrderCreate'] ?? null;
$userErrors = $result['userErrors'] ?? [];
$draft = $result['draftOrder'] ?? null;

if ($http_code >= 200 && $http_code < 300 && $draft && empty($userErrors)) {
    $invoice_url = $draft['invoiceUrl'] ?? null;
    if (!$invoice_url) {
        $gid = $draft['id'] ?? '';
        $numericId = preg_replace('/\D/', '', $gid);
        $invoice_url = 'https://' . SHOPIFY_SHOP . '/admin/draft_orders/' . $numericId . '/invoice';
    }
    $out = [
        'success'        => true,
        'invoice_url'    => $invoice_url,
        'draft_order_id' => $draft['id'],
        'config_ids'     => array_map(function ($row) {
            return (int) ($row['id'] ?? 0);
        }, $configs),
    ];
    if ($debug) {
        $out['line_items_debug'] = $lineItemsDebug;
        $shopifyLineItems = [];
        foreach (($draft['lineItems']['edges'] ?? []) as $edge) {
            $node = $edge['node'] ?? [];
            $shopifyLineItems[] = [
                'title' => $node['title'] ?? '',
                'customAttributes' => $node['customAttributes'] ?? [],
            ];
        }
        $out['shopify_line_items'] = $shopifyLineItems;
    }
    echo json_encode($out);
} else {
    http_response_code($http_code >= 400 ? $http_code : 500);
    $errMsg = !empty($userErrors)
        ? implode('; ', array_column($userErrors, 'message'))
        : (isset($data['errors']) ? (is_string($data['errors']) ? $data['errors'] : json_encode($data['errors'])) : substr($response, 0, 500));
    $fail = ['success' => false, 'error' => $errMsg ?: 'Unknown error'];
    if ($debug) {
        $fail['line_items_debug'] = $lineItemsDebug;
    }
    echo json_encode($fail);
}
