<?php
// FILE: cetak_laporan_pembelian.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'] : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';
$id_supplier = isset($_GET['id_supplier']) ? $_GET['id_supplier'] : '';

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

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

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

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

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

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

$query = "SELECT p.*, s.nama_supplier, s.alamat, s.telepon 
          FROM pembelian p 
          LEFT JOIN supplier s ON p.id_supplier = s.id_supplier 
          WHERE $where_sql
          ORDER BY p.tanggal_pembelian ASC";
$result = mysqli_query($conn, $query);

// Ambil nama supplier jika filter supplier aktif
$nama_supplier_filter = 'Semua Supplier';
if (!empty($id_supplier)) {
    $supplier_query = "SELECT nama_supplier FROM supplier WHERE id_supplier = '$id_supplier'";
    $supplier_result = mysqli_query($conn, $supplier_query);
    if ($supplier_data = mysqli_fetch_assoc($supplier_result)) {
        $nama_supplier_filter = $supplier_data['nama_supplier'];
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Laporan Pembelian Obat</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;
        }
        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;
        }
        .detail-items {
            margin: 5px 0;
            padding: 5px;
            background-color: #f0f0f0;
            border-radius: 3px;
            font-size: 10px;
        }
        .detail-items table {
            width: 100%;
            margin-top: 5px;
        }
        .detail-items th {
            background-color: #e0e0e0;
            padding: 4px;
            text-align: left;
            font-size: 10px;
        }
        .detail-items td {
            padding: 3px;
            border-bottom: 1px solid #ddd;
        }
        .total-row {
            background-color: #e3f2fd !important;
            font-weight: bold;
        }
        .text-right {
            text-align: right;
        }
        .text-center {
            text-align: center;
        }
        .badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 10px;
            font-weight: bold;
        }
        .badge-draft { background-color: #9e9e9e; color: white; }
        .badge-approved { background-color: #2196F3; color: white; }
        .badge-received { background-color: #4CAF50; color: white; }
        .badge-closed { background-color: #424242; color: white; }
        .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;
        }
        .summary-box {
            background-color: #e3f2fd;
            padding: 15px;
            border-radius: 5px;
            margin-top: 20px;
            border: 2px solid #2196F3;
        }
        .summary-box h6 {
            margin: 0 0 10px 0;
            color: #1976D2;
        }
        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            border-bottom: 1px solid #90CAF9;
        }
        .summary-item:last-child {
            border-bottom: none;
            font-weight: bold;
            font-size: 14px;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 2px solid #2196F3;
        }
    </style>
</head>
<body>
    <div class="no-print">
        <button class="btn-print" onclick="window.print()">🖨️ Cetak Laporan</button>
        <button class="btn-print" onclick="window.close()" style="background-color: #f44336;">❌ 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 PEMBELIAN OBAT</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>Supplier</strong></td>
                <td>: <?= $nama_supplier_filter ?></td>
            </tr>
            <tr>
                <td><strong>Status</strong></td>
                <td>: <?= !empty($status) ? $status : 'Semua Status' ?></td>
                <td><strong>Tanggal Cetak</strong></td>
                <td>: <?= date('d/m/Y H:i:s') ?></td>
            </tr>
        </table>
    </div>

    <table class="data">
        <thead>
            <tr>
                <th width="30">No</th>
                <th width="80">Tanggal</th>
                <th>Supplier</th>
                <th width="80">Status</th>
                <th width="100" class="text-right">Total Harga</th>
                <th>Detail Item</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $no = 1;
            $grand_total = 0;
            $total_transaksi = 0;
            $total_item = 0;
            
            while ($row = mysqli_fetch_assoc($result)) {
                $grand_total += $row['total_harga'];
                $total_transaksi++;
                
                // Get detail items
                $detail_query = "SELECT pd.*, o.nama_obat, o.satuan 
                               FROM pembelian_detail pd 
                               LEFT JOIN obat o ON pd.id_obat = o.id_obat 
                               WHERE pd.id_pembelian = " . $row['id_pembelian'];
                $detail_result = mysqli_query($conn, $detail_query);
                
                $status_badge = '';
                switch($row['status']) {
                    case 'DRAFT': $status_badge = 'badge-draft'; break;
                    case 'APPROVED': $status_badge = 'badge-approved'; break;
                    case 'RECEIVED': $status_badge = 'badge-received'; break;
                    case 'CLOSED': $status_badge = 'badge-closed'; break;
                }
            ?>
            <tr>
                <td class="text-center"><?= $no++ ?></td>
                <td><?= date('d/m/Y', strtotime($row['tanggal_pembelian'])) ?></td>
                <td>
                    <strong><?= $row['nama_supplier'] ?></strong><br>
                    <small><?= $row['alamat'] ?></small><br>
                    <small>Telp: <?= $row['telepon'] ?></small>
                </td>
                <td class="text-center">
                    <span class="badge <?= $status_badge ?>"><?= $row['status'] ?></span>
                </td>
                <td class="text-right"><strong>Rp <?= number_format($row['total_harga'], 0, ',', '.') ?></strong></td>
                <td>
                    <div class="detail-items">
                        <table>
                            <tr>
                                <th width="40%">Nama Obat</th>
                                <th width="15%" class="text-center">Jumlah</th>
                                <th width="20%" class="text-right">Harga</th>
                                <th width="25%" class="text-right">Subtotal</th>
                            </tr>
                            <?php 
                            while ($detail = mysqli_fetch_assoc($detail_result)) {
                                $total_item += $detail['jumlah'];
                            ?>
                            <tr>
                                <td><?= $detail['nama_obat'] ?></td>
                                <td class="text-center"><?= $detail['jumlah'] ?> <?= $detail['satuan'] ?></td>
                                <td class="text-right">Rp <?= number_format($detail['harga'], 0, ',', '.') ?></td>
                                <td class="text-right">Rp <?= number_format($detail['subtotal'], 0, ',', '.') ?></td>
                            </tr>
                            <?php } ?>
                        </table>
                        <?php if (!empty($row['keterangan'])) { ?>
                        <div style="margin-top: 5px; padding: 3px; background-color: #fff3cd; border-radius: 3px;">
                            <strong>Keterangan:</strong> <?= $row['keterangan'] ?>
                        </div>
                        <?php } ?>
                    </div>
                </td>
            </tr>
            <?php } ?>
            
            <?php if (mysqli_num_rows($result) == 0) { ?>
            <tr>
                <td colspan="6" class="text-center">Tidak ada data pembelian</td>
            </tr>
            <?php } ?>
        </tbody>
    </table>

    <?php if (mysqli_num_rows($result) > 0) { ?>
    <div class="summary-box">
        <h6>RINGKASAN LAPORAN</h6>
        <div class="summary-item">
            <span>Total Transaksi Pembelian:</span>
            <span><?= $total_transaksi ?> Transaksi</span>
        </div>
        <div class="summary-item">
            <span>Total Item Obat:</span>
            <span><?= number_format($total_item, 0, ',', '.') ?> Item</span>
        </div>
        <div class="summary-item">
            <span>GRAND TOTAL PEMBELIAN:</span>
            <span>Rp <?= number_format($grand_total, 0, ',', '.') ?></span>
        </div>
    </div>
    <?php } ?>

    <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>Admin</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>