<?php
/**
 * Create a Shopify Draft Order with a custom line item (no variant).
 *
 * Mode 1 – Inline payload (Add to cart from storefront):
 *   POST JSON: { "email", "basePrice", "options", "pricingSchema", "productTitle" }
 *   Creates draft order with one custom line item (title, calculated price, line item properties).
 *
 * Mode 2 – From saved config:
 *   POST or GET: config_id=123
 *   Creates draft order with one custom line item from stored config.
 *
 * Returns: { "success": true, "invoice_url": "...", ... } or { "success": false, "error": "..." }
 */

// Prevent PHP errors from breaking JSON response
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'])) {
    // Mode 1: Inline payload – custom line item with calculated price
    $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) {
    // Mode 2: From saved config – custom line item only (no variant_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 (shared logic)
$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, '.', '');
// Always custom line item (no variant_id) – title, calculated price, line item properties
$line_item = [
    'title'      => $productTitle,
    'quantity'  => 1,
    'price'     => $priceStr,
    'properties' => $properties,
];

$note = isset($config) ? 'Door config #' . $config['id'] . '. ' . ($config['notes_sales'] ?? '') : 'Custom door configuration';
$payload = [
    'draft_order' => [
        'email'      => $email,
        'line_items' => [$line_item],
        'note'       => $note,
    ],
];

$url = 'https://' . SHOPIFY_SHOP . '/admin/api/' . SHOPIFY_API_VERSION . '/draft_orders.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);
if ($http_code >= 200 && $http_code < 300 && !empty($data['draft_order'])) {
    $draft = $data['draft_order'];
    echo json_encode([
        'success'        => true,
        'draft_order_id' => $draft['id'],
        'invoice_url'    => $draft['invoice_url'] ?? null,
        'admin_url'      => 'https://' . SHOPIFY_SHOP . '/admin/draft_orders/' . $draft['id'],
    ]);
} else {
    http_response_code($http_code >= 400 ? $http_code : 500);
    $errMsg = (is_array($data) && isset($data['errors'])) ? (is_string($data['errors']) ? $data['errors'] : json_encode($data['errors'])) : (is_string($response) ? substr($response, 0, 500) : 'Unknown error');
    echo json_encode(['success' => false, 'error' => $errMsg]);
}
