<?php
// ==========================================================
// KOREKSI CORS: Pastikan HANYA ada satu set header izin.
// Kita gunakan yang spesifik ke http://localhost dan menambahkan
// penanganan OPTIONS request di awal.
// ==========================================================

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

// 1. Tentukan Origin yang Diizinkan (http://localhost)
header("Access-Control-Allow-Origin: http://localhost");

// 2. Tentukan Metode dan Header yang Diizinkan
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// 3. Tangani permintaan Preflight (OPTIONS)
// Jika metode adalah OPTIONS, segera kirim header dan keluar (exit)
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

// ==========================================================
// LANJUTAN LOGIKA APLIKASI
// ==========================================================

// Konfigurasi Database
$host = 'localhost';
$user = 'root';
$pass = '';
$db   = 'pos_m';

$response = array();

try {
    // Koneksi ke database
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            throw new Exception('Data JSON tidak valid');
        }
        
        if (!isset($input['jual']) || !isset($input['pesani'])) {
            throw new Exception('Data jual dan pesani harus ada');
        }
        
        $pdo->beginTransaction();
        
        $jualData = $input['jual'];
        $nomorJual = $jualData['nomor'];

        // Cek apakah nomor jual sudah ada di database
        $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM jual WHERE nomor = :nomor");
        $checkStmt->execute([':nomor' => $nomorJual]);
        $count = $checkStmt->fetchColumn();

        if ($count > 0) {
            // --- LOGIKA BARU: JIKA DATA DITEMUKAN (UPDATE) ---
            
            // 1. Update tabel jual
            $sqlJualUpdate = "UPDATE jual SET brand=:brand, cab=:cab, tipe=:tipe, komplit=:komplit, mesin=:mesin, tanggal=:tanggal, jamm=:jamm, jams=:jams, shift=:shift, guest=:guest, cover=:cover, segmen=:segmen, member=:member, jumlah=:jumlah, bayar=:bayar, meja=:meja, ttax=:ttax, ttot=:ttot, tserv=:tserv, user=:user, batal=:batal, kasir=:kasir, register=:register, deliver=:deliver, cash=:cash, card=:card, voucher=:voucher, house=:house, gift=:gift, usia=:usia, sex=:sex, kembali=:kembali, rounding=:rounding, pvoucher=:pvoucher, diskrupiah=:diskrupiah WHERE nomor=:nomor";
            $stmtJual = $pdo->prepare($sqlJualUpdate);
            $response['message'] = 'Data berhasil diperbarui';

        } else {
            // --- LOGIKA LAMA: JIKA DATA TIDAK DITEMUKAN (INSERT) ---

            $sqlJualUpdate = "INSERT INTO jual (brand, cab, tipe, komplit, mesin, nomor, tanggal, jamm, jams, shift, guest, cover, segmen, member, jumlah, bayar, meja, ttax, ttot, tserv, user, batal, kasir, register, deliver, cash, card, voucher, house, gift, usia, sex, kembali, rounding, pvoucher, diskrupiah) 
                              VALUES (:brand, :cab, :tipe, :komplit, :mesin, :nomor, :tanggal, :jamm, :jams, :shift, :guest, :cover, :segmen, :member, :jumlah, :bayar, :meja, :ttax, :ttot, :tserv, :user, :batal, :kasir, :register, :deliver, :cash, :card, :voucher, :house, :gift, :usia, :sex, :kembali, :rounding, :pvoucher, :diskrupiah)";
            $stmtJual = $pdo->prepare($sqlJualUpdate);
            $response['message'] = 'Data berhasil disimpan';
        }

        // Eksekusi statement Jual (baik INSERT maupun UPDATE)
        $stmtJual->execute([
            ':brand' => $jualData['brand'], ':cab' => $jualData['cab'], ':tipe' => $jualData['tipe'], ':komplit' => $jualData['komplit'],
            ':mesin' => $jualData['mesin'], ':nomor' => $jualData['nomor'], ':tanggal' => $jualData['tanggal'], ':jamm' => $jualData['jamm'],
            ':jams' => $jualData['jams'], ':shift' => $jualData['shift'], ':guest' => $jualData['guest'], ':cover' => $jualData['cover'],
            ':segmen' => $jualData['segmen'], ':member' => $jualData['member'], ':jumlah' => $jualData['jumlah'], ':bayar' => $jualData['bayar'],
            ':meja' => $jualData['meja'], ':ttax' => $jualData['ttax'], ':ttot' => $jualData['ttot'], ':tserv' => $jualData['tserv'],
            ':user' => $jualData['user'], ':batal' => $jualData['batal'], ':kasir' => $jualData['kasir'], ':register' => $jualData['register'],
            ':deliver' => $jualData['deliver'], ':cash' => $jualData['cash'], ':card' => $jualData['card'], ':voucher' => $jualData['voucher'],
            ':house' => $jualData['house'], ':gift' => $jualData['gift'], ':usia' => $jualData['usia'], ':sex' => $jualData['sex'],
            ':kembali' => $jualData['kembali'], ':rounding' => $jualData['rounding'], ':pvoucher' => $jualData['pvoucher'], ':diskrupiah' => $jualData['diskrupiah']
        ]);
        
        if ($count > 0) {
            // Jika ini adalah proses UPDATE, hapus pesani lama terlebih dahulu
            $deletePesaniStmt = $pdo->prepare("DELETE FROM pesani WHERE nomor = :nomor");
            $deletePesaniStmt->execute([':nomor' => $nomorJual]);
        }

        // Insert data ke tabel pesani (logika ini sama untuk INSERT maupun UPDATE)
        $sqlPesani = "INSERT INTO pesani (brand, cab, nomor, sub, noit, payment, tglo, kode, name, kgroup, group_name, condiment, condiment_name, quantity, harga, price, image, toping, discp, discr, netto, disc, ppn, pajak, serv, service, jumlah, meja, ket, edc, nocard, user, split, dname, note, cetak) 
                     VALUES (:brand, :cab, :nomor, :sub, :noit, :payment, :tglo, :kode, :name, :kgroup, :group_name, :condiment, :condiment_name, :quantity, :harga, :price, :image, :toping, :discp, :discr, :netto, :disc, :ppn, :pajak, :serv, :service, :jumlah, :meja, :ket, :edc, :nocard, :user, :split, :dname, :note, :cetak)";
        
        $stmtPesani = $pdo->prepare($sqlPesani);
        
        $pesaniInserted = 0;
        foreach ($input['pesani'] as $pesaniData) {
            $stmtPesani->execute([
                ':brand' => $pesaniData['brand'], ':cab' => $pesaniData['cab'], ':nomor' => $pesaniData['nomor'], ':sub' => $pesaniData['sub'],
                ':noit' => $pesaniData['noit'], ':payment' => $pesaniData['payment'], ':tglo' => $pesaniData['tglo'], ':kode' => $pesaniData['kode'],
                ':name' => $pesaniData['name'], ':kgroup' => $pesaniData['kgroup'], ':group_name' => $pesaniData['group_name'], ':condiment' => $pesaniData['condiment'],
                ':condiment_name' => $pesaniData['condiment_name'], ':quantity' => $pesaniData['quantity'], ':harga' => $pesaniData['harga'], ':price' => $pesaniData['price'],
                ':image' => $pesaniData['image'], ':toping' => $pesaniData['toping'], ':discp' => $pesaniData['discp'], ':discr' => $pesaniData['discr'],
                ':netto' => $pesaniData['netto'], ':disc' => $pesaniData['disc'], ':ppn' => $pesaniData['ppn'], ':pajak' => $pesaniData['pajak'],
                ':serv' => $pesaniData['serv'], ':service' => $pesaniData['service'], ':jumlah' => $pesaniData['jumlah'], ':meja' => $pesaniData['meja'],
                ':ket' => $pesaniData['ket'], ':edc' => $pesaniData['edc'], ':nocard' => $pesaniData['nocard'], ':user' => $pesaniData['user'],
                ':split' => $pesaniData['split'], ':dname' => $pesaniData['dname'], ':note' => $pesaniData['note'], ':cetak' => $pesaniData['cetak']
            ]);
            $pesaniInserted++;
        }
        
        $pdo->commit();
        
        $response['success'] = true;
        $response['pesani_inserted'] = $pesaniInserted;
        
    } else {
        $response['success'] = false;
        $response['message'] = 'Method tidak diizinkan. Gunakan POST.';
    }
    
} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollback(); }
    $response['success'] = false;
    $response['message'] = 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollback(); }
    $response['success'] = false;
    $response['message'] = 'Error: ' . $e->getMessage();
}

echo json_encode($response);
?>