<?php
include 'indexapoteker.php';

// Check role - hanya petugas yang bisa akses
$user_role = isset($_SESSION['role']) ? $_SESSION['role'] : '';


if(isset($_GET['scan']) && !empty($_GET['scan'])) {
    $kode_obat = mysqli_real_escape_string($conn, $_GET['scan']);
    
    $query_obat = mysqli_query($conn, "SELECT o.*, COALESCE(SUM(s.jumlah), 0) as total_stok 
                                       FROM obat o 
                                       LEFT JOIN stok s ON o.id_obat = s.id_obat 
                                       WHERE o.kode_obat = '$kode_obat' 
                                       GROUP BY o.id_obat");
    $data_obat = mysqli_fetch_assoc($query_obat);
    
    if($data_obat) {
        $id_obat = $data_obat['id_obat'];
        
        $query_stok_gudang = mysqli_query($conn, "SELECT s.*, g.nama_gudang, g.lokasi, o.satuan
                                                   FROM stok s
                                                   JOIN gudang g ON s.id_gudang = g.id_gudang
                                                   JOIN obat o ON s.id_obat = o.id_obat
                                                   WHERE s.id_obat = '$id_obat'
                                                   ORDER BY g.nama_gudang ASC");
    }
}
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
<script src="https://unpkg.com/html5-qrcode"></script>
<style>
    body {
        background-color: #f8f9fa;
    }
    .card {
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
    }
    .card-header {
        background-color: #f1f8ff;
        border-bottom: 1px solid #d1e3ff;
    }
    .header-icon {
        background-color: #e8f4ff;
        width: 40px;
        height: 40px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
    }
    .scan-container {
        border: 2px dashed #ccc;
        border-radius: 10px;
        padding: 20px;
        background-color: #f9f9f9;
    }
    #reader {
        border-radius: 8px;
        overflow: hidden;
        width: 100%;
        max-width: 100%;
    }
    .info-box {
        padding: 15px;
        border-radius: 8px;
        margin-bottom: 15px;
    }
    .info-box-primary {
        background-color: #e8f4ff;
    }
    .hasil-section {
        display: none;
    }
    .info-label {
        font-size: 12px;
        color: #6c757d;
        margin-bottom: 3px;
    }
    .info-value {
        font-size: 16px;
        font-weight: 500;
    }
    .table-container {
        overflow-x: auto;
    }
</style>

<section class="pc-container">
    <div class="pc-content">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex align-items-center">
                            <div class="header-icon">
                                <i class="bi bi-upc-scan fs-4 text-primary"></i>
                            </div>
                            <div>
                                <h3 class="mb-0">Kelola Stok Obat</h3>
                                <p class="text-muted mb-0">Scan barcode untuk menambah atau mengupdate stok obat di gudang</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-lg-5">
                <div class="card">
                    <div class="card-header py-3">
                        <h5 class="mb-0"><i class="bi bi-camera me-2"></i>Scanner Barcode</h5>
                    </div>
                    <div class="card-body">
                        <div class="scan-container mb-4">
                            <div id="reader" class="mx-auto mb-3"></div>
                            <div class="text-center mt-2">
                                <small class="text-muted">Arahkan kamera ke barcode (garis-garis hitam)</small>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="hasil_scan" class="form-label"><i class="bi bi-upc me-2"></i>Hasil Scan</label>
                            <div class="input-group">
                                <input type="text" id="hasil_scan" class="form-control" placeholder="Barcode hasil scan akan tampil di sini..." readonly>
                                <button id="btnStartScanner" class="btn btn-primary">
                                    <i class="bi bi-camera-video"></i>
                                </button>
                                <button id="btnStopScanner" class="btn btn-danger" style="display:none;">
                                    <i class="bi bi-camera-video-off"></i>
                                </button>
                            </div>
                        </div>

                        <div class="mt-4">
                            <div class="d-flex align-items-center mb-3">
                                <hr class="flex-grow-1">
                                <div class="px-3 text-muted">atau</div>
                                <hr class="flex-grow-1">
                            </div>
                            
                            <form class="mt-3" method="GET" action="">
                                <div class="input-group">
                                    <input type="text" class="form-control" name="scan" placeholder="Masukkan kode obat secara manual...">
                                    <button class="btn btn-success" type="submit">
                                        <i class="bi bi-search me-1"></i> Cari
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-7 hasil-section" id="hasilSection" <?= isset($data_obat) ? 'style="display:block"' : '' ?>>
                <?php if(isset($data_obat)): ?>
                    <!-- Informasi Obat -->
                    <div class="card mb-4">
                        <div class="card-header d-flex justify-content-between align-items-center py-3">
                            <h5 class="mb-0"><i class="bi bi-info-circle me-2"></i>Informasi Obat</h5>
                            <span class="badge bg-success"><?= $data_obat['kode_obat'] ?></span>
                        </div>
                        <div class="card-body">
                            <h4 class="mb-3"><?= $data_obat['nama_obat'] ?></h4>
                            <div class="row mb-3">
                                <div class="col-sm-6 mb-2">
                                    <div class="info-label">Bentuk</div>
                                    <div class="info-value"><?= $data_obat['bentuk'] ?></div>
                                </div>
                                <div class="col-sm-6 mb-2">
                                    <div class="info-label">Satuan</div>
                                    <div class="info-value"><?= $data_obat['satuan'] ?></div>
                                </div>
                                <div class="col-sm-6 mb-2">
                                    <div class="info-label">Harga Beli</div>
                                    <div class="info-value">Rp <?= number_format($data_obat['harga_beli'], 0, ',', '.') ?></div>
                                </div>
                                <div class="col-sm-6 mb-2">
                                    <div class="info-label">Harga Jual</div>
                                    <div class="info-value">Rp <?= number_format($data_obat['harga_jual'], 0, ',', '.') ?></div>
                                </div>
                            </div>
                            <div class="info-box info-box-primary">
                                <div class="row">
                                    <div class="col-md-4 mb-2 mb-md-0">
                                        <div class="text-center">
                                            <div class="fs-5 fw-bold text-primary"><?= number_format($data_obat['total_stok'], 0, ',', '.') ?></div>
                                            <div class="small text-muted">Total Stok</div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 mb-2 mb-md-0">
                                        <div class="text-center">
                                            <div class="fs-5 fw-bold text-success"><?= $data_obat['stok_minimum'] ?></div>
                                            <div class="small text-muted">Stok Min</div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="text-center">
                                            <div class="fs-5 fw-bold text-warning"><?= $data_obat['stok_maksimum'] ?></div>
                                            <div class="small text-muted">Stok Max</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Stok Per Gudang -->
                    <div class="card mb-4">
                        <div class="card-header py-3">
                            <h5 class="mb-0"><i class="bi bi-building-warehouse me-2"></i>Stok Per Gudang</h5>
                        </div>
                        <div class="card-body">
                            <?php if(mysqli_num_rows($query_stok_gudang) > 0): ?>
                                <div class="table-container">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>No</th>
                                                <th>Gudang</th>
                                                <th>Lokasi</th>
                                                <th>Jumlah Stok</th>
                                                <th class="text-center">Status</th>
                                                <th class="text-center">Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $no = 1;
                                            while($row = mysqli_fetch_assoc($query_stok_gudang)): 
                                                $status_badge = '';
                                                if ($data_obat['total_stok'] < $data_obat['stok_minimum']) {
                                                    $status_badge = '<span class="badge bg-danger">Kurang</span>';
                                                } elseif ($data_obat['total_stok'] > $data_obat['stok_maksimum']) {
                                                    $status_badge = '<span class="badge bg-info">Berlebih</span>';
                                                } else {
                                                    $status_badge = '<span class="badge bg-success">Normal</span>';
                                                }
                                            ?>
                                            <tr>
                                                <td><?= $no++ ?></td>
                                                <td><strong><?= $row['nama_gudang'] ?></strong></td>
                                                <td><?= $row['lokasi'] ?></td>
                                                <td><strong class="text-primary"><?= number_format($row['jumlah'], 0, ',', '.') ?> <?= $row['satuan'] ?></strong></td>
                                                <td class="text-center"><?= $status_badge ?></td>
                                                <td class="text-center">
                                                    <button type="button" class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#updateStokModal<?= $row['id_stok'] ?>">
                                                        <i class="bi bi-pencil"></i> Update
                                                    </button>
                                                </td>
                                            </tr>

                                            <!-- Modal Update Stok -->
                                            <div class="modal fade" id="updateStokModal<?= $row['id_stok'] ?>" tabindex="-1">
                                                <div class="modal-dialog">
                                                    <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h5 class="modal-title">Update Stok - <?= $row['nama_gudang'] ?></h5>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                        </div>
                                                        <form action="editstokapoteker.php" method="POST">
                                                            <div class="modal-body">
                                                                <input type="hidden" name="id_stok" value="<?= $row['id_stok'] ?>">
                                                                <input type="hidden" name="id_obat" value="<?= $data_obat['id_obat'] ?>">
                                                                
                                                                <div class="mb-3">
                                                                    <label class="form-label">Obat</label>
                                                                    <input type="text" class="form-control" value="<?= $data_obat['nama_obat'] ?>" readonly>
                                                                </div>
                                                                
                                                                <div class="mb-3">
                                                                    <label class="form-label">Gudang</label>
                                                                    <input type="text" class="form-control" value="<?= $row['nama_gudang'] ?> - <?= $row['lokasi'] ?>" readonly>
                                                                </div>
                                                                
                                                                <div class="mb-3">
                                                                    <label class="form-label">Stok Saat Ini</label>
                                                                    <div class="input-group">
                                                                        <input type="text" class="form-control" value="<?= number_format($row['jumlah'], 0, ',', '.') ?>" readonly>
                                                                        <span class="input-group-text"><?= $row['satuan'] ?></span>
                                                                    </div>
                                                                </div>
                                                                
                                                                <div class="mb-3">
                                                                    <label for="stok_baru<?= $row['id_stok'] ?>" class="form-label">Stok Baru <span class="text-danger">*</span></label>
                                                                    <div class="input-group">
                                                                        <input type="number" class="form-control" id="stok_baru<?= $row['id_stok'] ?>" name="jumlah" min="0" value="<?= $row['jumlah'] ?>" required>
                                                                        <span class="input-group-text"><?= $row['satuan'] ?></span>
                                                                    </div>
                                                                    <small class="text-muted">Masukkan jumlah stok yang baru</small>
                                                                </div>

                                                                <div class="mb-3">
                                                                    <label for="keterangan<?= $row['id_stok'] ?>" class="form-label">Keterangan</label>
                                                                    <textarea class="form-control" id="keterangan<?= $row['id_stok'] ?>" name="keterangan" rows="3" placeholder="Alasan perubahan stok..."></textarea>
                                                                </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="bi bi-pencil-square"></i> Update Stok
                                                                </button>
                                                            </div>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php else: ?>
                                <div class="alert alert-warning">
                                    <i class="bi bi-info-circle me-2"></i>
                                    <strong>Perhatian!</strong> Obat belum ada stok di gudang manapun.
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Tambah Stok Baru -->
                    <div class="card">
                        <div class="card-header py-3">
                            <h5 class="mb-0"><i class="bi bi-plus-circle me-2"></i>Tambah Stok Obat</h5>
                        </div>
                        <div class="card-body">
                            <form action="tambahstokapoteker.php" method="POST">
                                <input type="hidden" name="id_obat" value="<?= $data_obat['id_obat'] ?>">
                                
                                <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>
                                    <div class="input-group">
                                        <input type="number" class="form-control" id="jumlah" name="jumlah" min="1" required placeholder="Masukkan jumlah...">
                                        <span class="input-group-text"><?= $data_obat['satuan'] ?></span>
                                    </div>
                                    <small class="text-muted">Masukkan jumlah stok yang akan ditambahkan</small>
                                </div>

                                <div class="mb-3">
                                    <label for="keterangan_tambah" class="form-label">Keterangan</label>
                                    <textarea class="form-control" id="keterangan_tambah" name="keterangan" rows="3" placeholder="Keterangan penambahan stok..."></textarea>
                                </div>
                                
                                <div class="alert alert-info">
                                    <i class="bi bi-info-circle me-2"></i>
                                    <strong>Info:</strong> Jika obat sudah ada di gudang, stok akan ditambahkan pada entry yang sudah ada
                                </div>
                                
                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-success btn-lg" name="tambah">
                                        <i class="bi bi-plus-circle me-2"></i>Tambah Stok
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                <?php else: ?>
                    <div class="card">
                        <div class="card-body text-center p-5">
                            <i class="bi bi-exclamation-triangle text-warning mb-3" style="font-size: 3rem;"></i>
                            <h4>Obat Tidak Ditemukan</h4>
                            <p class="text-muted">Data obat dengan kode "<?= htmlspecialchars($_GET['scan']) ?>" tidak ditemukan dalam database.</p>
                            <a href="scanstok.php" class="btn btn-outline-primary mt-3">
                                <i class="bi bi-arrow-left me-2"></i>Kembali
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
<script>
    $(document).ready(function() {
        const html5QrCode = new Html5Qrcode("reader");

        const formatsToSupport = [
            Html5QrcodeSupportedFormats.EAN_13,
            Html5QrcodeSupportedFormats.UPC_A,
            Html5QrcodeSupportedFormats.CODE_128,
            Html5QrcodeSupportedFormats.CODE_39
        ];

        const config = { 
            fps: 10, 
            qrbox: { width: 250, height: 50 },
            formatsToSupport: formatsToSupport
        };

        let isScannerRunning = false;

        function startScanner() {
            if (isScannerRunning) return;
            
            html5QrCode.start(
                { facingMode: "environment" }, 
                config, 
                (decodedText) => {
                    handleScanSuccess(decodedText);
                },
                (errorMessage) => {
                    console.log(`Scanner: ${errorMessage}`);
                }
            ).then(() => {
                isScannerRunning = true;
                $('#btnStartScanner').hide();
                $('#btnStopScanner').show();
            }).catch((err) => {
                console.log(`Error: ${err}`);
                alert('Gagal memulai scanner: ' + err);
            });
        }

        function stopScanner() {
            if (!isScannerRunning) return;
            
            html5QrCode.stop().then(() => {
                isScannerRunning = false;
                $('#btnStopScanner').hide();
                $('#btnStartScanner').show();
            }).catch((err) => {
                console.log("Error: ", err);
            });
        }

        function handleScanSuccess(decodedText) {
            document.getElementById('hasil_scan').value = decodedText;
            stopScanner();
            
            setTimeout(() => {
                window.location.href = 'scanapoteker.php?scan=' + encodeURIComponent(decodedText);
            }, 800);
        }

        $('#btnStartScanner').click(function() {
            startScanner();
        });

        $('#btnStopScanner').click(function() {
            stopScanner();
        });

        <?php if(isset($_GET['scan']) && !empty($_GET['scan'])): ?>
            $('#hasilSection').show();
        <?php endif; ?>

        window.addEventListener('beforeunload', function() {
            if (isScannerRunning) {
                stopScanner();
            }
        });
    });
</script>

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