<?php
// kasir/api_transaksi.php — proses simpan transaksi (AJAX)
require_once '../includes/config.php';
require_once '../includes/auth.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success'=>false, 'error'=>'Tidak terautentikasi']); exit;
}

$raw  = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!$data || empty($data['items'])) {
    echo json_encode(['success'=>false, 'error'=>'Data tidak valid']); exit;
}

try {
    $pdo->beginTransaction();

    $metode   = in_array($data['metode'], ['tunai','qris']) ? $data['metode'] : 'tunai';
    $noTrx    = generateNoTransaksi($metode);
    $kasirId  = (int)$data['kasir_id'];
    $total    = (float)$data['total'];
    $bayar    = (float)$data['bayar'];
    $kembalian = (float)($bayar - $total);

    // Insert header transaksi
    $stmt = $pdo->prepare("INSERT INTO transaksi(no_transaksi,kasir_id,total,bayar,kembalian,metode) VALUES(?,?,?,?,?,?)");
    $stmt->execute([$noTrx, $kasirId, $total, $bayar, $kembalian, $metode]);
    $trxId = $pdo->lastInsertId();

    // Insert detail & kurangi stok
    $stmtDetail = $pdo->prepare("INSERT INTO detail_transaksi(transaksi_id,barang_id,nama_barang,harga_satuan,qty,subtotal) VALUES(?,?,?,?,?,?)");
    $stmtStok   = $pdo->prepare("UPDATE barang SET stok = stok - ? WHERE id = ? AND stok >= ?");

    foreach ($data['items'] as $item) {
        $barangId = (int)$item['id'];
        $qty      = (int)$item['qty'];
        $harga    = (float)$item['harga'];
        $subtotal = $harga * $qty;

        // Kurangi stok
        $stmtStok->execute([$qty, $barangId, $qty]);
        if ($stmtStok->rowCount() === 0) {
            throw new Exception("Stok barang '{$item['nama']}' tidak mencukupi.");
        }

        $stmtDetail->execute([$trxId, $barangId, $item['nama'], $harga, $qty, $subtotal]);
    }

    $pdo->commit();

    echo json_encode([
        'success'        => true,
        'no_transaksi'   => $noTrx,
        'total'          => $total,
        'bayar'          => $bayar,
        'kembalian'      => $kembalian,
        'items'          => $data['items'],
    ]);

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['success'=>false, 'error'=>$e->getMessage()]);
}