<?php
/**
 * Create a Shopify Draft Order via GraphQL (draftOrderCreate with price override).
 *
 * Same contract as create_draft_order.php:
 * Mode 1 – Inline payload (Add to cart from storefront):
 *   POST JSON: { "email", "basePrice", "options", "pricingSchema", "productTitle" }
 * Mode 2 – From saved config:
 *   POST or GET: config_id=123
 *
 * Returns: { "success": true, "invoice_url": "...", ... } or { "success": false, "error": "..." }
 */

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
ini_set('display_errors', '0');

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: https://shopify.vintagedoors.com');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

if (is_file(__DIR__ . '/config.php')) {
    require __DIR__ . '/config.php';
} elseif (is_file(__DIR__ . '/../admin/config.php')) {
    require __DIR__ . '/../admin/config.php';
} else {
    echo json_encode(['success' => false, 'error' => 'Config file not found']);
    exit;
}

$config_id = isset($_POST['config_id']) ? (int)$_POST['config_id'] : (int)($_GET['config_id'] ?? 0);
$raw = file_get_contents('php://input');
$inline = null;
if ($raw && strpos($_SERVER['CONTENT_TYPE'] ?? '', 'application/json') !== false) {
    $inline = json_decode($raw, true);
}

if ($inline && !empty($inline['email'])) {
    $email = trim($inline['email']);
    $basePrice = isset($inline['basePrice']) ? (float)$inline['basePrice'] : 0.0;
    $options = isset($inline['options']) && is_array($inline['options']) ? $inline['options'] : [];
    if (isset($inline['pricingSchema']) && is_array($inline['pricingSchema'])) {
        $options['_pricing_schema'] = $inline['pricingSchema'];
    }
    $productTitle = trim($inline['productTitle'] ?? '') ?: 'Custom door';
    $price = calculateDoorPrice($basePrice, $options);
    $properties = [];
} elseif ($config_id) {
    $stmt = $pdo->prepare("SELECT * FROM door_configurations WHERE id = ?");
    $stmt->execute([$config_id]);
    $config = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$config) {
        http_response_code(404);
        echo json_encode(['success' => false, 'error' => 'Configuration not found']);
        exit;
    }
    $options = json_decode($config['options_json'], true) ?: [];
    $email = $config['customer_email'];
    $price = (float)$config['computed_price'];
    $productTitle = trim($options['_product_title'] ?? '') ?: ('Custom Door (Config #' . $config['id'] . ')');
    $properties = [['name' => 'Config ID', 'value' => (string)$config['id']]];
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Provide config_id or JSON body with email, basePrice, options, pricingSchema, productTitle']);
    exit;
}

// Build line item properties from schema + options (same as create_draft_order.php)
$schema = $options['_pricing_schema'] ?? null;
if (is_array($schema)) {
    foreach ($schema as $opt) {
        if (!is_array($opt) || empty($opt['id']) || empty($opt['label']) || empty($opt['type'])) continue;
        $id = $opt['id'];
        $label = $opt['label'];
        $type = $opt['type'];
        $value = $options[$id] ?? null;
        if ($value === null || $value === '' || (is_array($value) && count($value) === 0)) continue;

        if ($type === 'select' && isset($opt['options']) && is_array($opt['options'])) {
            foreach ($opt['options'] as $c) {
                if (($c['value'] ?? null) === $value && !empty($c['label'])) {
                    $value = $c['label'];
                    break;
                }
            }
        }
        if (is_array($value)) $value = implode(', ', $value);
        $properties[] = ['name' => $label, 'value' => (string)$value];
    }
}

$priceStr = number_format($price, 2, '.', '');
$note = isset($config) ? 'Door config #' . $config['id'] . '. ' . ($config['notes_sales'] ?? '') : 'Custom door configuration';

// GraphQL: customAttributes = array of { key, value }
$customAttributes = [];
foreach ($properties as $prop) {
    $customAttributes[] = [
        'key'   => (string)($prop['name'] ?? ''),
        'value' => (string)($prop['value'] ?? ''),
    ];
}

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

// For custom line items (no variantId), originalUnitPriceWithCurrency sets the base price.
// Without it the line item shows $0.00. priceOverride is the price used in the draft.
/*$variables = [
    'input' => [
        'email' => $email,
        'note'  => $note,
        'lineItems' => [
            [
                'title'  => $productTitle,
                'quantity' => 1,
                'originalUnitPriceWithCurrency' => [
                    'amount'       => $priceStr,
                    'currencyCode' => 'USD',
                ],
                'priceOverride' => [
                    'amount'       => $priceStr,
                    'currencyCode' => 'USD',
                ],
                'customAttributes' => $customAttributes,
            ],
        ],
    ],
];*/


$variables = [
    'input' => [
        'email' => $email,
        'note'  => $note,
        'lineItems' => [
            [
                'variantId' => 'gid://shopify/ProductVariant/48079586427135',
                'quantity' => 1,
                'priceOverride' => [
                    'amount'       => $priceStr,
                    'currencyCode' => 'USD',
                ],
                'customAttributes' => $customAttributes,
            ],
        ],
    ],
];


$payload = ['query' => $mutation, 'variables' => $variables];
$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)) {
    $gid = $draft['id'];
    $numericId = preg_replace('/\D/', '', $gid);
    echo json_encode([
        'success'        => true,
        'draft_order_id' => $gid,
        'invoice_url'    => $draft['invoiceUrl'] ?? ('https://' . SHOPIFY_SHOP . '/admin/draft_orders/' . $numericId . '/invoice'),
        'admin_url'      => 'https://' . SHOPIFY_SHOP . '/admin/draft_orders/' . $numericId,
    ]);
} 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));
    echo json_encode(['success' => false, 'error' => $errMsg ?: 'Unknown error']);
}
