<?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">Data Mutasi Stok</h2>
            </div>
        </div>

        <!-- Filter Laporan -->
        <div class="row mb-3">
            <div class="col-sm-12">
                <div class="card">
                    <div class="card-header">
                        <h5>Filter Laporan Mutasi</h5>
                    </div>
                    <div class="card-body">
                        <form method="GET" action="" id="filterForm">
                            <div class="row align-items-end">
                                <div class="col-md-2">
                                    <label for="tanggal_dari" class="form-label">Tanggal Dari</label>
                                    <input type="date" class="form-control" id="tanggal_dari" name="tanggal_dari" value="<?= isset($_GET['tanggal_dari']) ? $_GET['tanggal_dari'] : '' ?>">
                                </div>
                                <div class="col-md-2">
                                    <label for="tanggal_sampai" class="form-label">Tanggal Sampai</label>
                                    <input type="date" class="form-control" id="tanggal_sampai" name="tanggal_sampai" value="<?= isset($_GET['tanggal_sampai']) ? $_GET['tanggal_sampai'] : '' ?>">
                                </div>
                                <div class="col-md-2">
                                    <label for="tipe" class="form-label">Tipe</label>
                                    <select class="form-select" id="tipe" name="tipe">
                                        <option value="">Semua</option>
                                        <option value="MASUK" <?= (isset($_GET['tipe']) && $_GET['tipe'] == 'MASUK') ? 'selected' : '' ?>>MASUK</option>
                                        <option value="KELUAR" <?= (isset($_GET['tipe']) && $_GET['tipe'] == 'KELUAR') ? 'selected' : '' ?>>KELUAR</option>
                                        <option value="ADJUSTMENT" <?= (isset($_GET['tipe']) && $_GET['tipe'] == 'ADJUSTMENT') ? 'selected' : '' ?>>ADJUSTMENT</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label for="sumber" class="form-label">Sumber</label>
                                    <select class="form-select" id="sumber" name="sumber">
                                        <option value="">Semua</option>
                                        <option value="PEMBELIAN" <?= (isset($_GET['sumber']) && $_GET['sumber'] == 'PEMBELIAN') ? 'selected' : '' ?>>PEMBELIAN</option>
                                        <option value="PENGGUNAAN" <?= (isset($_GET['sumber']) && $_GET['sumber'] == 'PENGGUNAAN') ? 'selected' : '' ?>>PENGGUNAAN</option>
                                        <option value="STOK_OPNAME" <?= (isset($_GET['sumber']) && $_GET['sumber'] == 'STOK_OPNAME') ? 'selected' : '' ?>>STOK OPNAME</option>
                                        <option value="RETUR" <?= (isset($_GET['sumber']) && $_GET['sumber'] == 'RETUR') ? 'selected' : '' ?>>RETUR</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label for="id_gudang" class="form-label">Gudang</label>
                                    <select class="form-select" id="id_gudang" name="id_gudang">
                                        <option value="">Semua</option>
                                        <?php
                                        $gudang_query = "SELECT * FROM gudang ORDER BY nama_gudang";
                                        $gudang_result = mysqli_query($conn, $gudang_query);
                                        while ($gudang = mysqli_fetch_assoc($gudang_result)) {
                                            $selected = (isset($_GET['id_gudang']) && $_GET['id_gudang'] == $gudang['id_gudang']) ? 'selected' : '';
                                            echo "<option value='{$gudang['id_gudang']}' $selected>{$gudang['nama_gudang']}</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <button type="submit" class="btn btn-primary w-100">
                                        <i class="ti ti-filter"></i> Filter
                                    </button>
                                </div>
                            </div>
                        </form>
                        
                        <?php if (isset($_GET['tanggal_dari']) || isset($_GET['tanggal_sampai']) || isset($_GET['tipe']) || isset($_GET['sumber']) || isset($_GET['id_gudang'])) { ?>
                        <div class="row mt-3">
                            <div class="col-md-12">
                                <a href="pengeluaran.php" class="btn btn-secondary btn-sm me-2">
                                    <i class="ti ti-refresh"></i> Reset Filter
                                </a>
                                <button type="button" class="btn btn-success btn-sm" onclick="cetakLaporan()">
                                    <i class="ti ti-printer"></i> Cetak Laporan
                                </button>
                            </div>
                        </div>
                        <?php } ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Summary Cards -->
        <?php
        // Build query untuk summary
        $where_clauses_summary = ["1=1"];
        
        if (isset($_GET['tanggal_dari']) && !empty($_GET['tanggal_dari'])) {
            $tanggal_dari = $_GET['tanggal_dari'];
            $where_clauses_summary[] = "DATE(tanggal) >= '$tanggal_dari'";
        }
        
        if (isset($_GET['tanggal_sampai']) && !empty($_GET['tanggal_sampai'])) {
            $tanggal_sampai = $_GET['tanggal_sampai'];
            $where_clauses_summary[] = "DATE(tanggal) <= '$tanggal_sampai'";
        }
        
        if (isset($_GET['id_gudang']) && !empty($_GET['id_gudang'])) {
            $id_gudang = $_GET['id_gudang'];
            $where_clauses_summary[] = "id_gudang = '$id_gudang'";
        }
        
        $where_sql_summary = implode(" AND ", $where_clauses_summary);
        
        // Hitung total mutasi masuk
        $query_masuk = "SELECT COUNT(*) as total, COALESCE(SUM(jumlah), 0) as jumlah_total 
                        FROM mutasi_stok 
                        WHERE tipe = 'MASUK' AND $where_sql_summary";
        $result_masuk = mysqli_query($conn, $query_masuk);
        $data_masuk = mysqli_fetch_assoc($result_masuk);
        
        // Hitung total mutasi keluar
        $query_keluar = "SELECT COUNT(*) as total, COALESCE(SUM(jumlah), 0) as jumlah_total 
                         FROM mutasi_stok 
                         WHERE tipe = 'KELUAR' AND $where_sql_summary";
        $result_keluar = mysqli_query($conn, $query_keluar);
        $data_keluar = mysqli_fetch_assoc($result_keluar);
        
        // Hitung total adjustment
        $query_adjustment = "SELECT COUNT(*) as total 
                             FROM mutasi_stok 
                             WHERE tipe = 'ADJUSTMENT' AND $where_sql_summary";
        $result_adjustment = mysqli_query($conn, $query_adjustment);
        $data_adjustment = mysqli_fetch_assoc($result_adjustment);
        ?>
        
        <div class="row mb-3">
            <div class="col-md-4">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <h6 class="text-white">Total Mutasi Masuk</h6>
                        <h3 class="text-white"><?= $data_masuk['total'] ?> Transaksi</h3>
                        <p class="mb-0">Jumlah: <?= number_format($data_masuk['jumlah_total'], 0, ',', '.') ?> Unit</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card bg-danger text-white">
                    <div class="card-body">
                        <h6 class="text-white">Total Mutasi Keluar</h6>
                        <h3 class="text-white"><?= $data_keluar['total'] ?> Transaksi</h3>
                        <p class="mb-0">Jumlah: <?= number_format($data_keluar['jumlah_total'], 0, ',', '.') ?> Unit</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card bg-warning text-dark">
                    <div class="card-body">
                        <h6>Total Adjustment</h6>
                        <h3><?= $data_adjustment['total'] ?> Transaksi</h3>
                        <p class="mb-0">Penyesuaian Stok</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-sm-12">
                <div class="card">
                    <div class="card-header">
                        <h5>Daftar Mutasi Stok</h5>
                        <small>Monitoring seluruh pergerakan stok obat</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>Tanggal</th>
                                        <th>Nama Obat</th>
                                        <th>Gudang</th>
                                        <th>Tipe</th>
                                        <th>Sumber</th>
                                        <th>Jumlah</th>
                                        <th>Petugas</th>
                                        <th class="text-center">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    // Build query dengan filter
                                    $where_clauses = ["1=1"];
                                    
                                    if (isset($_GET['tanggal_dari']) && !empty($_GET['tanggal_dari'])) {
                                        $tanggal_dari = $_GET['tanggal_dari'];
                                        $where_clauses[] = "DATE(m.tanggal) >= '$tanggal_dari'";
                                    }
                                    
                                    if (isset($_GET['tanggal_sampai']) && !empty($_GET['tanggal_sampai'])) {
                                        $tanggal_sampai = $_GET['tanggal_sampai'];
                                        $where_clauses[] = "DATE(m.tanggal) <= '$tanggal_sampai'";
                                    }
                                    
                                    if (isset($_GET['tipe']) && !empty($_GET['tipe'])) {
                                        $tipe = $_GET['tipe'];
                                        $where_clauses[] = "m.tipe = '$tipe'";
                                    }
                                    
                                    if (isset($_GET['sumber']) && !empty($_GET['sumber'])) {
                                        $sumber = $_GET['sumber'];
                                        $where_clauses[] = "m.sumber = '$sumber'";
                                    }
                                    
                                    if (isset($_GET['id_gudang']) && !empty($_GET['id_gudang'])) {
                                        $id_gudang = $_GET['id_gudang'];
                                        $where_clauses[] = "m.id_gudang = '$id_gudang'";
                                    }
                                    
                                    $where_sql = implode(" AND ", $where_clauses);
                                    
                                    $query = "SELECT m.*, o.nama_obat, o.satuan, g.nama_gudang, u.username 
                                              FROM mutasi_stok m 
                                              LEFT JOIN obat o ON m.id_obat = o.id_obat 
                                              LEFT JOIN gudang g ON m.id_gudang = g.id_gudang 
                                              LEFT JOIN users u ON m.id_user = u.id_user 
                                              WHERE $where_sql
                                              ORDER BY m.id_mutasi DESC";
                                    $result = mysqli_query($conn, $query);
                                    $no = 1;
                                    
                                    while ($row = mysqli_fetch_assoc($result)) {
                                        // Tentukan badge class untuk tipe
                                        $tipe_class = '';
                                        switch($row['tipe']) {
                                            case 'MASUK': $tipe_class = 'bg-success'; break;
                                            case 'KELUAR': $tipe_class = 'bg-danger'; break;
                                            case 'ADJUSTMENT': $tipe_class = 'bg-warning'; break;
                                        }
                                        
                                        // Tentukan badge class untuk sumber
                                        $sumber_class = '';
                                        switch($row['sumber']) {
                                            case 'PEMBELIAN': $sumber_class = 'bg-primary'; break;
                                            case 'PENGGUNAAN': $sumber_class = 'bg-info'; break;
                                            case 'STOK_OPNAME': $sumber_class = 'bg-secondary'; break;
                                            case 'RETUR': $sumber_class = 'bg-dark'; break;
                                        }
                                        
                                        // Tentukan icon untuk jumlah
                                        $jumlah_icon = '';
                                        $jumlah_class = '';
                                        if ($row['tipe'] == 'MASUK') {
                                            $jumlah_icon = '<i class="ti ti-arrow-up"></i> ';
                                            $jumlah_class = 'text-success';
                                        } else if ($row['tipe'] == 'KELUAR') {
                                            $jumlah_icon = '<i class="ti ti-arrow-down"></i> ';
                                            $jumlah_class = 'text-danger';
                                        } else {
                                            $jumlah_icon = '<i class="ti ti-adjustments"></i> ';
                                            $jumlah_class = 'text-warning';
                                        }
                                    ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td><?= date('d/m/Y H:i', strtotime($row['tanggal'])) ?></td>
                                        <td><?= $row['nama_obat'] ?></td>
                                        <td><?= $row['nama_gudang'] ?></td>
                                        <td><span class="badge <?= $tipe_class ?>"><?= $row['tipe'] ?></span></td>
                                        <td><span class="badge <?= $sumber_class ?>"><?= str_replace('_', ' ', $row['sumber']) ?></span></td>
                                        <td class="<?= $jumlah_class ?>">
                                            <strong><?= $jumlah_icon ?><?= $row['jumlah'] ?> <?= $row['satuan'] ?></strong>
                                        </td>
                                        <td><?= $row['username'] ?></td>
                                        <td class="text-center">
                                            <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#detailMutasiModal<?php echo $row['id_mutasi']; ?>" title="Detail">
                                                <i class="ti ti-eye"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<?php
    // Query untuk modal detail
    $where_clauses_modal = ["1=1"];
    
    if (isset($_GET['tanggal_dari']) && !empty($_GET['tanggal_dari'])) {
        $where_clauses_modal[] = "DATE(m.tanggal) >= '{$_GET['tanggal_dari']}'";
    }
    
    if (isset($_GET['tanggal_sampai']) && !empty($_GET['tanggal_sampai'])) {
        $where_clauses_modal[] = "DATE(m.tanggal) <= '{$_GET['tanggal_sampai']}'";
    }
    
    if (isset($_GET['tipe']) && !empty($_GET['tipe'])) {
        $where_clauses_modal[] = "m.tipe = '{$_GET['tipe']}'";
    }
    
    if (isset($_GET['sumber']) && !empty($_GET['sumber'])) {
        $where_clauses_modal[] = "m.sumber = '{$_GET['sumber']}'";
    }
    
    if (isset($_GET['id_gudang']) && !empty($_GET['id_gudang'])) {
        $where_clauses_modal[] = "m.id_gudang = '{$_GET['id_gudang']}'";
    }
    
    $where_sql_modal = implode(" AND ", $where_clauses_modal);
    
    $query = "SELECT m.*, o.nama_obat, o.kode_obat, o.bentuk, o.satuan, o.harga_beli, o.harga_jual, 
              g.nama_gudang, g.lokasi, u.username, u.email, u.nohp
              FROM mutasi_stok m 
              LEFT JOIN obat o ON m.id_obat = o.id_obat 
              LEFT JOIN gudang g ON m.id_gudang = g.id_gudang 
              LEFT JOIN users u ON m.id_user = u.id_user 
              WHERE $where_sql_modal
              ORDER BY m.id_mutasi DESC";
    $result = mysqli_query($conn, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        // Tentukan badge class untuk tipe
        $tipe_class = '';
        switch($row['tipe']) {
            case 'MASUK': $tipe_class = 'bg-success'; break;
            case 'KELUAR': $tipe_class = 'bg-danger'; break;
            case 'ADJUSTMENT': $tipe_class = 'bg-warning'; break;
        }
        
        // Tentukan badge class untuk sumber
        $sumber_class = '';
        switch($row['sumber']) {
            case 'PEMBELIAN': $sumber_class = 'bg-primary'; break;
            case 'PENGGUNAAN': $sumber_class = 'bg-info'; break;
            case 'STOK_OPNAME': $sumber_class = 'bg-secondary'; break;
            case 'RETUR': $sumber_class = 'bg-dark'; break;
        }
?>
<!-- Modal Detail Mutasi -->
<div class="modal fade" id="detailMutasiModal<?php echo $row['id_mutasi']; ?>" tabindex="-1" aria-labelledby="detailMutasiModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="detailMutasiModalLabel">Detail Mutasi Stok #<?php echo $row['id_mutasi']; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <h6 class="fw-bold">Informasi Transaksi</h6>
                        <table class="table table-sm">
                            <tr>
                                <td width="150">ID Mutasi</td>
                                <td>: <?= $row['id_mutasi'] ?></td>
                            </tr>
                            <tr>
                                <td>Tanggal & Waktu</td>
                                <td>: <?= date('d/m/Y H:i:s', strtotime($row['tanggal'])) ?></td>
                            </tr>
                            <tr>
                                <td>Tipe</td>
                                <td>: <span class="badge <?= $tipe_class ?>"><?= $row['tipe'] ?></span></td>
                            </tr>
                            <tr>
                                <td>Sumber</td>
                                <td>: <span class="badge <?= $sumber_class ?>"><?= str_replace('_', ' ', $row['sumber']) ?></span></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6 class="fw-bold">Informasi Obat</h6>
                        <table class="table table-sm">
                            <tr>
                                <td width="150">Kode Obat</td>
                                <td>: <?= $row['kode_obat'] ?></td>
                            </tr>
                            <tr>
                                <td>Nama Obat</td>
                                <td>: <?= $row['nama_obat'] ?></td>
                            </tr>
                            <tr>
                                <td>Bentuk</td>
                                <td>: <?= $row['bentuk'] ?></td>
                            </tr>
                            <tr>
                                <td>Jumlah</td>
                                <td>: 
                                    <?php
                                    $jumlah_class_modal = '';
                                    if ($row['tipe'] == 'MASUK') {
                                        $jumlah_class_modal = 'text-success';
                                        $sign = '+';
                                    } else if ($row['tipe'] == 'KELUAR') {
                                        $jumlah_class_modal = 'text-danger';
                                        $sign = '-';
                                    } else {
                                        $jumlah_class_modal = 'text-warning';
                                        $sign = '±';
                                    }
                                    ?>
                                    <strong class="<?= $jumlah_class_modal ?>"><?= $sign ?> <?= $row['jumlah'] ?> <?= $row['satuan'] ?></strong>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

                <div class="row mb-3">
                    <div class="col-md-6">
                        <h6 class="fw-bold">Informasi Gudang</h6>
                        <table class="table table-sm">
                            <tr>
                                <td width="150">Nama Gudang</td>
                                <td>: <?= $row['nama_gudang'] ?></td>
                            </tr>
                            <tr>
                                <td>Lokasi</td>
                                <td>: <?= $row['lokasi'] ?></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6 class="fw-bold">Informasi Petugas</h6>
                        <table class="table table-sm">
                            <tr>
                                <td width="150">Username</td>
                                <td>: <?= $row['username'] ?></td>
                            </tr>
                            <tr>
                                <td>Email</td>
                                <td>: <?= $row['email'] ?></td>
                            </tr>
                            <tr>
                                <td>No. HP</td>
                                <td>: <?= $row['nohp'] ?></td>
                            </tr>
                        </table>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <h6 class="fw-bold">Keterangan</h6>
                        <div class="alert alert-light">
                            <?= $row['keterangan'] ?: '<em class="text-muted">Tidak ada keterangan</em>' ?>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <h6 class="fw-bold">Informasi Harga</h6>
                        <table class="table table-sm table-bordered">
                            <tr>
                                <td width="200"><strong>Harga Beli Satuan</strong></td>
                                <td>: Rp <?= number_format($row['harga_beli'], 0, ',', '.') ?></td>
                            </tr>
                            <tr>
                                <td><strong>Harga Jual Satuan</strong></td>
                                <td>: Rp <?= number_format($row['harga_jual'], 0, ',', '.') ?></td>
                            </tr>
                            <tr class="table-light">
                                <td><strong>Total Nilai Beli</strong></td>
                                <td>: <strong>Rp <?= number_format($row['harga_beli'] * $row['jumlah'], 0, ',', '.') ?></strong></td>
                            </tr>
                            <tr class="table-light">
                                <td><strong>Total Nilai Jual</strong></td>
                                <td>: <strong>Rp <?= number_format($row['harga_jual'] * $row['jumlah'], 0, ',', '.') ?></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>

<?php } ?>

<script>
function cetakLaporan() {
    const params = new URLSearchParams(window.location.search);
    const tanggalDari = params.get('tanggal_dari') || '';
    const tanggalSampai = params.get('tanggal_sampai') || '';
    const tipe = params.get('tipe') || '';
    const sumber = params.get('sumber') || '';
    const idGudang = params.get('id_gudang') || '';
    
    const url = `cetaklaporanpengeluaran.php?tanggal_dari=${tanggalDari}&tanggal_sampai=${tanggalSampai}&tipe=${tipe}&sumber=${sumber}&id_gudang=${idGudang}`;
    window.open(url, '_blank');
}
</script>

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