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

// Rate dari DB (default: takeaway 5%, catering 10%, service 0%, ppn 0%)
$fee_takeaway_rate = (float)($pdo->query("SELECT value FROM payment_settings WHERE key_name='takeaway_rate'")->fetchColumn() ?? 5) / 100;
$fee_catering_rate = (float)($pdo->query("SELECT value FROM payment_settings WHERE key_name='catering_rate'")->fetchColumn() ?? 10) / 100;
$fee_service_rate  = (float)($pdo->query("SELECT value FROM payment_settings WHERE key_name='service_rate'")->fetchColumn() ?? 0)  / 100;
$fee_ppn_rate      = (float)($pdo->query("SELECT value FROM payment_settings WHERE key_name='ppn_rate'")->fetchColumn() ?? 0)  / 100;

// Ensure customer_orders table exists
$pdo->exec("CREATE TABLE IF NOT EXISTS customer_orders (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    invoice VARCHAR(40) NOT NULL,
    table_no INT UNSIGNED NOT NULL DEFAULT 0,
    customer_name VARCHAR(150) NOT NULL DEFAULT 'Umum',
    customer_phone VARCHAR(20) DEFAULT NULL,
    order_type ENUM('dinein','takeaway') NOT NULL DEFAULT 'dinein',
    cart LONGTEXT NOT NULL,
    subtotal INT UNSIGNED NOT NULL DEFAULT 0,
    service_charge INT UNSIGNED NOT NULL DEFAULT 0,
    takeaway_fee INT UNSIGNED NOT NULL DEFAULT 0,
    ppn INT UNSIGNED NOT NULL DEFAULT 0,
    total INT UNSIGNED NOT NULL DEFAULT 0,
    payment_method VARCHAR(80) NOT NULL DEFAULT 'tunai',
    status ENUM('new','processing','done','cancelled') NOT NULL DEFAULT 'new',
    is_notified TINYINT(1) NOT NULL DEFAULT 0,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$cart_raw     = $_POST['cart']           ?? '[]';
$customer     = trim($_POST['customer']  ?? '') ?: 'Tamu';
$phone        = trim($_POST['phone']     ?? '') ?: null;
$order_type   = in_array($_POST['order_type'] ?? '', ['dinein','takeaway']) ? $_POST['order_type'] : 'dinein';
$table_no     = max(1, (int)($_POST['table_no'] ?? 0));
$pay_method   = trim($_POST['payment_method'] ?? 'tunai') ?: 'tunai';

$cart = json_decode($cart_raw, true);
if (!is_array($cart) || empty($cart)) {
    echo json_encode(['success' => false, 'message' => 'Keranjang kosong']);
    exit;
}

// Hitung ulang di server — ambil harga dari DB agar tidak bisa dimanipulasi
$ids = array_map(fn($i) => (int)($i['id'] ?? 0), $cart);
$ids = array_filter($ids, fn($i) => $i > 0);

if (empty($ids)) {
    echo json_encode(['success' => false, 'message' => 'Produk tidak valid']);
    exit;
}

$placeholders = implode(',', array_fill(0, count($ids), '?'));
$stmt = $pdo->prepare("SELECT id, name, price FROM products WHERE id IN ($placeholders) AND is_active = 1");
$stmt->execute(array_values($ids));
$db_products = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $p) {
    $db_products[$p['id']] = $p;
}

$verified_cart = [];
$subtotal = 0;

foreach ($cart as $item) {
    $pid = (int)($item['id'] ?? 0);
    $qty = max(1, (int)($item['qty'] ?? 1));
    if (!isset($db_products[$pid])) continue;
    $p = $db_products[$pid];
    $verified_cart[] = [
        'id'    => $pid,
        'name'  => $p['name'],
        'price' => (int)$p['price'],
        'qty'   => $qty,
    ];
    $subtotal += (int)$p['price'] * $qty;
}

if (empty($verified_cart)) {
    echo json_encode(['success' => false, 'message' => 'Produk tidak ditemukan']);
    exit;
}

$service = (int)round($subtotal * $fee_service_rate);
$fee     = ($order_type === 'takeaway') ? (int)round($subtotal * $fee_takeaway_rate) : 0;
$ppn     = (int)round(($subtotal + $service + $fee) * $fee_ppn_rate);
$total   = $subtotal + $service + $fee + $ppn;

$invoice = 'SELF-' . date('YmdHis') . '-T' . $table_no;

try {
    $stmt = $pdo->prepare("
        INSERT INTO customer_orders
          (invoice, table_no, customer_name, customer_phone, order_type,
           cart, subtotal, service_charge, takeaway_fee, ppn, total, payment_method, status)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'new')
    ");
    $stmt->execute([
        $invoice, $table_no, $customer, $phone, $order_type,
        json_encode($verified_cart, JSON_UNESCAPED_UNICODE),
        $subtotal, $service, $fee, $ppn, $total, $pay_method
    ]);

    echo json_encode([
        'success' => true,
        'invoice' => $invoice,
        'total'   => $total,
        'message' => 'Pesanan berhasil dikirim!'
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'DB Error: ' . $e->getMessage()]);
}