<?php
// save_configuration.php
require __DIR__ . '/config.php';

// Expect JSON from JS fetch OR normal form post; here we assume JSON:
$raw  = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!$data || empty($data['customerEmail'])) {
    http_response_code(400);
    echo json_encode(['error' => 'customerEmail is required']);
    exit;
}

$customerEmail    = $data['customerEmail'];
$baseProductId    = $data['baseProductId'] ?? null;
$options          = $data['options'] ?? [];
$notesCustomer    = $data['notesFromCustomer'] ?? '';
$basePrice        = isset($data['basePrice']) ? (float)$data['basePrice'] : 0.0;

// Partial selection is fine; we still compute a (partial) price
$computedPrice = calculateDoorPrice($basePrice, $options);

$sql = "INSERT INTO door_configurations
        (customer_email, base_product_id, options_json, notes_customer, status, base_price, computed_price)
        VALUES (:email, :product, :options, :notes_customer, :status, :base_price, :computed_price)";
$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':email'          => $customerEmail,
    ':product'        => $baseProductId,
    ':options'        => json_encode($options),
    ':notes_customer' => $notesCustomer,
    ':status'         => 'draft',
    ':base_price'     => $basePrice,
    ':computed_price' => $computedPrice,
]);

$configId = $pdo->lastInsertId();

header('Content-Type: application/json');
echo json_encode(['id' => $configId]);