<?php
require_once 'config.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success'=>false,'error'=>'Invalid method']); exit;
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input || empty($_SESSION['cart'])) {
    echo json_encode(['success'=>false,'error'=>'Cart is empty']); exit;
}

$name = trim($input['name'] ?? '');
$phone = trim($input['phone'] ?? '');
$address = trim($input['address'] ?? '');
$payment_method = trim($input['payment_method'] ?? 'Cash on Delivery');
$order_type = $input['order_type'] ?? 'local';
$transaction_id = trim($input['transaction_id'] ?? '');

if (!$name || !$phone || !$address) {
    echo json_encode(['success'=>false,'error'=>'Missing customer details']); exit;
}

$cart = $_SESSION['cart'];
$total = 0;
$order_lines = [];
foreach ($cart as $item) {
    if ($item['type'] === 'single') {
        $sub = $item['price'] * $item['quantity'];
        $total += $sub;
        $order_lines[] = "{$item['medicine_name']} M/{$item['potency']} x {$item['quantity']} = {$sub} BDT";
    } else {
        $sub = $item['package_price'] * $item['quantity'];
        $total += $sub;
        $order_lines[] = "{$item['medicine_name']} (Combo M/{$item['potency_start']}-M/{$item['potency_end']}) x {$item['quantity']} = {$sub} BDT";
    }
}

$order_details_json = json_encode($cart);

// Insert order with transaction_id
$stmt = $pdo->prepare("INSERT INTO orders (customer_name, customer_phone, customer_address, total_amount, order_details, payment_method, order_status, transaction_id) VALUES (?,?,?,?,?,?,?,?)");
$order_status = 'pending';
$stmt->execute([$name, $phone, $address, $total, $order_details_json, $payment_method, $order_status, $transaction_id]);
$order_id = $pdo->lastInsertId();

$response = ['success' => true, 'order_id' => $order_id];

// For WhatsApp orders only, generate WhatsApp link
if ($order_type === 'whatsapp') {
    $whatsapp_number = getSetting('admin_whatsapp', $pdo);
    $msg = "🌿 *NEW ORDER #$order_id* 🌿\n\nCustomer: $name\nPhone: $phone\nAddress: $address\nPayment: $payment_method\n\nItems:\n• " . implode("\n• ", $order_lines) . "\n\n*Total: $total BDT*";
    $wa_url = "https://wa.me/" . preg_replace('/[^0-9]/','',$whatsapp_number) . "?text=" . urlencode($msg);
    $response['whatsapp_url'] = $wa_url;
}

// Clear cart
unset($_SESSION['cart']);
echo json_encode($response);
?>