<?php
/**
 * Create a Shopify draft order from the current cart (cart.js payload).
 *
 * POST JSON body: { "cart": <cart object from /cart.js> }
 * - cart.items[].variant_id, .quantity, .price (cents), .properties (object)
 * - For each item with properties._configured_price, that value is used as the line price.
 *
 * Returns: { "success": true, "invoice_url": "..." } or { "success": false, "error": "..." }
 * The frontend should redirect the customer to invoice_url to complete checkout.
 */

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

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;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    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 not found']);
    exit;
}

$raw = file_get_contents('php://input');
$body = $raw && strpos($_SERVER['CONTENT_TYPE'] ?? '', 'application/json') !== false
    ? json_decode($raw, true)
    : null;

$cart = $body['cart'] ?? null;
if (!$cart || !isset($cart['items']) || !is_array($cart['items']) || count($cart['items']) === 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Cart is empty or invalid. Send POST JSON: { "cart": <cart from /cart.js> }']);
    exit;
}

$lineItems = [];
foreach ($cart['items'] as $item) {
    $variant_id = isset($item['variant_id']) ? (int) $item['variant_id'] : 0;
    if ($variant_id <= 0) {
        continue;
    }
    $quantity = isset($item['quantity']) ? max(1, (int) $item['quantity']) : 1;
    $properties = isset($item['properties']) && is_array($item['properties']) ? $item['properties'] : [];

    // Calculated price: use _configured_price if present; otherwise variant price (cart.js price is in cents)
    $configured = isset($properties['_configured_price']) ? trim((string) $properties['_configured_price']) : null;
    if ($configured !== null && $configured !== '') {
        $priceStr = number_format((float) $configured, 2, '.', '');
    } else {
        $priceStr = isset($item['price']) ? number_format(((int) $item['price']) / 100, 2, '.', '') : '0.00';
    }

    $variantIdGid = 'gid://shopify/ProductVariant/' . $variant_id;
    $lineItem = [
        'variantId'     => $variantIdGid,
        'quantity'      => $quantity,
        'priceOverride' => [
            'amount'       => $priceStr,
            'currencyCode' => 'USD',
        ],
    ];

    $customAttributes = [];
    foreach ($properties as $name => $value) {
        if ($name === '' || $value === null) {
            continue;
        }
        $customAttributes[] = [
            'key'   => (string) $name,
            'value' => is_array($value) ? implode(', ', $value) : (string) $value,
        ];
    }
    if (!empty($customAttributes)) {
        $lineItem['customAttributes'] = $customAttributes;
    }

    $lineItems[] = $lineItem;
}

if (empty($lineItems)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'No valid line items (variant_id required)']);
    exit;
}

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

$variables = [
    'input' => [
        'note'      => 'Created from cart (draft order checkout)',
        'lineItems' => $lineItems,
    ],
];

$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)) {
    $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';
    }
    echo json_encode([
        'success'        => true,
        'invoice_url'    => $invoice_url,
        'draft_order_id' => $draft['id'],
    ]);
} 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']);
}
