<?php
// Mulai output buffering untuk menghindari "headers already sent" error
ob_start();

// Include koneksi database
include 'koneksi.php';

if (isset($_POST['tambah'])) {
    $id_obat = mysqli_real_escape_string($conn, $_POST['id_obat']);
    $id_gudang = mysqli_real_escape_string($conn, $_POST['id_gudang']);
    $jumlah = intval($_POST['jumlah']);
    
    // Tentukan halaman redirect
    $redirect_page = isset($_POST['redirect_to']) ? $_POST['redirect_to'] : 'stok.php';
    $redirect_scan_code = isset($_POST['scan_code']) ? $_POST['scan_code'] : '';

    // Validasi input
    if (empty($id_obat) || empty($id_gudang) || $jumlah <= 0) {
        $_SESSION['alert'] = ['type' => 'error', 'message' => 'Semua field harus diisi dengan benar!'];
        header("Location: " . $redirect_page);
        exit();
    }

    // Ambil info obat dan gudang
    $query_info = "SELECT o.nama_obat, o.kode_obat, o.satuan, g.nama_gudang 
                   FROM obat o, gudang g 
                   WHERE o.id_obat = '$id_obat' AND g.id_gudang = '$id_gudang'";
    $result_info = mysqli_query($conn, $query_info);
    
    if (!$result_info || mysqli_num_rows($result_info) == 0) {
        $_SESSION['alert'] = ['type' => 'error', 'message' => 'Data obat atau gudang tidak ditemukan!'];
        header("Location: " . $redirect_page);
        exit();
    }
    
    $info = mysqli_fetch_assoc($result_info);

    // Mulai transaksi
    mysqli_begin_transaction($conn);
    
    try {
        // Cek apakah stok untuk kombinasi id_obat dan id_gudang sudah ada
        $cek_stok = "SELECT jumlah FROM stok WHERE id_obat = '$id_obat' AND id_gudang = '$id_gudang' LIMIT 1";
        $result_cek = mysqli_query($conn, $cek_stok);
        
        if (!$result_cek) {
            throw new Exception('Query error: ' . mysqli_error($conn));
        }

        if (mysqli_num_rows($result_cek) > 0) {
            // Stok sudah ada, lakukan UPDATE (tambahkan)
            $stok_existing = mysqli_fetch_assoc($result_cek);
            $jumlah_baru = $stok_existing['jumlah'] + $jumlah;
            
            $query_update = "UPDATE stok SET jumlah = $jumlah_baru 
                            WHERE id_obat = '$id_obat' AND id_gudang = '$id_gudang'";
            
            if (!mysqli_query($conn, $query_update)) {
                throw new Exception('Gagal mengupdate stok: ' . mysqli_error($conn));
            }
            
            $action = "diperbarui";
            $detail = "Stok Lama: {$stok_existing['jumlah']} {$info['satuan']}\nDitambah: $jumlah {$info['satuan']}\nStok Baru: $jumlah_baru {$info['satuan']}";
            
        } else {
            // Stok belum ada, lakukan INSERT (buat baru)
            $query_insert = "INSERT INTO stok (id_obat, id_gudang, jumlah) 
                            VALUES ('$id_obat', '$id_gudang', $jumlah)";
            
            if (!mysqli_query($conn, $query_insert)) {
                throw new Exception('Gagal menambahkan stok baru: ' . mysqli_error($conn));
            }
            
            $action = "ditambahkan";
            $detail = "Jumlah Stok: $jumlah {$info['satuan']}";
        }
        
        // Commit transaksi
        mysqli_commit($conn);
        
        $pesan = "Stok berhasil $action!\n\nInfo:\nObat: {$info['nama_obat']}\nKode: {$info['kode_obat']}\nGudang: {$info['nama_gudang']}\n$detail";
        
        // Simpan pesan ke session
        $_SESSION['alert'] = [
            'type' => 'success',
            'message' => $pesan
        ];
        
        // Redirect dengan parameter scan jika berasal dari scan.php
        $redirect_url = $redirect_page;
        if ($redirect_page === 'scan.php' && !empty($redirect_scan_code)) {
            $redirect_url = "scan.php?scan=" . urlencode($redirect_scan_code);
        }
        
        header("Location: " . $redirect_url);
        exit();
        
    } catch (Exception $e) {
        // Rollback jika ada error
        mysqli_rollback($conn);
        
        $_SESSION['alert'] = [
            'type' => 'error',
            'message' => 'Gagal menambahkan stok: ' . $e->getMessage()
        ];
        
        header("Location: " . $redirect_page);
        exit();
    }
}

ob_end_flush();
?>