<?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 Pembelian</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 Pembelian</h5>
                    </div>
                    <div class="card-body">
                        <form method="GET" action="" id="filterForm">
                            <div class="row align-items-end">
                                <div class="col-md-3">
                                    <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-3">
                                    <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="status" class="form-label">Status</label>
                                    <select class="form-select" id="status" name="status">
                                        <option value="">Semua</option>
                                        <option value="DRAFT" <?= (isset($_GET['status']) && $_GET['status'] == 'DRAFT') ? 'selected' : '' ?>>DRAFT</option>
                                        <option value="APPROVED" <?= (isset($_GET['status']) && $_GET['status'] == 'APPROVED') ? 'selected' : '' ?>>APPROVED</option>
                                        <option value="RECEIVED" <?= (isset($_GET['status']) && $_GET['status'] == 'RECEIVED') ? 'selected' : '' ?>>RECEIVED</option>
                                        <option value="CLOSED" <?= (isset($_GET['status']) && $_GET['status'] == 'CLOSED') ? 'selected' : '' ?>>CLOSED</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label for="id_supplier" class="form-label">Supplier</label>
                                    <select class="form-select" id="id_supplier" name="id_supplier">
                                        <option value="">Semua</option>
                                        <?php
                                        $supplier_query = "SELECT * FROM supplier ORDER BY nama_supplier";
                                        $supplier_result = mysqli_query($conn, $supplier_query);
                                        while ($supplier = mysqli_fetch_assoc($supplier_result)) {
                                            $selected = (isset($_GET['id_supplier']) && $_GET['id_supplier'] == $supplier['id_supplier']) ? 'selected' : '';
                                            echo "<option value='{$supplier['id_supplier']}' $selected>{$supplier['nama_supplier']}</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['status']) || isset($_GET['id_supplier'])) { ?>
                        <div class="row mt-3">
                            <div class="col-md-12">
                                <a href="pembelian.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>

        <div class="row">
            <div class="col-sm-12">
                <div class="card">
                    <div class="card-header">
                        <h5>Daftar Pembelian</h5>
                        <small>Kelola konfirmasi pembelian obat dari supplier</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>Supplier</th>
                                        <th>Total Harga</th>
                                        <th>Status</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(p.tanggal_pembelian) >= '$tanggal_dari'";
                                    }
                                    
                                    if (isset($_GET['tanggal_sampai']) && !empty($_GET['tanggal_sampai'])) {
                                        $tanggal_sampai = $_GET['tanggal_sampai'];
                                        $where_clauses[] = "DATE(p.tanggal_pembelian) <= '$tanggal_sampai'";
                                    }
                                    
                                    if (isset($_GET['status']) && !empty($_GET['status'])) {
                                        $status = $_GET['status'];
                                        $where_clauses[] = "p.status = '$status'";
                                    }
                                    
                                    if (isset($_GET['id_supplier']) && !empty($_GET['id_supplier'])) {
                                        $id_supplier = $_GET['id_supplier'];
                                        $where_clauses[] = "p.id_supplier = '$id_supplier'";
                                    }
                                    
                                    $where_sql = implode(" AND ", $where_clauses);
                                    
                                    $query = "SELECT p.*, s.nama_supplier 
                                              FROM pembelian p 
                                              LEFT JOIN supplier s ON p.id_supplier = s.id_supplier 
                                              WHERE $where_sql
                                              ORDER BY p.id_pembelian DESC";
                                    $result = mysqli_query($conn, $query);
                                    $no = 1;
                                    while ($row = mysqli_fetch_assoc($result)) {
                                        $status_class = '';
                                        switch($row['status']) {
                                            case 'DRAFT': $status_class = 'bg-secondary'; break;
                                            case 'APPROVED': $status_class = 'bg-info'; break;
                                            case 'RECEIVED': $status_class = 'bg-success'; break;
                                            case 'CLOSED': $status_class = 'bg-dark'; break;
                                        }
                                    ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td><?= date('d/m/Y', strtotime($row['tanggal_pembelian'])) ?></td>
                                        <td><?= $row['nama_supplier'] ?></td>
                                        <td>Rp <?= number_format($row['total_harga'], 0, ',', '.') ?></td>
                                        <td><span class="badge <?= $status_class ?>"><?= $row['status'] ?></span></td>
                                        <td class="text-center">
                                            <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#detailPembelianModal<?php echo $row['id_pembelian']; ?>" title="Detail">
                                                <i class="ti ti-eye"></i>
                                            </button>
                                            <?php if ($row['status'] == 'DRAFT') { ?>
                                            <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#konfirmasiPembelianModal<?php echo $row['id_pembelian']; ?>" title="Konfirmasi">
                                                <i class="ti ti-check"></i>
                                            </button>
                                            <?php } ?>
                                            <button class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#deletePembelianModal<?php echo $row['id_pembelian']; ?>" title="Hapus">
                                                <i class="ti ti-trash"></i>
                                            </button>
                                            <?php if ($row['status'] == 'APPROVED') { ?>
                                            <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#terimaPembelianModal<?php echo $row['id_pembelian']; ?>" title="Terima">
                                                <i class="ti ti-truck-delivery"></i>
                                            </button>
                                            <?php } ?>
                                        </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(p.tanggal_pembelian) >= '{$_GET['tanggal_dari']}'";
    }
    
    if (isset($_GET['tanggal_sampai']) && !empty($_GET['tanggal_sampai'])) {
        $where_clauses_modal[] = "DATE(p.tanggal_pembelian) <= '{$_GET['tanggal_sampai']}'";
    }
    
    if (isset($_GET['status']) && !empty($_GET['status'])) {
        $where_clauses_modal[] = "p.status = '{$_GET['status']}'";
    }
    
    if (isset($_GET['id_supplier']) && !empty($_GET['id_supplier'])) {
        $where_clauses_modal[] = "p.id_supplier = '{$_GET['id_supplier']}'";
    }
    
    $where_sql_modal = implode(" AND ", $where_clauses_modal);
    
    $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_modal
              ORDER BY p.id_pembelian DESC";
    $result = mysqli_query($conn, $query);
    while ($row = mysqli_fetch_assoc($result)) {
?>
<!-- Modal Detail Pembelian -->
<div class="modal fade" id="detailPembelianModal<?php echo $row['id_pembelian']; ?>" tabindex="-1" aria-labelledby="detailPembelianModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="detailPembelianModalLabel">Detail Pembelian #<?php echo $row['id_pembelian']; ?></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 Pembelian</h6>
                        <table class="table table-sm">
                            <tr>
                                <td width="150">Tanggal</td>
                                <td>: <?= date('d/m/Y', strtotime($row['tanggal_pembelian'])) ?></td>
                            </tr>
                            <tr>
                                <td>Status</td>
                                <td>: <span class="badge bg-info"><?= $row['status'] ?></span></td>
                            </tr>
                            <tr>
                                <td>Keterangan</td>
                                <td>: <?= $row['keterangan'] ?: '-' ?></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6 class="fw-bold">Informasi Supplier</h6>
                        <table class="table table-sm">
                            <tr>
                                <td width="150">Nama Supplier</td>
                                <td>: <?= $row['nama_supplier'] ?></td>
                            </tr>
                            <tr>
                                <td>Alamat</td>
                                <td>: <?= $row['alamat'] ?></td>
                            </tr>
                            <tr>
                                <td>Telepon</td>
                                <td>: <?= $row['telepon'] ?></td>
                            </tr>
                        </table>
                    </div>
                </div>
                
                <h6 class="fw-bold mt-4">Detail Item Pembelian</h6>
                <div class="table-responsive">
                    <table class="table table-bordered table-sm">
                        <thead class="table-light">
                            <tr>
                                <th>No</th>
                                <th>Nama Obat</th>
                                <th class="text-end">Jumlah</th>
                                <th class="text-end">Harga</th>
                                <th class="text-end">Subtotal</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $detail_query = "SELECT pd.*, o.nama_obat 
                                           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);
                            $no_detail = 1;
                            while ($detail = mysqli_fetch_assoc($detail_result)) {
                            ?>
                            <tr>
                                <td><?= $no_detail++ ?></td>
                                <td><?= $detail['nama_obat'] ?></td>
                                <td class="text-end"><?= $detail['jumlah'] ?></td>
                                <td class="text-end">Rp <?= number_format($detail['harga'], 0, ',', '.') ?></td>
                                <td class="text-end">Rp <?= number_format($detail['subtotal'], 0, ',', '.') ?></td>
                            </tr>
                            <?php } ?>
                        </tbody>
                        <tfoot class="table-light">
                            <tr>
                                <th colspan="4" class="text-end">Total Harga:</th>
                                <th class="text-end">Rp <?= number_format($row['total_harga'], 0, ',', '.') ?></th>
                            </tr>
                        </tfoot>
                    </table>
                </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 if ($row['status'] == 'DRAFT') { ?>
<!-- Modal Konfirmasi Pembelian -->
<div class="modal fade" id="konfirmasiPembelianModal<?php echo $row['id_pembelian']; ?>" tabindex="-1" aria-labelledby="konfirmasiPembelianModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="konfirmasiPembelianModalLabel">Konfirmasi Pembelian</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="konfirmasipembelian.php" method="POST">
                <input type="hidden" name="id_pembelian" value="<?php echo $row['id_pembelian']; ?>">
                <div class="modal-body">
                    <p>Apakah Anda yakin ingin mengkonfirmasi pembelian ini?</p>
                    <div class="alert alert-info">
                        <strong>Detail Pembelian:</strong><br>
                        Supplier: <?php echo $row['nama_supplier']; ?><br>
                        Tanggal: <?= date('d/m/Y', strtotime($row['tanggal_pembelian'])) ?><br>
                        Total: Rp <?= number_format($row['total_harga'], 0, ',', '.') ?>
                    </div>
                    <p class="text-muted small">Status akan berubah menjadi <strong>APPROVED</strong></p>
                </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-success" name="konfirmasi">Konfirmasi</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php } ?>

<?php if ($row['status'] == 'APPROVED') { ?>
<div class="modal fade" id="terimaPembelianModal<?php echo $row['id_pembelian']; ?>" tabindex="-1" aria-labelledby="terimaPembelianModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="terimaPembelianModalLabel">Terima Pembelian #<?php echo $row['id_pembelian']; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="terimapembelian.php" method="POST">
                <input type="hidden" name="id_pembelian" value="<?php echo $row['id_pembelian']; ?>">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <strong><i class="ti ti-info-circle"></i> Informasi Penerimaan Barang</strong>
                    </div>

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <h6 class="fw-bold">Informasi Pembelian</h6>
                            <table class="table table-sm table-borderless">
                                <tr>
                                    <td width="140">Tanggal Pembelian</td>
                                    <td>: <?= date('d/m/Y', strtotime($row['tanggal_pembelian'])) ?></td>
                                </tr>
                                <tr>
                                    <td>Supplier</td>
                                    <td>: <?= $row['nama_supplier'] ?></td>
                                </tr>
                                <tr>
                                    <td>Status</td>
                                    <td>: <span class="badge bg-info"><?= $row['status'] ?></span></td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6 class="fw-bold">Ringkasan Item</h6>
                            <table class="table table-sm table-borderless">
                                <tr>
                                    <td width="140">Total Item</td>
                                    <td>: 
                                        <?php
                                        $count_query = "SELECT COUNT(*) as total FROM pembelian_detail WHERE id_pembelian = {$row['id_pembelian']}";
                                        $count_result = mysqli_query($conn, $count_query);
                                        $count = mysqli_fetch_assoc($count_result);
                                        echo $count['total'];
                                        ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td>Total Harga</td>
                                    <td>: Rp <?= number_format($row['total_harga'], 0, ',', '.') ?></td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <h6 class="fw-bold mb-3">Detail Item yang Diterima</h6>
                    <div class="table-responsive">
                        <table class="table table-bordered table-sm">
                            <thead class="table-light">
                                <tr>
                                    <th>No</th>
                                    <th>Nama Obat</th>
                                    <th class="text-center">Jumlah Pesan</th>
                                    <th class="text-center">Harga/Unit</th>
                                    <th class="text-end">Subtotal</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $detail_query_terima = "SELECT pd.*, o.nama_obat 
                                                       FROM pembelian_detail pd 
                                                       LEFT JOIN obat o ON pd.id_obat = o.id_obat 
                                                       WHERE pd.id_pembelian = {$row['id_pembelian']}";
                                $detail_result_terima = mysqli_query($conn, $detail_query_terima);
                                $no_terima = 1;
                                while ($detail_terima = mysqli_fetch_assoc($detail_result_terima)) {
                                ?>
                                <tr>
                                    <td><?= $no_terima++ ?></td>
                                    <td><strong><?= $detail_terima['nama_obat'] ?></strong></td>
                                    <td class="text-center"><?= $detail_terima['jumlah'] ?></td>
                                    <td class="text-center">Rp <?= number_format($detail_terima['harga'], 0, ',', '.') ?></td>
                                    <td class="text-end">Rp <?= number_format($detail_terima['subtotal'], 0, ',', '.') ?></td>
                                </tr>
                                <?php } ?>
                            </tbody>
                            <tfoot class="table-light">
                                <tr>
                                    <th colspan="4" class="text-end">Total:</th>
                                    <th class="text-end">Rp <?= number_format($row['total_harga'], 0, ',', '.') ?></th>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

                    <div class="alert alert-warning mt-4">
                        <i class="ti ti-alert-circle"></i>
                        <strong>Perhatian!</strong><br>
                        Dengan menerima pembelian ini, Anda menyatakan bahwa:
                        <ul class="mt-2 mb-0">
                            <li>Semua item telah diterima dengan lengkap sesuai pesanan</li>
                            <li>Kondisi item baik dan tidak rusak</li>
                            <li>Stok akan otomatis ditambahkan ke gudang</li>
                        </ul>
                    </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-success" name="terima">
                        <i class="ti ti-truck-delivery"></i> Terima Pembelian
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php } ?>

<!-- Modal Hapus Pembelian -->
<div class="modal fade" id="deletePembelianModal<?php echo $row['id_pembelian']; ?>" tabindex="-1" aria-labelledby="deletePembelianModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deletePembelianModalLabel">Konfirmasi Hapus</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="hapuspembelian.php" method="POST">
                <input type="hidden" name="id_pembelian" value="<?php echo $row['id_pembelian']; ?>">
                <div class="modal-body">
                    <p>Apakah Anda yakin ingin menghapus pembelian ini?</p>
                    <div class="alert alert-warning">
                        <i class="ti ti-alert-triangle"></i> Data pembelian dan detail item akan dihapus permanen!
                    </div>
                    <div class="alert alert-info">
                        <strong>Detail Pembelian:</strong><br>
                        Supplier: <?php echo $row['nama_supplier']; ?><br>
                        Tanggal: <?= date('d/m/Y', strtotime($row['tanggal_pembelian'])) ?><br>
                        Total: Rp <?= number_format($row['total_harga'], 0, ',', '.') ?><br>
                        Status: <?php echo $row['status']; ?>
                    </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-danger" name="hapus">Hapus</button>
                </div>
            </form>
        </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 status = params.get('status') || '';
    const idSupplier = params.get('id_supplier') || '';
    
    const url = `cetaklaporanpembelian.php?tanggal_dari=${tanggalDari}&tanggal_sampai=${tanggalSampai}&status=${status}&id_supplier=${idSupplier}`;
    window.open(url, '_blank');
}
</script>

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