<?php
include 'koneksi.php';

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

if (isset($_GET['id_gudang']) && !empty($_GET['id_gudang'])) {
    $id_gudang = mysqli_real_escape_string($conn, $_GET['id_gudang']);
    
    // Query untuk mendapatkan obat yang ada stoknya di gudang tertentu
    $query = "SELECT o.id_obat, o.nama_obat, o.kode_obat, o.satuan, 
              COALESCE(s.jumlah, 0) as stok_gudang
              FROM obat o
              LEFT JOIN stok s ON o.id_obat = s.id_obat AND s.id_gudang = '$id_gudang'
              WHERE s.jumlah > 0
              ORDER BY o.nama_obat ASC";
    
    $result = mysqli_query($conn, $query);
    
    if ($result) {
        $data = array();
        while ($row = mysqli_fetch_assoc($result)) {
            $data[] = $row;
        }
        
        if (count($data) > 0) {
            echo json_encode([
                'success' => true,
                'data' => $data,
                'message' => 'Data berhasil diambil'
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'data' => [],
                'message' => 'Tidak ada obat dengan stok tersedia di gudang ini'
            ]);
        }
    } else {
        echo json_encode([
            'success' => false,
            'data' => [],
            'message' => 'Error: ' . mysqli_error($conn)
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'data' => [],
        'message' => 'Parameter id_gudang tidak ditemukan'
    ]);
}

mysqli_close($conn);
?>