<?php
// FILE: cetaklaporanmutasi.php
include 'koneksi.php';

// Ambil parameter filter
$tanggal_dari = isset($_GET['tanggal_dari']) ? $_GET['tanggal_dari'] : '';
$tanggal_sampai = isset($_GET['tanggal_sampai']) ? $_GET['tanggal_sampai'] : '';
$tipe = isset($_GET['tipe']) ? $_GET['tipe'] : '';
$sumber = isset($_GET['sumber']) ? $_GET['sumber'] : '';
$id_gudang = isset($_GET['id_gudang']) ? $_GET['id_gudang'] : '';

// Build query dengan filter
$where_clauses = ["1=1"];

if (!empty($tanggal_dari)) {
    $where_clauses[] = "DATE(m.tanggal) >= '$tanggal_dari'";
}

if (!empty($tanggal_sampai)) {
    $where_clauses[] = "DATE(m.tanggal) <= '$tanggal_sampai'";
}

if (!empty($tipe)) {
    $where_clauses[] = "m.tipe = '$tipe'";
}

if (!empty($sumber)) {
    $where_clauses[] = "m.sumber = '$sumber'";
}

if (!empty($id_gudang)) {
    $where_clauses[] = "m.id_gudang = '$id_gudang'";
}

$where_sql = implode(" AND ", $where_clauses);

$query = "SELECT m.*, o.nama_obat, o.kode_obat, o.satuan, o.harga_beli, o.harga_jual, 
          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.tanggal ASC, m.tipe ASC";
$result = mysqli_query($conn, $query);

// Ambil nama gudang jika filter gudang aktif
$nama_gudang_filter = 'Semua Gudang';
if (!empty($id_gudang)) {
    $gudang_query = "SELECT nama_gudang FROM gudang WHERE id_gudang = '$id_gudang'";
    $gudang_result = mysqli_query($conn, $gudang_query);
    if ($gudang_data = mysqli_fetch_assoc($gudang_result)) {
        $nama_gudang_filter = $gudang_data['nama_gudang'];
    }
}

// Hitung summary berdasarkan filter
$summary_query = "SELECT 
                    SUM(CASE WHEN m.tipe = 'MASUK' THEN m.jumlah ELSE 0 END) as total_masuk,
                    SUM(CASE WHEN m.tipe = 'KELUAR' THEN m.jumlah ELSE 0 END) as total_keluar,
                    SUM(CASE WHEN m.tipe = 'MASUK' THEN (m.jumlah * o.harga_beli) ELSE 0 END) as nilai_masuk,
                    SUM(CASE WHEN m.tipe = 'KELUAR' THEN (m.jumlah * o.harga_beli) ELSE 0 END) as nilai_keluar,
                    COUNT(CASE WHEN m.tipe = 'MASUK' THEN 1 END) as count_masuk,
                    COUNT(CASE WHEN m.tipe = 'KELUAR' THEN 1 END) as count_keluar,
                    COUNT(CASE WHEN m.tipe = 'ADJUSTMENT' THEN 1 END) as count_adjustment
                  FROM mutasi_stok m
                  LEFT JOIN obat o ON m.id_obat = o.id_obat
                  WHERE $where_sql";
$summary_result = mysqli_query($conn, $summary_query);
$summary = mysqli_fetch_assoc($summary_result);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Laporan Mutasi Stok</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            font-size: 12px;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 3px solid #333;
            padding-bottom: 10px;
        }
        .header h2 {
            margin: 5px 0;
            font-size: 18px;
        }
        .header p {
            margin: 3px 0;
            font-size: 11px;
        }
        .info-laporan {
            margin-bottom: 20px;
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 5px;
        }
        .info-laporan table {
            width: 100%;
        }
        .info-laporan td {
            padding: 3px;
        }
        .summary-box {
            display: flex;
            justify-content: space-around;
            margin-bottom: 20px;
            gap: 10px;
        }
        .summary-item {
            flex: 1;
            padding: 15px;
            border-radius: 5px;
            text-align: center;
        }
        .summary-masuk {
            background-color: #e8f5e9;
            border: 2px solid #4CAF50;
        }
        .summary-keluar {
            background-color: #ffebee;
            border: 2px solid #f44336;
        }
        .summary-adjustment {
            background-color: #fff3e0;
            border: 2px solid #ff9800;
        }
        .summary-item h4 {
            margin: 5px 0;
            font-size: 14px;
        }
        .summary-item .nilai {
            font-size: 18px;
            font-weight: bold;
            margin: 5px 0;
        }
        .summary-item .keterangan {
            font-size: 10px;
            color: #666;
        }
        table.data {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        table.data th {
            background-color: #2196F3;
            color: white;
            padding: 8px;
            text-align: left;
            font-size: 11px;
            border: 1px solid #ddd;
        }
        table.data td {
            padding: 6px;
            border: 1px solid #ddd;
            font-size: 11px;
        }
        table.data tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .badge {
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 10px;
            font-weight: bold;
            display: inline-block;
        }
        .badge-masuk {
            background-color: #4CAF50;
            color: white;
        }
        .badge-keluar {
            background-color: #f44336;
            color: white;
        }
        .badge-adjustment {
            background-color: #ff9800;
            color: white;
        }
        .badge-pembelian {
            background-color: #2196F3;
            color: white;
        }
        .badge-penggunaan {
            background-color: #00BCD4;
            color: white;
        }
        .badge-stok-opname {
            background-color: #9E9E9E;
            color: white;
        }
        .badge-retur {
            background-color: #607D8B;
            color: white;
        }
        .total-row {
            background-color: #e3f2fd !important;
            font-weight: bold;
        }
        .text-right {
            text-align: right;
        }
        .text-center {
            text-align: center;
        }
        .text-success {
            color: #4CAF50;
            font-weight: bold;
        }
        .text-danger {
            color: #f44336;
            font-weight: bold;
        }
        .text-warning {
            color: #ff9800;
            font-weight: bold;
        }
        .footer {
            margin-top: 30px;
            display: flex;
            justify-content: space-between;
        }
        .ttd {
            text-align: center;
            width: 200px;
        }
        .ttd-line {
            margin-top: 60px;
            border-top: 1px solid #000;
            padding-top: 5px;
        }
        @media print {
            .no-print {
                display: none;
            }
            body {
                margin: 0;
            }
        }
        .btn-print {
            background-color: #2196F3;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            margin-bottom: 20px;
        }
        .btn-print:hover {
            background-color: #1976D2;
        }
        .btn-close {
            background-color: #f44336;
        }
        .btn-close:hover {
            background-color: #d32f2f;
        }
    </style>
</head>
<body>
    <div class="no-print">
        <button class="btn-print" onclick="window.print()">🖨️ Cetak Laporan</button>
        <button class="btn-print btn-close" onclick="window.close()">❌ Tutup</button>
    </div>

    <div class="header">
        <h2>PUSKESMAS</h2>
        <p>Jl. Alamat Puskesmas No. 123, Kota</p>
        <p>Telp: (021) 12345678 | Email: puskesmas@email.com</p>
        <h3 style="margin-top: 15px;">LAPORAN MUTASI STOK</h3>
    </div>

    <div class="info-laporan">
        <table>
            <tr>
                <td width="150"><strong>Periode</strong></td>
                <td>: 
                    <?php 
                    if (!empty($tanggal_dari) && !empty($tanggal_sampai)) {
                        echo date('d/m/Y', strtotime($tanggal_dari)) . ' s/d ' . date('d/m/Y', strtotime($tanggal_sampai));
                    } elseif (!empty($tanggal_dari)) {
                        echo 'Dari ' . date('d/m/Y', strtotime($tanggal_dari));
                    } elseif (!empty($tanggal_sampai)) {
                        echo 'Sampai ' . date('d/m/Y', strtotime($tanggal_sampai));
                    } else {
                        echo 'Semua Data';
                    }
                    ?>
                </td>
                <td width="150"><strong>Gudang</strong></td>
                <td>: <?= $nama_gudang_filter ?></td>
            </tr>
            <tr>
                <td><strong>Tipe</strong></td>
                <td>: <?= !empty($tipe) ? $tipe : 'Semua Tipe' ?></td>
                <td><strong>Tanggal Cetak</strong></td>
                <td>: <?= date('d/m/Y H:i:s') ?></td>
            </tr>
            <tr>
                <td><strong>Sumber</strong></td>
                <td>: <?= !empty($sumber) ? str_replace('_', ' ', $sumber) : 'Semua Sumber' ?></td>
                <td></td>
                <td></td>
            </tr>
        </table>
    </div>

    <!-- Summary Box -->
    <div class="summary-box">
        <div class="summary-item summary-masuk">
            <h4>MUTASI MASUK</h4>
            <div class="nilai"><?= number_format($summary['total_masuk'], 0, ',', '.') ?> Unit</div>
            <div class="keterangan"><?= $summary['count_masuk'] ?> Transaksi</div>
            <div class="keterangan">Nilai: Rp <?= number_format($summary['nilai_masuk'], 0, ',', '.') ?></div>
        </div>
        <div class="summary-item summary-keluar">
            <h4>MUTASI KELUAR</h4>
            <div class="nilai"><?= number_format($summary['total_keluar'], 0, ',', '.') ?> Unit</div>
            <div class="keterangan"><?= $summary['count_keluar'] ?> Transaksi</div>
            <div class="keterangan">Nilai: Rp <?= number_format($summary['nilai_keluar'], 0, ',', '.') ?></div>
        </div>
        <div class="summary-item summary-adjustment">
            <h4>ADJUSTMENT</h4>
            <div class="nilai"><?= $summary['count_adjustment'] ?> Transaksi</div>
            <div class="keterangan">Penyesuaian Stok</div>
        </div>
    </div>

    <table class="data">
        <thead>
            <tr>
                <th width="30">No</th>
                <th width="80">Tanggal</th>
                <th width="80">Kode Obat</th>
                <th>Nama Obat</th>
                <th width="100">Gudang</th>
                <th width="60" class="text-center">Tipe</th>
                <th width="80">Sumber</th>
                <th width="70" class="text-center">Jumlah</th>
                <th width="100" class="text-right">Nilai (Rp)</th>
                <th width="100">Petugas</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $no = 1;
            $total_jumlah_masuk = 0;
            $total_jumlah_keluar = 0;
            $total_nilai_masuk = 0;
            $total_nilai_keluar = 0;
            
            while ($row = mysqli_fetch_assoc($result)) {
                $nilai_total = $row['harga_beli'] * $row['jumlah'];
                
                if ($row['tipe'] == 'MASUK') {
                    $total_jumlah_masuk += $row['jumlah'];
                    $total_nilai_masuk += $nilai_total;
                    $jumlah_display = '+' . $row['jumlah'];
                    $jumlah_class = 'text-success';
                    $tipe_badge = 'badge-masuk';
                } elseif ($row['tipe'] == 'KELUAR') {
                    $total_jumlah_keluar += $row['jumlah'];
                    $total_nilai_keluar += $nilai_total;
                    $jumlah_display = '-' . $row['jumlah'];
                    $jumlah_class = 'text-danger';
                    $tipe_badge = 'badge-keluar';
                } else {
                    $jumlah_display = '±' . $row['jumlah'];
                    $jumlah_class = 'text-warning';
                    $tipe_badge = 'badge-adjustment';
                }
                
                // Badge untuk sumber
                $sumber_badge = 'badge-pembelian';
                switch($row['sumber']) {
                    case 'PEMBELIAN': $sumber_badge = 'badge-pembelian'; break;
                    case 'PENGGUNAAN': $sumber_badge = 'badge-penggunaan'; break;
                    case 'STOK_OPNAME': $sumber_badge = 'badge-stok-opname'; break;
                    case 'RETUR': $sumber_badge = 'badge-retur'; break;
                }
            ?>
            <tr>
                <td class="text-center"><?= $no++ ?></td>
                <td><?= date('d/m/Y H:i', strtotime($row['tanggal'])) ?></td>
                <td><?= $row['kode_obat'] ?></td>
                <td><?= $row['nama_obat'] ?></td>
                <td><?= $row['nama_gudang'] ?></td>
                <td class="text-center">
                    <span class="badge <?= $tipe_badge ?>"><?= $row['tipe'] ?></span>
                </td>
                <td>
                    <span class="badge <?= $sumber_badge ?>"><?= str_replace('_', ' ', $row['sumber']) ?></span>
                </td>
                <td class="text-center <?= $jumlah_class ?>">
                    <strong><?= $jumlah_display ?> <?= $row['satuan'] ?></strong>
                </td>
                <td class="text-right"><?= number_format($nilai_total, 0, ',', '.') ?></td>
                <td><?= $row['username'] ?></td>
            </tr>
            <?php } ?>
            
            <?php if (mysqli_num_rows($result) == 0) { ?>
            <tr>
                <td colspan="10" class="text-center">Tidak ada data mutasi</td>
            </tr>
            <?php } else { ?>
            <tr class="total-row">
                <td colspan="7" class="text-right"><strong>TOTAL MASUK</strong></td>
                <td class="text-center text-success">
                    <strong>+<?= number_format($total_jumlah_masuk, 0, ',', '.') ?></strong>
                </td>
                <td class="text-right"><strong><?= number_format($total_nilai_masuk, 0, ',', '.') ?></strong></td>
                <td></td>
            </tr>
            <tr class="total-row">
                <td colspan="7" class="text-right"><strong>TOTAL KELUAR</strong></td>
                <td class="text-center text-danger">
                    <strong>-<?= number_format($total_jumlah_keluar, 0, ',', '.') ?></strong>
                </td>
                <td class="text-right"><strong><?= number_format($total_nilai_keluar, 0, ',', '.') ?></strong></td>
                <td></td>
            </tr>
            <tr class="total-row" style="background-color: #bbdefb !important;">
                <td colspan="7" class="text-right"><strong>SALDO AKHIR</strong></td>
                <td class="text-center">
                    <strong><?= number_format($total_jumlah_masuk - $total_jumlah_keluar, 0, ',', '.') ?></strong>
                </td>
                <td class="text-right">
                    <strong><?= number_format($total_nilai_masuk - $total_nilai_keluar, 0, ',', '.') ?></strong>
                </td>
                <td></td>
            </tr>
            <?php } ?>
        </tbody>
    </table>

    <div class="footer">
        <div class="ttd">
            <p>Mengetahui,<br>Kepala Puskesmas</p>
            <div class="ttd-line">
                <strong>(__________________)</strong><br>
                NIP. ............................
            </div>
        </div>
        <div class="ttd">
            <p><?= date('d F Y') ?><br>Petugas</p>
            <div class="ttd-line">
                <strong>(__________________)</strong><br>
                NIP. ............................
            </div>
        </div>
    </div>

    <script>
        // Auto print saat halaman dimuat (opsional)
        // window.onload = function() { window.print(); }
    </script>
</body>
</html>