<?php
// Tampilkan semua error untuk diagnosis
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Coba muat file konfigurasi, jika gagal, skrip akan berhenti di sini dan menampilkan error
require_once 'db_config.php';

// Atur header HANYA setelah memastikan tidak ada error sebelumnya
header('Content-Type: application/json');

// Fungsi untuk mengirim respons error dan menghentikan script
function send_error_response($message, $conn = null, $code = 400) {
    if ($conn) {
        try { $conn->rollback(); } catch (Exception $e) {}
    }
    http_response_code($code);
    echo json_encode(['status' => 'error', 'message' => $message]);
    exit();
}

// Cek metode request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_error_response('Metode tidak diizinkan. Gunakan POST.');
}

// Ambil dan decode JSON
$data = json_decode(file_get_contents('php://input'), true);
if (json_last_error() !== JSON_ERROR_NONE) {
    send_error_response('Data JSON yang dikirim tidak valid.');
}

// Cek struktur dasar JSON
if (!isset($data['transaksi']) || !is_array($data['transaksi'])) {
    send_error_response("Format JSON salah. Harus ada key 'transaksi' yang berisi array.");
}

try {
    // Mulai transaksi
    $conn->begin_transaction();

    // Siapkan statement di luar loop
    $sql_jual = "INSERT INTO jual (brand, cab, tipe, komplit, mesin, nomor, tanggal, jamm, jams, shift, guest, cover, jumlah, bayar, meja, ttax, ttot, tserv, user, batal, kasir, register, deliver, cash, card, voucher, house, gift, usia, sex, kembali, rounding, pvoucher, diskrupiah) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt_jual = $conn->prepare($sql_jual);

    $sql_pesani = "INSERT INTO pesani (brand, cab, nomor, sub, payment, tglo, kode, name, kgroup, group_name, quantity, harga, price, discp, discr, netto, disc, ppn, pajak, serv, service, jumlah, meja, ket, edc, nocard, user, split, dname, note, cetak) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt_pesani = $conn->prepare($sql_pesani);

    if (!$stmt_jual || !$stmt_pesani) {
        throw new Exception("Gagal menyiapkan prepared statement: " . $conn->error);
    }
    
    // Proses setiap transaksi
    foreach ($data['transaksi'] as $transaksi) {
        // Proses tabel jual
        $j = $transaksi['jual_data'];
        $stmt_jual->bind_param("ssssssssiisiddsdddsisssddddssddidd", $j['brand'], $j['cab'], $j['tipe'], $j['komplit'], $j['mesin'], $j['nomor'], $j['tanggal'], $j['jamm'], $j['jams'], $j['shift'], $j['guest'], $j['cover'], $j['jumlah'], $j['bayar'], $j['meja'], $j['ttax'], $j['ttot'], $j['tserv'], $j['user'], $j['batal'], $j['kasir'], $j['register'], $j['deliver'], $j['cash'], $j['card'], $j['voucher'], $j['house'], $j['gift'], $j['usia'], $j['sex'], $j['kembali'], $j['rounding'], $j['pvoucher'], $j['diskrupiah']);
        $stmt_jual->execute();

        // Proses tabel pesani
        foreach ($transaksi['pesani_data'] as $p) {
            $sub = $p['sub'] ?? '0'; $payment = $p['payment'] ?? ''; $kode = $p['kode'] ?? null; $kgroup = $p['kgroup'] ?? null; $group_name = $p['group_name'] ?? null; $harga = $p['harga'] ?? 0; $price = $p['price'] ?? 0; $discp = $p['discp'] ?? 0; $discr = $p['discr'] ?? 0; $netto = $p['netto'] ?? 0; $disc = $p['disc'] ?? 0; $ppn = $p['ppn'] ?? 0; $pajak = $p['pajak'] ?? 0; $serv = $p['serv'] ?? 0; $service = $p['service'] ?? 0; $ket = $p['ket'] ?? null; $edc = $p['edc'] ?? null; $nocard = $p['nocard'] ?? null; $split = $p['split'] ?? ''; $dname = $p['dname'] ?? ''; $note = $p['note'] ?? ''; $cetak = $p['cetak'] ?? null;
            
            $stmt_pesani->bind_param("ssssssssssiddiddsdddsdsssssss", $p['brand'], $p['cab'], $p['nomor'], $sub, $payment, $p['tglo'], $kode, $p['name'], $kgroup, $group_name, $p['quantity'], $harga, $price, $discp, $discr, $netto, $disc, $ppn, $pajak, $serv, $service, $p['jumlah'], $p['meja'], $ket, $edc, $nocard, $p['user'], $split, $dname, $note, $cetak);
            $stmt_pesani->execute();
        }
    }

    // Jika semua berhasil, commit
    $conn->commit();
    $stmt_jual->close();
    $stmt_pesani->close();
    $conn->close();

    // Kirim respons sukses
    http_response_code(201);
    echo json_encode(['status' => 'success', 'message' => 'Data berhasil disinkronkan.']);

} catch (Exception $e) {
    send_error_response($e->getMessage(), $conn, 500);
}
?>