<?php
include 'index.php';
?>
<section class="pc-container">
    <div class="pc-content">
        <div class="row">
            <div class="mb-4 d-flex justify-content-between align-items-center">
                <h2 class="mb-0">Manajemen Stok Gudang</h2>
                <div>
                    <button class="btn btn-success rounded" data-bs-toggle="modal" data-bs-target="#addStokModal">
                        <i class="ti ti-plus"></i> Tambah Stok
                    </button>
                </div>
            </div>
        </div>

        <!-- Filter Gudang -->
        <div class="row mb-3">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-body">
                        <form method="GET" action="">
                            <div class="row align-items-end">
                                <div class="col-md-4">
                                    <label class="form-label">Filter Gudang</label>
                                    <select class="form-select" name="filter_gudang" onchange="this.form.submit()">
                                        <option value="">Semua Gudang</option>
                                        <?php
                                        $query_gudang = "SELECT * FROM gudang ORDER BY nama_gudang ASC";
                                        $result_gudang = mysqli_query($conn, $query_gudang);
                                        $selected_gudang = isset($_GET['filter_gudang']) ? $_GET['filter_gudang'] : '';
                                        while ($gudang = mysqli_fetch_assoc($result_gudang)) {
                                            $selected = ($selected_gudang == $gudang['id_gudang']) ? 'selected' : '';
                                            echo '<option value="'.$gudang['id_gudang'].'" '.$selected.'>'.$gudang['nama_gudang'].' - '.$gudang['lokasi'].'</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Cari Obat</label>
                                    <input type="text" class="form-control" name="search" placeholder="Nama atau kode obat..." value="<?php echo isset($_GET['search']) ? $_GET['search'] : ''; ?>">
                                </div>
                                <div class="col-md-4">
                                    <button type="submit" class="btn btn-primary"><i class="ti ti-search"></i> Filter</button>
                                    <a href="stok.php" class="btn btn-outline-secondary"><i class="ti ti-refresh"></i> Reset</a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tabel Stok -->
        <div class="row">
            <div class="col-sm-12">
                <div class="card">
                    <div class="card-header">
                        <h5>Daftar Stok per Gudang</h5>
                        <small>Kelola stok obat di setiap gudang</small>
                    </div>
                    <div class="card-body">
                        <div class="dt-responsive">
                            <table id="dom-jqry" class="table table-striped table-bordered nowrap">
                                <thead>
                                    <tr>
                                        <th>No</th>
                                        <th>Kode Obat</th>
                                        <th>Nama Obat</th>
                                        <th>Gudang</th>
                                        <th>Lokasi</th>
                                        <th>Jumlah Stok</th>
                                        <th>Satuan</th>
                                        <th>Status</th>
                                        <th class="text-center">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $where = array();
                                    if (isset($_GET['filter_gudang']) && !empty($_GET['filter_gudang'])) {
                                        $filter_gudang = mysqli_real_escape_string($conn, $_GET['filter_gudang']);
                                        $where[] = "s.id_gudang = '$filter_gudang'";
                                    }
                                    if (isset($_GET['search']) && !empty($_GET['search'])) {
                                        $search = mysqli_real_escape_string($conn, $_GET['search']);
                                        $where[] = "(o.nama_obat LIKE '%$search%' OR o.kode_obat LIKE '%$search%')";
                                    }
                                    
                                    $where_clause = count($where) > 0 ? "WHERE " . implode(" AND ", $where) : "";
                                    
                                    $query = "SELECT s.*, o.kode_obat, o.nama_obat, o.satuan, o.stok_minimum, o.stok_maksimum,
                                              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_clause
                                              ORDER BY g.nama_gudang ASC, o.nama_obat ASC";
                                    $result = mysqli_query($conn, $query);
                                    $no = 1;
                                    
                                    if (mysqli_num_rows($result) > 0) {
                                        while ($row = mysqli_fetch_assoc($result)) {
                                            $status_badge = '';
                                            if ($row['total_stok_semua_gudang'] < $row['stok_minimum']) {
                                                $status_badge = '<span class="badge bg-danger">Stok Kurang</span>';
                                            } elseif ($row['total_stok_semua_gudang'] > $row['stok_maksimum']) {
                                                $status_badge = '<span class="badge bg-info">Stok Berlebih</span>';
                                            } else {
                                                $status_badge = '<span class="badge bg-success">Stok Normal</span>';
                                            }
                                    ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td><strong><?= $row['kode_obat'] ?></strong></td>
                                        <td><?= $row['nama_obat'] ?></td>
                                        <td><span class="badge bg-primary"><?= $row['nama_gudang'] ?></span></td>
                                        <td><?= $row['lokasi'] ?></td>
                                        <td class="text-end">
                                            <strong class="text-primary"><?= $row['jumlah'] ?></strong>
                                            <small class="text-muted">(Total: <?= $row['total_stok_semua_gudang'] ?>)</small>
                                        </td>
                                        <td><?= $row['satuan'] ?></td>
                                        <td><?= $status_badge ?></td>
                                        <td class="text-center">
                                            <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#detailStokModal<?php echo $row['id_stok']; ?>" title="Detail">
                                                <i class="ti ti-eye"></i>
                                            </button>
                                            <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editStokModal<?php echo $row['id_stok']; ?>" title="Edit">
                                                <i class="ti ti-edit"></i>
                                            </button>
                                            <button class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#deleteStokModal<?php echo $row['id_stok']; ?>" title="Hapus">
                                                <i class="ti ti-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php 
                                        } 
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Modal Tambah Stok -->
<div class="modal fade" id="addStokModal" tabindex="-1" aria-labelledby="addStokModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addStokModalLabel"><i class="ti ti-plus"></i> Tambah Stok</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="tambahstok.php" method="POST">
                <div class="modal-body">
                    <input type="hidden" name="redirect_to" value="stok.php">
                    
                    <div class="mb-3">
                        <label for="id_obat" class="form-label">Pilih Obat <span class="text-danger">*</span></label>
                        <select class="form-select" id="id_obat" name="id_obat" required onchange="loadObatInfo(this.value)">
                            <option value="">-- Pilih Obat --</option>
                            <?php
                            $query_obat = "SELECT o.*, COALESCE(SUM(s.jumlah), 0) as total_stok 
                                          FROM obat o 
                                          LEFT JOIN stok s ON o.id_obat = s.id_obat 
                                          GROUP BY o.id_obat 
                                          ORDER BY o.nama_obat ASC";
                            $result_obat = mysqli_query($conn, $query_obat);
                            while ($obat = mysqli_fetch_assoc($result_obat)) {
                                echo '<option value="'.$obat['id_obat'].'" 
                                      data-kode="'.$obat['kode_obat'].'" 
                                      data-satuan="'.$obat['satuan'].'" 
                                      data-stok="'.$obat['total_stok'].'"
                                      data-min="'.$obat['stok_minimum'].'"
                                      data-max="'.$obat['stok_maksimum'].'">
                                      '.$obat['kode_obat'].' - '.$obat['nama_obat'].' (Stok: '.$obat['total_stok'].')
                                      </option>';
                            }
                            ?>
                        </select>
                    </div>
                    
                    <div id="obat-info" class="alert alert-info d-none mb-3">
                        <strong>Info Obat:</strong>
                        <ul class="mb-0 mt-2">
                            <li>Kode: <span id="info-kode">-</span></li>
                            <li>Satuan: <span id="info-satuan">-</span></li>
                            <li>Total Stok: <span id="info-stok">-</span></li>
                            <li>Stok Min/Max: <span id="info-min">-</span> / <span id="info-max">-</span></li>
                        </ul>
                    </div>
                    
                    <div class="mb-3">
                        <label for="id_gudang" class="form-label">Pilih Gudang <span class="text-danger">*</span></label>
                        <select class="form-select" id="id_gudang" name="id_gudang" required>
                            <option value="">-- Pilih Gudang --</option>
                            <?php
                            $query_gudang = "SELECT * FROM gudang ORDER BY nama_gudang ASC";
                            $result_gudang = mysqli_query($conn, $query_gudang);
                            while ($gudang = mysqli_fetch_assoc($result_gudang)) {
                                echo '<option value="'.$gudang['id_gudang'].'">'.$gudang['nama_gudang'].' - '.$gudang['lokasi'].'</option>';
                            }
                            ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="jumlah" class="form-label">Jumlah Stok <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="jumlah" name="jumlah" min="1" required>
                        <small class="text-muted">Masukkan jumlah stok yang akan ditambahkan</small>
                    </div>
                    
                    <div class="alert alert-warning mb-0">
                        <i class="ti ti-info-circle"></i> <strong>Catatan:</strong>
                        <ul class="mb-0 mt-2">
                            <li>Jika obat sudah ada di gudang, stok akan ditambahkan</li>
                            <li>Jika belum ada, akan membuat entry stok baru</li>
                        </ul>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-dark" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-success" name="tambah"><i class="ti ti-device-floppy"></i> Simpan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
$query = "SELECT s.*, o.kode_obat, o.nama_obat, o.bentuk, o.satuan, o.harga_beli, o.harga_jual, o.stok_minimum, o.stok_maksimum,
          g.nama_gudang, g.lokasi, g.keterangan,
          (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
          ORDER BY s.id_stok DESC";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
?>

<!-- Modal Detail Stok -->
<div class="modal fade" id="detailStokModal<?php echo $row['id_stok']; ?>" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="ti ti-info-circle"></i> Detail Stok</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <h6 class="text-primary mb-3"><i class="ti ti-pill"></i> Informasi Obat</h6>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <table class="table table-borderless table-sm">
                            <tr>
                                <th width="40%">Kode Obat</th>
                                <td>: <?php echo $row['kode_obat']; ?></td>
                            </tr>
                            <tr>
                                <th>Nama Obat</th>
                                <td>: <?php echo $row['nama_obat']; ?></td>
                            </tr>
                            <tr>
                                <th>Bentuk</th>
                                <td>: <?php echo $row['bentuk']; ?></td>
                            </tr>
                            <tr>
                                <th>Satuan</th>
                                <td>: <?php echo $row['satuan']; ?></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <table class="table table-borderless table-sm">
                            <tr>
                                <th width="40%">Harga Beli</th>
                                <td>: Rp <?php echo number_format($row['harga_beli'], 0, ',', '.'); ?></td>
                            </tr>
                            <tr>
                                <th>Harga Jual</th>
                                <td>: Rp <?php echo number_format($row['harga_jual'], 0, ',', '.'); ?></td>
                            </tr>
                            <tr>
                                <th>Stok Min/Max</th>
                                <td>: <?php echo $row['stok_minimum']; ?> / <?php echo $row['stok_maksimum']; ?></td>
                            </tr>
                            <tr>
                                <th>Total Semua Gudang</th>
                                <td>: <strong class="text-primary"><?php echo $row['total_stok_semua_gudang']; ?></strong></td>
                            </tr>
                        </table>
                    </div>
                </div>
                
                <hr>
                
                <h6 class="text-primary mb-3"><i class="ti ti-building-warehouse"></i> Informasi Gudang</h6>
                <div class="row">
                    <div class="col-md-12">
                        <table class="table table-borderless table-sm">
                            <tr>
                                <th width="20%">Nama Gudang</th>
                                <td>: <span class="badge bg-primary"><?php echo $row['nama_gudang']; ?></span></td>
                            </tr>
                            <tr>
                                <th>Lokasi</th>
                                <td>: <?php echo $row['lokasi']; ?></td>
                            </tr>
                            <tr>
                                <th>Keterangan</th>
                                <td>: <?php echo !empty($row['keterangan']) ? $row['keterangan'] : '-'; ?></td>
                            </tr>
                            <tr>
                                <th>Stok di Gudang Ini</th>
                                <td>: <strong class="text-success fs-5"><?php echo $row['jumlah']; ?> <?php echo $row['satuan']; ?></strong></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-dark" data-bs-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal Edit Stok -->
<div class="modal fade" id="editStokModal<?php echo $row['id_stok']; ?>" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="ti ti-edit"></i> Edit Stok</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="editstok.php" method="POST">
                <input type="hidden" name="id_stok" value="<?php echo $row['id_stok']; ?>">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <strong>Obat:</strong> <?php echo $row['nama_obat']; ?><br>
                        <strong>Gudang:</strong> <?php echo $row['nama_gudang']; ?>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Stok Saat Ini</label>
                        <input type="text" class="form-control" value="<?php echo $row['jumlah']; ?> <?php echo $row['satuan']; ?>" readonly>
                    </div>
                    
                    <div class="mb-3">
                        <label for="jumlah_baru" class="form-label">Jumlah Stok Baru <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="jumlah_baru" name="jumlah" value="<?php echo $row['jumlah']; ?>" min="0" required>
                        <small class="text-muted">Masukkan jumlah stok yang baru</small>
                    </div>
                    
                    <div class="alert alert-warning mb-0">
                        <i class="ti ti-alert-triangle"></i> Perubahan akan langsung mempengaruhi total stok obat
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-dark" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-warning" name="edit"><i class="ti ti-device-floppy"></i> Simpan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Hapus Stok -->
<div class="modal fade" id="deleteStokModal<?php echo $row['id_stok']; ?>" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="ti ti-alert-triangle"></i> Konfirmasi Hapus</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="hapusstok.php" method="POST">
                <input type="hidden" name="id_stok" value="<?php echo $row['id_stok']; ?>">
                <div class="modal-body">
                    <p>Apakah Anda yakin ingin menghapus stok ini?</p>
                    <div class="alert alert-info">
                        <strong>Obat:</strong> <?php echo $row['nama_obat']; ?><br>
                        <strong>Gudang:</strong> <?php echo $row['nama_gudang']; ?><br>
                        <strong>Jumlah:</strong> <?php echo $row['jumlah']; ?> <?php echo $row['satuan']; ?>
                    </div>
                    <div class="alert alert-danger mb-0">
                        <i class="ti ti-alert-triangle"></i> <strong>Perhatian!</strong>
                        <ul class="mb-0 mt-2">
                            <li>Stok <?php echo $row['jumlah']; ?> unit akan dihapus dari gudang ini</li>
                            <li>Total stok obat akan berkurang</li>
                            <li>Data tidak dapat dikembalikan</li>
                        </ul>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-dark" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-danger" name="hapus"><i class="ti ti-trash"></i> Ya, Hapus</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php } ?>

<script>
function loadObatInfo(id_obat) {
    if (id_obat) {
        const select = document.getElementById('id_obat');
        const option = select.options[select.selectedIndex];
        
        document.getElementById('info-kode').textContent = option.dataset.kode;
        document.getElementById('info-satuan').textContent = option.dataset.satuan;
        document.getElementById('info-stok').textContent = option.dataset.stok;
        document.getElementById('info-min').textContent = option.dataset.min;
        document.getElementById('info-max').textContent = option.dataset.max;
        
        document.getElementById('obat-info').classList.remove('d-none');
    } else {
        document.getElementById('obat-info').classList.add('d-none');
    }
}
</script>

<?php include 'footer.php'; ?>