<?php
declare(strict_types=1);

require __DIR__ . '/common.php';

const KAPVOE_SHIPPING_PRICE = 7.99;

kapvoe_require_post();
$config = kapvoe_load_config();
$data = kapvoe_json_input();

$required = [
    'product_code',
    'quantity',
    'customer_name',
    'phone',
    'email',
];

$errors = kapvoe_validate_required($data, $required);

if (!filter_var((string)($data['email'] ?? ''), FILTER_VALIDATE_EMAIL)) {
    $errors['email'] = 'Correu electrònic invàlid';
}

if (!preg_match('/^[0-9+\s]{8,20}$/', (string)($data['phone'] ?? ''))) {
    $errors['phone'] = 'Telèfon invàlid';
}

$quantity = max(1, (int)($data['quantity'] ?? 1));

$productCode = trim((string)($data['product_code'] ?? ''));
$shippingMethod = ((string)($data['shipping_method'] ?? 'pickup') === 'shipping') ? 'shipping' : 'pickup';
$shippingCost = $shippingMethod === 'shipping' ? KAPVOE_SHIPPING_PRICE : 0.0;

$address = trim((string)($data['address'] ?? ''));
$postalCode = trim((string)($data['postal_code'] ?? ''));
$city = trim((string)($data['city'] ?? ''));
$province = trim((string)($data['province'] ?? ''));

if ($shippingMethod === 'shipping') {
    if ($address === '') {
        $errors['address'] = 'Adreça obligatòria si hi ha enviament';
    }
    if (!preg_match('/^\d{5}$/', $postalCode)) {
        $errors['postal_code'] = 'Codi postal invàlid';
    }
    if ($city === '') {
        $errors['city'] = 'Ciutat obligatòria si hi ha enviament';
    }
    if ($province === '') {
        $errors['province'] = 'Província obligatòria si hi ha enviament';
    }
}

if ($errors) {
    kapvoe_json_response(['ok' => false, 'errors' => $errors], 422);
}

try {
    $catalogProduct = kapvoe_get_catalog_product_by_code($config, $productCode);

    $realPrice = (float)($catalogProduct['europe_price_number'] ?? 0);
    if ($realPrice <= 0) {
        throw new RuntimeException("El producte {$productCode} no té un preu vàlid");
    }

    $productName = trim((string)($catalogProduct['product_code'] ?? $productCode));
    $productImageUrl = trim((string)($catalogProduct['image_url'] ?? ''));

    $orderId = 'ORD-' . date('Ymd-His') . '-' . substr(bin2hex(random_bytes(3)), 0, 6);

    $unitAmountCents = (int)round($realPrice * 100);
    $subtotalCents = $unitAmountCents * $quantity;
    $shippingCostCents = (int)round($shippingCost * 100);
    $totalAmountCents = $subtotalCents + $shippingCostCents;

    $payload = [
        'order_id' => $orderId,
        'product_code' => $productCode,
        'product_name' => $productName,
        'unit_amount_cents' => $unitAmountCents,
        'quantity' => $quantity,
        'customer_name' => trim((string)$data['customer_name']),
        'phone' => trim((string)$data['phone']),
        'email' => trim((string)$data['email']),
        'analytics_session_id' => trim((string)($data['analytics_session_id'] ?? '')),
        'analytics_page_url' => trim((string)($data['analytics_page_url'] ?? '')),
        'analytics_referrer' => trim((string)($data['analytics_referrer'] ?? '')),
        'analytics_user_agent' => trim((string)($data['analytics_user_agent'] ?? '')),
        'analytics_utm_source' => trim((string)($data['analytics_utm_source'] ?? '')),
        'analytics_utm_medium' => trim((string)($data['analytics_utm_medium'] ?? '')),
        'analytics_utm_campaign' => trim((string)($data['analytics_utm_campaign'] ?? '')),
        'analytics_device_type' => trim((string)($data['analytics_device_type'] ?? '')),
        'analytics_page_type' => trim((string)($data['analytics_page_type'] ?? 'catalog')),

        'shipping_method' => $shippingMethod,
        'shipping_cost_cents' => $shippingCostCents,
        'subtotal_cents' => $subtotalCents,
        'total_amount_cents' => $totalAmountCents,

        'address' => $address,
        'postal_code' => $postalCode,
        'city' => $city,
        'province' => $province,
    ];

    $session = kapvoe_create_checkout_session($config, $payload);

    kapvoe_append_order($config, [
        'order_id' => $orderId,
        'created_at' => date('Y-m-d H:i:s'),
        'product_code' => $payload['product_code'],
        'product_name' => $payload['product_name'],
        'product_image_url' => $productImageUrl,
        'unit_price' => number_format($realPrice, 2, '.', ''),
        'quantity' => $quantity,
        'subtotal' => number_format($subtotalCents / 100, 2, '.', ''),
        'shipping_method' => $shippingMethod,
        'shipping_cost' => number_format($shippingCostCents / 100, 2, '.', ''),
        'total_amount' => number_format($totalAmountCents / 100, 2, '.', ''),
        'customer_name' => $payload['customer_name'],
        'address' => $payload['address'],
        'postal_code' => $payload['postal_code'],
        'city' => $payload['city'],
        'province' => $payload['province'],
        'phone' => $payload['phone'],
        'email' => $payload['email'],
        'analytics_session_id' => $payload['analytics_session_id'],
        'analytics_page_url' => $payload['analytics_page_url'],
        'analytics_referrer' => $payload['analytics_referrer'],
        'analytics_user_agent' => $payload['analytics_user_agent'],
        'analytics_utm_source' => $payload['analytics_utm_source'],
        'analytics_utm_medium' => $payload['analytics_utm_medium'],
        'analytics_utm_campaign' => $payload['analytics_utm_campaign'],
        'analytics_device_type' => $payload['analytics_device_type'],
        'analytics_page_type' => $payload['analytics_page_type'],
        'payment_status' => 'pending',
        'stripe_session_id' => $session['id'] ?? '',
        'payment_intent_id' => '',
        'stock_updated' => '0',
        'stock_updated_at' => '',
        'webhook_processed_at' => '',
        'customer_email_sent' => '0',
        'admin_email_sent' => '0',
        'email_notifications_sent_at' => '',
    ]);

    kapvoe_json_response([
        'ok' => true,
        'checkout_url' => $session['url'] ?? null,
        'order_id' => $orderId,
    ]);
} catch (Throwable $e) {
    kapvoe_json_response([
        'ok' => false,
        'error' => $e->getMessage(),
    ], 500);
}
