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

// Ambil 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;
$fee_gojek_rate    = (float)($pdo->query("SELECT value FROM payment_settings WHERE key_name='gojek_rate'")->fetchColumn() ?? 20) / 100;
$fee_grab_rate     = (float)($pdo->query("SELECT value FROM payment_settings WHERE key_name='grab_rate'")->fetchColumn() ?? 20) / 100;
$fee_shopee_rate   = (float)($pdo->query("SELECT value FROM payment_settings WHERE key_name='shopee_rate'")->fetchColumn() ?? 20) / 100;

// Pastikan kolom ppn ada di tabel transactions
try { $pdo->exec("ALTER TABLE transactions ADD COLUMN ppn INT UNSIGNED NOT NULL DEFAULT 0 AFTER takeaway_fee"); } catch (Exception $e) {}

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Belum login']);
    exit;
}

$cart         = json_decode($_POST['cart']           ?? '[]', true);
$customer     = trim($_POST['customer']              ?? 'Umum') ?: 'Umum';
$phone        = trim($_POST['phone']                 ?? '') ?: null;
$order_type   = in_array($_POST['order_type'] ?? '', ['dinein','takeaway','catering'])
                ? $_POST['order_type'] : 'dinein';
$voucher_disc = max(0, (int)($_POST['voucher_discount'] ?? 0));
$voucher_code = strtoupper(trim($_POST['voucher_code'] ?? '')) ?: null;

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

// ── Hitung ulang di server ──────────────────────────────────────────
$subtotal      = 0;
$item_discount = 0;

foreach ($cart as &$item) {
    $price    = max(0, (int)($item['price'] ?? 0));
    $qty      = max(1, (int)($item['qty']   ?? 1));

    // Kompatibel dengan field lama (itemDiscount) maupun baru (disc)
    $disc_val = (float)($item['disc'] ?? $item['itemDiscount'] ?? 0);
    $is_pct   = (bool)($item['isPercent'] ?? false);

    $final_price = $price;
    if ($disc_val > 0) {
        $final_price = $is_pct
            ? (int)round($price * (1 - $disc_val / 100))
            : max(0, $price - (int)$disc_val);
    }

    // Normalisasi cart agar selalu pakai field 'itemDiscount' (sesuai data historis DB)
    $item['itemDiscount'] = $disc_val;
    $item['isPercent']    = $is_pct;
    unset($item['disc']); // hapus field 'disc' agar tidak double

    $subtotal      += $price * $qty;
    $item_discount += ($price - $final_price) * $qty;
}
unset($item);

$service     = (int)round(($subtotal - $item_discount - $voucher_disc) * $fee_service_rate);
$fee          = 0;
$fee_takeaway = 0;
$fee_catering = 0;
$fee_gojek    = 0;
$fee_grab     = 0;
$fee_shopee   = 0;

// Hitung fee berdasarkan item_order_type per item
foreach ($cart as $item) {
    $otype = $item['item_order_type'] ?? 'dinein';
    $item_sub = ($item['price'] ?? 0) * ($item['qty'] ?? 1);
    if ($otype === 'takeaway') $fee_takeaway += $item_sub;
    if ($otype === 'catering') $fee_catering += $item_sub;
    if ($otype === 'gojek')    $fee_gojek    += $item_sub;
    if ($otype === 'grab')     $fee_grab     += $item_sub;
    if ($otype === 'shopee')   $fee_shopee   += $item_sub;
}
$fee_takeaway = (int)round($fee_takeaway * $fee_takeaway_rate);
$fee_catering = (int)round($fee_catering * $fee_catering_rate);
$fee_gojek    = (int)round($fee_gojek    * $fee_gojek_rate);
$fee_grab     = (int)round($fee_grab     * $fee_grab_rate);
$fee_shopee   = (int)round($fee_shopee   * $fee_shopee_rate);
$fee = $fee_takeaway + $fee_catering + $fee_gojek + $fee_grab + $fee_shopee;

// Tentukan order_type transaksi (mixed kalau campur)
$unique_types = array_unique(array_map(fn($i) => $i['item_order_type'] ?? 'dinein', $cart));
$order_type = count($unique_types) === 1 ? reset($unique_types) : 'mixed';

$ppn         = (int)round(($subtotal - $item_discount - $voucher_disc + $service + $fee) * $fee_ppn_rate);
$grand_total = max(0, $subtotal - $item_discount - $voucher_disc + $service + $fee + $ppn);

$invoice = 'INV-' . date('YmdHis');

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare("
        INSERT INTO transactions
          (invoice, user_id, customer_name, customer_phone, order_type,
           cart, subtotal, discount, voucher_code, voucher_discount,
           service_charge, takeaway_fee, ppn, total, status, created_at)
        VALUES
          (?, ?, ?, ?, ?,
           ?, ?, ?, ?, ?,
           ?, ?, ?, ?, 'paid', NOW())
    ");
    $stmt->execute([
        $invoice,
        (int)$_SESSION['user_id'],
        $customer,
        $phone,
        $order_type,
        json_encode($cart, JSON_UNESCAPED_UNICODE),
        $subtotal,
        $item_discount,     // kolom 'discount' = item discount
        $voucher_code,
        $voucher_disc,      // kolom 'voucher_discount' = voucher discount
        $service,
        $fee,
        $ppn,
        $grand_total
    ]);

    $transaction_id = (int)$pdo->lastInsertId();

    // Naikkan used_count voucher
    if ($voucher_code && $voucher_disc > 0) {
        $pdo->prepare("
            UPDATE vouchers
               SET used_count = used_count + 1
             WHERE code = ?
               AND is_active = 1
               AND (quota = 0 OR used_count < quota)
        ")->execute([$voucher_code]);
    }

    $pdo->commit();

    echo json_encode([
        'success'        => true,
        'invoice'        => $invoice,
        'transaction_id' => $transaction_id,
        'grand_total'    => $grand_total,
        'message'        => 'Transaksi berhasil disimpan'
    ]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => 'DB Error: ' . $e->getMessage()]);
}