<?php
require __DIR__ . '/app/bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: checkout.php');
    exit;
}

$quantity = (int) ($_POST['quantity'] ?? 1);
$package = package_details($quantity);
if (!$package) {
    $quantity = 1;
    $package = package_details(1);
}

$post = $_POST;
$post['district'] = trim((string) ($post['district'] ?? '')) ?: trim((string) ($post['district_manual'] ?? ''));
$post['neighborhood'] = trim((string) ($post['neighborhood'] ?? '')) ?: trim((string) ($post['neighborhood_manual'] ?? ''));

$errors = [];
if (!verify_csrf($post['csrf_token'] ?? null)) {
    $errors['form'] = 'Oturum doğrulanamadı. Sayfayı yenileyip tekrar deneyin.';
}
$errors += validate_checkout($post);
if (!in_array($post['province'] ?? '', turkey_provinces(), true)) {
    $errors['province'] = 'Listeden geçerli bir il seçin.';
}

if ($errors) {
    $_SESSION['checkout_errors'] = $errors;
    $_SESSION['checkout_old'] = $post;
    header('Location: checkout.php?quantity=' . $quantity);
    exit;
}

$clean = static fn (mixed $value, int $max = 500): string => mb_substr(trim(strip_tags((string) $value)), 0, $max);
$id = create_order_id();
$accessToken = bin2hex(random_bytes(24));
$shippingPrice = (float) cfg('shipping.price', 0);

$order = [
    'id' => $id,
    'created_at' => date(DATE_ATOM),
    'updated_at' => date(DATE_ATOM),
    'status' => 'Ödeme Bekleniyor',
    'access_token_hash' => hash('sha256', $accessToken),
    'customer' => [
        'first_name' => $clean($post['first_name'], 70),
        'last_name' => $clean($post['last_name'], 70),
        'email' => mb_strtolower($clean($post['email'], 120), 'UTF-8'),
        'phone' => $clean($post['phone'], 20),
        'note' => $clean($post['note'] ?? '', 250),
    ],
    'address' => [
        'province' => $clean($post['province'], 70),
        'district' => $clean($post['district'], 80),
        'neighborhood' => $clean($post['neighborhood'], 100),
        'line' => $clean($post['address'], 500),
        'postal_code' => $clean($post['postal_code'] ?? '', 10),
    ],
    'product' => [
        'sku' => (string) cfg('product.sku'),
        'name' => (string) cfg('product.name'),
        'quantity' => $quantity,
        'package_price' => $package['price'],
    ],
    'shipping' => [
        'company' => (string) cfg('shipping.company'),
        'price' => $shippingPrice,
        'status' => (string) cfg('shipping.badge'),
    ],
    'totals' => [
        'subtotal' => $package['price'],
        'shipping' => $shippingPrice,
        'grand_total' => $package['price'] + $shippingPrice,
        'currency' => (string) cfg('product.currency', 'TRY'),
    ],
    'payment' => [
        'method' => 'Havale/EFT',
        'receipt' => null,
        'receipt_uploaded_at' => null,
    ],
    'consents' => [
        'distance_sales_and_preinfo' => true,
        'privacy_acknowledged' => true,
        'commercial_messages' => !empty($post['commercial_consent']),
        'contract_version' => (string) cfg('orders.contract_version'),
        'accepted_at' => date(DATE_ATOM),
    ],
    'security' => [
        'ip_hash' => client_ip_hash(),
        'user_agent' => mb_substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 250),
    ],
    'notifications' => [
        'new_order_telegram' => null,
        'receipt_telegram' => null,
    ],
];

if (!save_order($order)) {
    $_SESSION['checkout_errors'] = ['form' => 'Sipariş kaydedilemedi. Lütfen tekrar deneyin veya WhatsApp üzerinden iletişime geçin.'];
    $_SESSION['checkout_old'] = $post;
    header('Location: checkout.php?quantity=' . $quantity);
    exit;
}

$order['notifications']['new_order_telegram'] = notify_new_order($order);
$order['updated_at'] = date(DATE_ATOM);
save_order($order);

header('Location: payment.php?order=' . rawurlencode($id) . '&token=' . rawurlencode($accessToken));
exit;
