<?php
include 'indexapoteker.php';
?>
<section class="pc-container">
    <div class="pc-content">
        <div class="row">
            <div class="mb-4">
                <h2 class="mb-0">Data Obat</h2>
                <small class="text-muted">Lihat informasi obat dan stok gudang</small>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12">
                <div class="card">
                    <div class="card-header">
                        <h5>Daftar Obat</h5>
                        <small>Informasi obat dan stok per gudang (Read Only)</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>Bentuk</th>
                                        <th>Satuan</th>
                                        <th>Harga Jual</th>
                                        <th>Total Stok</th>
                                        <th>Stok Min/Max</th>
                                        <th>Kadaluarsa</th>
                                        <th class="text-center">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $query = "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.id_obat DESC";
                                    $result = mysqli_query($conn, $query);
                                    $no = 1;
                                    while ($row = mysqli_fetch_assoc($result)) {
                                        // Cek status kadaluarsa
                                        $tgl_sekarang = date('Y-m-d');
                                        $tgl_kadaluarsa = $row['tgl_kadaluarsa'];
                                        $selisih_hari = (strtotime($tgl_kadaluarsa) - strtotime($tgl_sekarang)) / (60 * 60 * 24);
                                        
                                        $status_kadaluarsa = '';
                                        if ($selisih_hari < 0) {
                                            $status_kadaluarsa = '<span class="badge bg-danger">Kadaluarsa</span>';
                                        } elseif ($selisih_hari <= 90) {
                                            $status_kadaluarsa = '<span class="badge bg-warning">Segera Kadaluarsa</span>';
                                        } else {
                                            $status_kadaluarsa = '<span class="badge bg-success">Aman</span>';
                                        }
                                        
                                        // Cek status stok
                                        $status_stok = '';
                                        if ($row['total_stok'] < $row['stok_minimum']) {
                                            $status_stok = '<span class="badge bg-danger">Stok Kurang</span>';
                                        } elseif ($row['total_stok'] > $row['stok_maksimum']) {
                                            $status_stok = '<span class="badge bg-info">Stok Berlebih</span>';
                                        }
                                    ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td><?= $row['kode_obat'] ?></td>
                                        <td><?= $row['nama_obat'] ?></td>
                                        <td><?= $row['bentuk'] ?></td>
                                        <td><?= $row['satuan'] ?></td>
                                        <td>Rp <?= number_format($row['harga_jual'], 0, ',', '.') ?></td>
                                        <td>
                                            <strong><?= $row['total_stok'] ?></strong>
                                            <?= $status_stok ?>
                                        </td>
                                        <td><?= $row['stok_minimum'] ?> / <?= $row['stok_maksimum'] ?></td>
                                        <td><?= $status_kadaluarsa ?></td>
                                        <td class="text-center">
                                            <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#detailObatModal<?php echo $row['id_obat']; ?>" title="Detail">
                                                <i class="ti ti-eye"></i>
                                            </button>
                                            <button class="btn btn-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#barcodeModal<?php echo $row['id_obat']; ?>" title="Barcode">
                                                <i class="ti ti-barcode"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<?php
    $query = "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.id_obat DESC";
    $result = mysqli_query($conn, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        // Get stok per gudang
        $query_stok = "SELECT s.*, g.nama_gudang, g.lokasi
                       FROM stok s 
                       JOIN gudang g ON s.id_gudang = g.id_gudang 
                       WHERE s.id_obat = " . $row['id_obat'] . "
                       ORDER BY g.nama_gudang ASC";
        $result_stok = mysqli_query($conn, $query_stok);
?>

<!-- Modal Detail Obat -->
<div class="modal fade" id="detailObatModal<?php echo $row['id_obat']; ?>" tabindex="-1" aria-labelledby="detailObatModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="detailObatModalLabel">📋 Detail Obat - <?php echo $row['nama_obat']; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="text-primary mb-3"><i class="ti ti-pill"></i> Informasi Obat</h6>
                        <table class="table table-sm table-borderless">
                            <tr>
                                <th width="45%">Kode Obat</th>
                                <td>: <strong><?php echo $row['kode_obat']; ?></strong></td>
                            </tr>
                            <tr>
                                <th>Nama Obat</th>
                                <td>: <strong class="text-primary"><?php echo $row['nama_obat']; ?></strong></td>
                            </tr>
                            <tr>
                                <th>Bentuk</th>
                                <td>: <?php echo $row['bentuk']; ?></td>
                            </tr>
                            <tr>
                                <th>Satuan</th>
                                <td>: <?php echo $row['satuan']; ?></td>
                            </tr>
                            <tr>
                                <th>Barcode</th>
                                <td>: <?php echo $row['barcode']; ?></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6 class="text-primary mb-3"><i class="ti ti-package"></i> Informasi Stok & Harga</h6>
                        <table class="table table-sm table-borderless">
                            <tr>
                                <th width="45%">Harga Beli</th>
                                <td>: Rp <?php echo number_format($row['harga_beli'], 0, ',', '.'); ?></td>
                            </tr>
                            <tr>
                                <th>Harga Jual</th>
                                <td>: <strong class="text-success">Rp <?php echo number_format($row['harga_jual'], 0, ',', '.'); ?></strong></td>
                            </tr>
                            <tr>
                                <th>Stok Minimum</th>
                                <td>: <?php echo $row['stok_minimum']; ?> <?php echo $row['satuan']; ?></td>
                            </tr>
                            <tr>
                                <th>Stok Maksimum</th>
                                <td>: <?php echo $row['stok_maksimum']; ?> <?php echo $row['satuan']; ?></td>
                            </tr>
                            <tr>
                                <th>Total Stok</th>
                                <td>: <strong class="text-primary fs-5"><?php echo $row['total_stok']; ?> <?php echo $row['satuan']; ?></strong></td>
                            </tr>
                        </table>
                    </div>
                </div>
                
                <hr>
                
                <div class="row">
                    <div class="col-md-12">
                        <h6 class="text-primary mb-3"><i class="ti ti-calendar"></i> Informasi Tambahan</h6>
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-sm table-borderless">
                                    <tr>
                                        <th width="45%">Lead Time</th>
                                        <td>: <?php echo $row['lead_time_hari']; ?> Hari</td>
                                    </tr>
                                    <tr>
                                        <th>Tanggal Kadaluarsa</th>
                                        <td>: <?php echo date('d F Y', strtotime($row['tgl_kadaluarsa'])); ?></td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <?php
                                // Hitung sisa hari kadaluarsa
                                $tgl_sekarang = date('Y-m-d');
                                $tgl_kadaluarsa = $row['tgl_kadaluarsa'];
                                $selisih_hari = round((strtotime($tgl_kadaluarsa) - strtotime($tgl_sekarang)) / (60 * 60 * 24));
                                
                                if ($selisih_hari < 0) {
                                    echo '<div class="alert alert-danger mb-0">';
                                    echo '<i class="ti ti-alert-triangle"></i> <strong>Kadaluarsa!</strong><br>';
                                    echo 'Obat sudah melewati tanggal kadaluarsa ' . abs($selisih_hari) . ' hari yang lalu';
                                    echo '</div>';
                                } elseif ($selisih_hari <= 90) {
                                    echo '<div class="alert alert-warning mb-0">';
                                    echo '<i class="ti ti-alert-circle"></i> <strong>Segera Kadaluarsa!</strong><br>';
                                    echo 'Sisa waktu: ' . $selisih_hari . ' hari lagi';
                                    echo '</div>';
                                } else {
                                    echo '<div class="alert alert-success mb-0">';
                                    echo '<i class="ti ti-check"></i> <strong>Status: Aman</strong><br>';
                                    echo 'Sisa waktu: ' . $selisih_hari . ' hari lagi';
                                    echo '</div>';
                                }
                                ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <hr>
                
                <h6 class="text-primary mb-3"><i class="ti ti-building-warehouse"></i> Distribusi Stok per Gudang</h6>
                <div class="table-responsive">
                    <table class="table table-bordered table-sm">
                        <thead class="table-light">
                            <tr>
                                <th width="50">No</th>
                                <th>Nama Gudang</th>
                                <th>Lokasi</th>
                                <th class="text-end" width="150">Jumlah Stok</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $no_stok = 1;
                            $found_stok = false;
                            while ($stok = mysqli_fetch_assoc($result_stok)) { 
                                $found_stok = true;
                            ?>
                            <tr>
                                <td><?php echo $no_stok++; ?></td>
                                <td><i class="ti ti-building"></i> <?php echo $stok['nama_gudang']; ?></td>
                                <td><i class="ti ti-map-pin"></i> <?php echo $stok['lokasi']; ?></td>
                                <td class="text-end"><strong class="text-primary"><?php echo $stok['jumlah']; ?></strong> <?php echo $row['satuan']; ?></td>
                            </tr>
                            <?php } 
                            if (!$found_stok) {
                            ?>
                            <tr>
                                <td colspan="4" class="text-center text-muted py-3">
                                    <i class="ti ti-inbox"></i> Belum ada stok di gudang manapun
                                </td>
                            </tr>
                            <?php } ?>
                        </tbody>
                        <?php if ($found_stok) { ?>
                        <tfoot class="table-light">
                            <tr>
                                <th colspan="3" class="text-end">Total Stok Keseluruhan:</th>
                                <th class="text-end text-primary fs-6"><?php echo $row['total_stok']; ?> <?php echo $row['satuan']; ?></th>
                            </tr>
                        </tfoot>
                        <?php } ?>
                    </table>
                </div>
                
                <?php
                // Status stok
                if ($row['total_stok'] < $row['stok_minimum']) {
                    echo '<div class="alert alert-danger mt-3 mb-0">';
                    echo '<i class="ti ti-alert-triangle"></i> <strong>Peringatan!</strong> Stok di bawah minimum. Segera lakukan pemesanan ulang!';
                    echo '</div>';
                } elseif ($row['total_stok'] > $row['stok_maksimum']) {
                    echo '<div class="alert alert-info mt-3 mb-0">';
                    echo '<i class="ti ti-info-circle"></i> <strong>Informasi:</strong> Stok melebihi maksimum. Pertimbangkan untuk mengurangi pemesanan.';
                    echo '</div>';
                } else {
                    echo '<div class="alert alert-success mt-3 mb-0">';
                    echo '<i class="ti ti-check"></i> <strong>Status Stok: Normal</strong> (Dalam rentang minimum-maksimum)';
                    echo '</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 Barcode -->
<div class="modal fade" id="barcodeModal<?php echo $row['id_obat']; ?>" tabindex="-1" aria-labelledby="barcodeModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="barcodeModalLabel"><i class="ti ti-barcode"></i> Barcode - <?php echo $row['nama_obat']; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center">
                <div class="card bg-light mb-3">
                    <div class="card-body">
                        <div id="barcodeContainer<?php echo $row['id_obat']; ?>" class="mb-3">
                            <?php
                            $barcodePath = "assets/images/barcode/" . $row['barcode'];
                            if (file_exists($barcodePath) && !empty($row['barcode'])) {
                                echo '<img src="' . $barcodePath . '" alt="Barcode" class="img-fluid" style="max-width: 300px;">';
                            } else {
                                echo '<div class="alert alert-warning mb-0"><i class="ti ti-alert-circle"></i> Gambar barcode tidak ditemukan</div>';
                            }
                            ?>
                        </div>
                        <div class="border-top pt-3">
                            <h5 class="mb-2"><?php echo $row['nama_obat']; ?></h5>
                            <p class="mb-1"><strong>Kode:</strong> <?php echo $row['kode_obat']; ?></p>
                            <p class="mb-1"><strong>Harga:</strong> <span class="text-success fs-5">Rp <?php echo number_format($row['harga_jual'], 0, ',', '.'); ?></span></p>
                            <p class="mb-0"><strong>Stok Total:</strong> <span class="text-primary fs-5"><?php echo $row['total_stok']; ?> <?php echo $row['satuan']; ?></span></p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-dark" data-bs-dismiss="modal">Tutup</button>
                <button type="button" class="btn btn-primary" onclick="printBarcode(
                        '<?php echo $row['id_obat']; ?>',
                        '<?php echo $row['nama_obat']; ?>',
                        '<?php echo $row['kode_obat']; ?>',
                        '<?php echo $row['harga_jual']; ?>'
                    )">
                    <i class="ti ti-printer"></i> Cetak Barcode
                </button>
            </div>
        </div>
    </div>
</div>

<?php } ?>

<script>
function printBarcode(id_obat, nama_obat, kode_obat, harga_jual) {
    var barcodeContainer = document.getElementById('barcodeContainer' + id_obat);
    
    if (!barcodeContainer) {
        alert('Elemen barcode tidak ditemukan!');
        return;
    }
    
    var printContents = barcodeContainer.innerHTML;
    
    var printWindow = window.open('', '_blank', 'width=600,height=600');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Cetak Barcode - ${nama_obat}</title>
            <style>
                body { 
                    font-family: Arial, sans-serif; 
                    text-align: center; 
                    padding: 20px;
                    margin: 0;
                }
                .barcode-container { 
                    margin: 20px auto; 
                    max-width: 350px;
                    border: 2px dashed #ccc;
                    padding: 20px;
                    border-radius: 10px;
                }
                .barcode-image {
                    max-width: 100%;
                    height: auto;
                }
                .product-info {
                    margin: 15px 0;
                    font-size: 16px;
                    font-weight: bold;
                }
                .barcode-number {
                    font-size: 18px;
                    font-weight: bold;
                    margin: 10px 0;
                    letter-spacing: 3px;
                    color: #333;
                }
                .price {
                    font-size: 16px;
                    color: #28a745;
                    font-weight: bold;
                    margin: 10px 0;
                }
                .header {
                    font-size: 12px;
                    color: #666;
                    margin-bottom: 10px;
                }
                @media print {
                    body { margin: 0; padding: 10px; }
                    .no-print { display: none; }
                    .barcode-container {
                        border: 2px solid #000;
                    }
                }
            </style>
        </head>
        <body>
            <div class="barcode-container">
                <div class="header">APOTEK BARCODE</div>
                <div class="product-info">${nama_obat}</div>
                <div class="barcode-content">
                    ${printContents}
                </div>
                <div class="barcode-number">${kode_obat}</div>
                <div class="price">Rp ${formatRupiah(harga_jual)}</div>
            </div>
            <div class="no-print" style="margin-top: 20px;">
                <button onclick="window.print()" style="padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 14px;">
                    🖨️ Cetak
                </button>
                <button onclick="window.close()" style="padding: 10px 20px; background: #dc3545; color: white; border: none; border-radius: 5px; cursor: pointer; margin-left: 10px; font-size: 14px;">
                    ❌ Tutup
                </button>
            </div>
            
            <script>
                function formatRupiah(angka) {
                    return angka.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ".");
                }
            <\/script>
        </body>
        </html>
    `);
    
    printWindow.document.close();
}

function formatRupiah(angka) {
    return angka.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
</script>

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