<?php
// get_stok_obat.php
// File untuk AJAX request mengambil data stok per gudang

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

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

// Cek apakah ada parameter id_obat
if (!isset($_GET['id_obat']) || empty($_GET['id_obat'])) {
    http_response_code(400);
    echo json_encode(['error' => 'id_obat is required']);
    exit;
}

$id_obat = mysqli_real_escape_string($conn, $_GET['id_obat']);

// Query untuk mengambil stok per gudang
$query = "SELECT 
            s.id_stok,
            s.jumlah,
            o.id_obat,
            o.kode_obat,
            o.nama_obat,
            o.satuan,
            g.id_gudang,
            g.nama_gudang,
            g.lokasi,
            (SELECT COALESCE(SUM(jumlah), 0) FROM stok WHERE id_obat = o.id_obat) as total_stok_semua_gudang
          FROM stok s
          JOIN obat o ON s.id_obat = o.id_obat
          JOIN gudang g ON s.id_gudang = g.id_gudang
          WHERE o.id_obat = '$id_obat'
          ORDER BY g.nama_gudang ASC";

$result = mysqli_query($conn, $query);

if (!$result) {
    http_response_code(500);
    echo json_encode(['error' => 'Database query failed: ' . mysqli_error($conn)]);
    exit;
}

$data = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

// Return sebagai JSON
echo json_encode($data);
?>