<?php
include 'indexapoteker.php';

$user_role = isset($_SESSION['role']) ? $_SESSION['role'] : '';
$user_id = isset($_SESSION['id']) ? $_SESSION['id'] : '';

$tahun_sekarang = date('Y');
$tahun_sekarang = mysqli_real_escape_string($conn, $tahun_sekarang);

$query_eoq_rekomendasi = "SELECT 
    e.id_obat,
    e.eoq,
    e.reorder_point,
    e.safety_stock,
    o.nama_obat,
    o.kode_obat,
    o.satuan,
    o.harga_beli,
    COALESCE(stok_sub.total_stok, 0) as stok_tersedia
FROM eoq e
LEFT JOIN obat o ON e.id_obat = o.id_obat
LEFT JOIN (
    SELECT id_obat, SUM(jumlah) as total_stok
    FROM stok
    GROUP BY id_obat
) stok_sub ON e.id_obat = stok_sub.id_obat
WHERE e.periode = '" . $tahun_sekarang . "'
    AND COALESCE(stok_sub.total_stok, 0) <= e.reorder_point
    -- Filter: Jangan tampilkan jika sudah ada pembelian APPROVED atau RECEIVED
    AND e.id_obat NOT IN (
        SELECT DISTINCT pd.id_obat
        FROM pembelian_detail pd
        JOIN pembelian p ON pd.id_pembelian = p.id_pembelian
        WHERE p.status IN ('APPROVED', 'RECEIVED')
        AND DATE(p.tanggal_pembelian) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    )
ORDER BY 
    CASE 
        WHEN COALESCE(stok_sub.total_stok, 0) <= e.safety_stock THEN 1
        WHEN COALESCE(stok_sub.total_stok, 0) <= e.reorder_point THEN 2
        ELSE 3
    END,
    o.nama_obat";

$result_eoq_rekomendasi = mysqli_query($conn, $query_eoq_rekomendasi);

if (!$result_eoq_rekomendasi) {
    die("Query Error: " . mysqli_error($conn));
}
?>
<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>
                <?php if ($user_role == 'apoteker') { ?>
                <button class="btn btn-success rounded" data-bs-toggle="modal" data-bs-target="#addPembelianModal">
                    <i class="ti ti-plus"></i> Tambah Pembelian
                </button>
                <?php } ?>
            </div>
        </div>

        <?php if ($user_role == 'apoteker' && mysqli_num_rows($result_eoq_rekomendasi) > 0) { ?>
        <div class="row mb-3">
            <div class="col-sm-12">
                <div class="card border-warning">
                    <div class="card-header bg-warning text-white">
                        <h5 class="mb-0"><i class="ti ti-alert-circle"></i> Rekomendasi Pemesanan Berdasarkan EOQ</h5>
                    </div>
                    <div class="card-body">
                        <p class="mb-3">Berikut adalah obat yang perlu dipesan berdasarkan perhitungan Economic Order Quantity (EOQ):</p>
                        <div class="table-responsive">
                            <table class="table table-sm table-bordered">
                                <thead class="table-light">
                                    <tr>
                                        <th>No</th>
                                        <th>Kode Obat</th>
                                        <th>Nama Obat</th>
                                        <th>Stok Tersedia</th>
                                        <th>Reorder Point</th>
                                        <th>EOQ (Rekomendasi)</th>
                                        <th>Status</th>
                                        <th>Estimasi Biaya</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $no_rek = 1;
                                    mysqli_data_seek($result_eoq_rekomendasi, 0);
                                    while ($rek = mysqli_fetch_assoc($result_eoq_rekomendasi)) {
                                        $status_class = $rek['stok_tersedia'] <= $rek['safety_stock'] ? 'bg-danger' : 'bg-warning';
                                        $status_text = $rek['stok_tersedia'] <= $rek['safety_stock'] ? 'KRITIS' : 'PERLU PESAN';
                                        $estimasi_biaya = $rek['eoq'] * $rek['harga_beli'];
                                    ?>
                                    <tr>
                                        <td><?= $no_rek++ ?></td>
                                        <td><?= $rek['kode_obat'] ?></td>
                                        <td><strong><?= $rek['nama_obat'] ?></strong></td>
                                        <td><?= number_format($rek['stok_tersedia'], 0, ',', '.') ?> <?= $rek['satuan'] ?></td>
                                        <td><?= number_format($rek['reorder_point'], 0, ',', '.') ?> <?= $rek['satuan'] ?></td>
                                        <td><span class="badge bg-primary fs-6"><?= number_format($rek['eoq'], 0, ',', '.') ?> <?= $rek['satuan'] ?></span></td>
                                        <td><span class="badge <?= $status_class ?>"><?= $status_text ?></span></td>
                                        <td>Rp <?= number_format($estimasi_biaya, 0, ',', '.') ?></td>
                                        <td>
                                            <button class="btn btn-success btn-sm" onclick="console.log('Tombol pesan diklik'); tambahObatDariRekomendasi('<?= $rek['id_obat'] ?>', '<?= $rek['eoq'] ?>', '<?= $rek['harga_beli'] ?>'); return false;">
                                                <i class="ti ti-shopping-cart"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php } ?>

        <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="pembelianapoteker.php" class="btn btn-secondary btn-sm me-2">
                                    <i class="ti ti-refresh"></i> Reset Filter
                                </a>
                                <?php if ($user_role == 'kepala_puskesmas') { ?>
                                <button type="button" class="btn btn-success btn-sm" onclick="cetakLaporan()">
                                    <i class="ti ti-printer"></i> Cetak Laporan
                                </button>
                                <?php } ?>
                            </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
                                    $where_clauses = ["1=1"];
                                    
                                    if (isset($_GET['tanggal_dari']) && !empty($_GET['tanggal_dari'])) {
                                        $tanggal_dari = mysqli_real_escape_string($conn, $_GET['tanggal_dari']);
                                        $where_clauses[] = "DATE(p.tanggal_pembelian) >= '$tanggal_dari'";
                                    }
                                    
                                    if (isset($_GET['tanggal_sampai']) && !empty($_GET['tanggal_sampai'])) {
                                        $tanggal_sampai = mysqli_real_escape_string($conn, $_GET['tanggal_sampai']);
                                        $where_clauses[] = "DATE(p.tanggal_pembelian) <= '$tanggal_sampai'";
                                    }
                                    
                                    if (isset($_GET['status']) && !empty($_GET['status'])) {
                                        $status = mysqli_real_escape_string($conn, $_GET['status']);
                                        $where_clauses[] = "p.status = '$status'";
                                    }
                                    
                                    if (isset($_GET['id_supplier']) && !empty($_GET['id_supplier'])) {
                                        $id_supplier = mysqli_real_escape_string($conn, $_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 ($user_role == 'kepala_puskesmas' && $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 } ?>
                                            <?php if ($user_role == 'apoteker' && $row['status'] == 'DRAFT') { ?>
                                            <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editPembelianModal<?php echo $row['id_pembelian']; ?>" title="Edit">
                                                <i class="ti ti-edit"></i>
                                            </button>
                                            <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 } ?>
                                            <?php if ($user_role == 'kepala_puskesmas' && $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>

<!-- Modal Tambah Pembelian (Apoteker Only) -->
<?php if ($user_role == 'apoteker') { ?>
<div class="modal fade" id="addPembelianModal" tabindex="-1" aria-labelledby="addPembelianModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addPembelianModalLabel">Tambah Pembelian</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="tambahpembelian.php" method="POST" id="formTambahPembelian">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="id_supplier" class="form-label">Supplier <span class="text-danger">*</span></label>
                                <select class="form-select" id="id_supplier" name="id_supplier" required>
                                    <option value="">-- Pilih Supplier --</option>
                                    <?php
                                    mysqli_data_seek($supplier_result, 0);
                                    while ($supplier = mysqli_fetch_assoc($supplier_result)) {
                                        echo '<option value="'.$supplier['id_supplier'].'">'.$supplier['nama_supplier'].'</option>';
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="tanggal_pembelian" class="form-label">Tanggal Pembelian <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="tanggal_pembelian" name="tanggal_pembelian" value="<?= date('Y-m-d') ?>" required>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="keterangan" class="form-label">Keterangan</label>
                        <textarea class="form-control" id="keterangan" name="keterangan" rows="2"></textarea>
                    </div>
                    
                    <hr>
                    <h6 class="fw-bold mb-3"><i class="ti ti-list"></i> Detail Item Pembelian</h6>
                    
                    <div class="row mb-3">
                        <div class="col-md-5">
                            <label for="id_obat_add" class="form-label">Pilih Obat <span class="text-danger">*</span></label>
                            <select class="form-select" id="id_obat_add">
                                <option value="">-- Pilih Obat --</option>
                                <?php
                                $obat_query = "SELECT o.*, 
                                              COALESCE(e.eoq, 0) as eoq_value,
                                              COALESCE(e.reorder_point, 0) as rop_value,
                                              COALESCE(SUM(s.jumlah), 0) as stok_value
                                       FROM obat o
                                       LEFT JOIN eoq e ON o.id_obat = e.id_obat AND e.periode = '$tahun_sekarang'
                                       LEFT JOIN stok s ON o.id_obat = s.id_obat
                                       GROUP BY o.id_obat
                                       ORDER BY o.nama_obat";
                                $obat_result = mysqli_query($conn, $obat_query);
                                while ($obat = mysqli_fetch_assoc($obat_result)) {
                                    $has_eoq = $obat['eoq_value'] > 0;
                                    $perlu_pesan = $has_eoq && ($obat['stok_value'] <= $obat['rop_value']);
                                    $label_eoq = $has_eoq ? " [EOQ: {$obat['eoq_value']}]" : "";
                                    $label_warning = $perlu_pesan ? " ⚠️ PERLU PESAN" : "";
                                    echo '<option value="'.$obat['id_obat'].'" 
                                          data-harga="'.$obat['harga_beli'].'" 
                                          data-satuan="'.$obat['satuan'].'"
                                          data-eoq="'.$obat['eoq_value'].'"
                                          data-stok="'.$obat['stok_value'].'"
                                          data-rop="'.$obat['rop_value'].'">'
                                          .$obat['nama_obat'].$label_eoq.$label_warning.'</option>';
                                }
                                ?>
                            </select>
                            <small class="text-muted">Obat dengan ⚠️ perlu segera dipesan</small>
                        </div>
                        <div class="col-md-2">
                            <label for="jumlah_add" class="form-label">Jumlah</label>
                            <input type="number" class="form-control" id="jumlah_add" min="1" placeholder="0">
                            <small class="text-muted" id="info_eoq_add"></small>
                        </div>
                        <div class="col-md-2">
                            <label for="harga_add" class="form-label">Harga Satuan</label>
                            <input type="number" class="form-control" id="harga_add" min="0" placeholder="0" readonly>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">&nbsp;</label>
                            <button type="button" class="btn btn-primary w-100" id="btnAddItem">
                                <i class="ti ti-plus"></i> Tambah Item
                            </button>
                        </div>
                    </div>
                    
                    <div class="mt-3">
                        <div class="table-responsive">
                            <table class="table table-sm table-bordered">
                                <thead class="table-light">
                                    <tr>
                                        <th width="35%">Obat</th>
                                        <th width="15%">Jumlah</th>
                                        <th width="18%">Harga</th>
                                        <th width="20%">Subtotal</th>
                                        <th width="12%">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody id="itemTableBody">
                                    <tr>
                                        <td colspan="5" class="text-center text-muted">Belum ada item yang ditambahkan</td>
                                    </tr>
                                </tbody>
                                <tfoot class="table-light">
                                    <tr>
                                        <th colspan="3" class="text-end">Total Harga:</th>
                                        <th id="totalHarga">Rp 0</th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                    
                    <!-- Hidden input untuk menyimpan data items -->
                    <input type="hidden" name="items_data" id="items_data">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-dark" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-success" name="tambah">
                        <i class="ti ti-check"></i> Simpan Pembelian
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php } ?>

<!-- Modals untuk Detail, Edit, Konfirmasi, dan Hapus akan sama seperti sebelumnya, saya tampilkan singkat saja -->

<?php
// Query untuk modal
$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">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Detail Pembelian #<?php echo $row['id_pembelian']; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></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</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</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:</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 ($user_role == 'kepala_puskesmas' && $row['status'] == 'DRAFT') { ?>
<div class="modal fade" id="konfirmasiPembelianModal<?php echo $row['id_pembelian']; ?>" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Konfirmasi Pembelian</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="konfirmasipembelianapoteker.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">
                        <i class="ti ti-check"></i> Konfirmasi
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php } ?>

<?php if ($user_role == 'kepala_puskesmas' && $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="terimapembelianapoteker.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 } ?>

<?php if ($user_role == 'apoteker' && $row['status'] == 'DRAFT') { ?>
<div class="modal fade" id="editPembelianModal<?php echo $row['id_pembelian']; ?>" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Pembelian #<?php echo $row['id_pembelian']; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="editpembelian.php" method="POST" id="formEditPembelian<?php echo $row['id_pembelian']; ?>">
                <input type="hidden" name="id_pembelian" value="<?php echo $row['id_pembelian']; ?>">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Supplier <span class="text-danger">*</span></label>
                                <select class="form-select" name="id_supplier" required>
                                    <option value="">-- Pilih Supplier --</option>
                                    <?php
                                    $supplier_query2 = "SELECT * FROM supplier ORDER BY nama_supplier";
                                    $supplier_result2 = mysqli_query($conn, $supplier_query2);
                                    while ($supplier2 = mysqli_fetch_assoc($supplier_result2)) {
                                        $selected = ($supplier2['id_supplier'] == $row['id_supplier']) ? 'selected' : '';
                                        echo '<option value="'.$supplier2['id_supplier'].'" '.$selected.'>'.$supplier2['nama_supplier'].'</option>';
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Tanggal Pembelian <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="tanggal_pembelian" value="<?php echo $row['tanggal_pembelian']; ?>" required>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Keterangan</label>
                        <textarea class="form-control" name="keterangan" rows="2"><?php echo $row['keterangan']; ?></textarea>
                    </div>
                    
                    <hr>
                    <h6 class="fw-bold mb-3"><i class="ti ti-list"></i> Detail Item Pembelian</h6>
                    
                    <div class="row mb-3">
                        <div class="col-md-5">
                            <label class="form-label">Pilih Obat</label>
                            <select class="form-select id_obat_edit" id="id_obat_edit<?php echo $row['id_pembelian']; ?>" data-form-id="<?php echo $row['id_pembelian']; ?>">
                                <option value="">-- Pilih Obat --</option>
                                <?php
                                $obat_query2 = "SELECT o.*, 
                                              COALESCE(e.eoq, 0) as eoq_value,
                                              COALESCE(e.reorder_point, 0) as rop_value,
                                              COALESCE(SUM(s.jumlah), 0) as stok_value
                                       FROM obat o
                                       LEFT JOIN eoq e ON o.id_obat = e.id_obat AND e.periode = '$tahun_sekarang'
                                       LEFT JOIN stok s ON o.id_obat = s.id_obat
                                       GROUP BY o.id_obat
                                       ORDER BY o.nama_obat";
                                $obat_result2 = mysqli_query($conn, $obat_query2);
                                while ($obat2 = mysqli_fetch_assoc($obat_result2)) {
                                    $has_eoq = $obat2['eoq_value'] > 0;
                                    $label_eoq = $has_eoq ? " [EOQ: {$obat2['eoq_value']}]" : "";
                                    echo '<option value="'.$obat2['id_obat'].'" 
                                          data-harga="'.$obat2['harga_beli'].'" 
                                          data-satuan="'.$obat2['satuan'].'"
                                          data-eoq="'.$obat2['eoq_value'].'">'
                                          .$obat2['nama_obat'].$label_eoq.'</option>';
                                }
                                ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Jumlah</label>
                            <input type="number" class="form-control jumlah_edit" id="jumlah_edit<?php echo $row['id_pembelian']; ?>" min="1" placeholder="0">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Harga</label>
                            <input type="number" class="form-control harga_edit" id="harga_edit<?php echo $row['id_pembelian']; ?>" min="0" placeholder="0" readonly>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">&nbsp;</label>
                            <button type="button" class="btn btn-primary w-100 btnAddItemEdit" data-form-id="<?php echo $row['id_pembelian']; ?>">
                                <i class="ti ti-plus"></i> Tambah Item
                            </button>
                        </div>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered">
                            <thead class="table-light">
                                <tr>
                                    <th>Obat</th>
                                    <th>Jumlah</th>
                                    <th>Harga</th>
                                    <th>Subtotal</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody id="itemTableBodyEdit<?php echo $row['id_pembelian']; ?>">
                                <?php
                                $detail_query2 = "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_result2 = mysqli_query($conn, $detail_query2);
                                while ($detail2 = mysqli_fetch_assoc($detail_result2)) {
                                ?>
                                <tr>
                                    <td><?= $detail2['nama_obat'] ?></td>
                                    <td><?= $detail2['jumlah'] ?></td>
                                    <td>Rp <?= number_format($detail2['harga'], 0, ',', '.') ?></td>
                                    <td>Rp <?= number_format($detail2['subtotal'], 0, ',', '.') ?></td>
                                    <td>
                                        <button type="button" class="btn btn-danger btn-sm" onclick="hapusItemEdit<?php echo $row['id_pembelian']; ?>(this)">
                                            <i class="ti ti-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php } ?>
                            </tbody>
                            <tfoot class="table-light">
                                <tr>
                                    <th colspan="3" class="text-end">Total:</th>
                                    <th id="totalHargaEdit<?php echo $row['id_pembelian']; ?>">Rp <?= number_format($row['total_harga'], 0, ',', '.') ?></th>
                                    <th></th>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    
                    <input type="hidden" name="items_data" id="items_data_edit<?php echo $row['id_pembelian']; ?>">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-dark" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-warning" name="edit">
                        <i class="ti ti-device-floppy"></i> Simpan Perubahan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php } ?>

<!-- Modal Hapus Pembelian (Apoteker Only) -->
<?php if ($user_role == 'apoteker' && $row['status'] == 'DRAFT') { ?>
<div class="modal fade" id="deletePembelianModal<?php echo $row['id_pembelian']; ?>" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Konfirmasi Hapus</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="hapuspembelianapoteker.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, ',', '.') ?>
                    </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">
                        <i class="ti ti-trash"></i> Hapus
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php } ?>

<?php } ?>
<!-- LETAKKAN DI AKHIR HALAMAN SEBELUM </body> -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    // Validasi jQuery sudah loaded
    if (typeof jQuery === 'undefined') {
        console.error('jQuery tidak terload!');
    } else {
        console.log('jQuery terload dengan baik');
    }

    // Global variable
    var items = [];

    // Ketika DOM sudah siap
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM Ready');

        // Tombol Tambah Item
        var btnAddItem = document.getElementById('btnAddItem');
        if (btnAddItem) {
            btnAddItem.addEventListener('click', function() {
                console.log('Tombol Tambah Item diklik');
                tambahItem();
            });
        } else {
            console.error('Tombol btnAddItem tidak ditemukan!');
        }

        // Select obat change event
        var selectObat = document.getElementById('id_obat_add');
        if (selectObat) {
            selectObat.addEventListener('change', function() {
                console.log('Obat dipilih:', this.value);
                updateHarga();
            });
        }

        // Form submit
        var formTambah = document.getElementById('formTambahPembelian');
        if (formTambah) {
            formTambah.addEventListener('submit', function(e) {
                console.log('Form submit, items:', items.length);
                if (items.length === 0) {
                    e.preventDefault();
                    alert('Tambahkan minimal 1 item pembelian!');
                    return false;
                }
            });
        }

        // Modal close event
        var modal = document.getElementById('addPembelianModal');
        if (modal) {
            modal.addEventListener('hidden.bs.modal', function() {
                console.log('Modal ditutup');
                items = [];
                renderTable();
                if (formTambah) {
                    formTambah.reset();
                }
            });
        }
    });

    // Fungsi update harga
    function updateHarga() {
        var selectObat = document.getElementById('id_obat_add');
        var inputHarga = document.getElementById('harga_add');
        
        if (!selectObat || !inputHarga) return;

        var selectedOption = selectObat.options[selectObat.selectedIndex];
        var harga = selectedOption.getAttribute('data-harga') || '0';
        var eoq = selectedOption.getAttribute('data-eoq') || '0';

        inputHarga.value = harga;
        
        // Set jumlah dari EOQ jika ada
        if (eoq > 0) {
            document.getElementById('jumlah_add').value = eoq;
        }

        console.log('Harga diupdate:', harga, 'EOQ:', eoq);
    }

    // Fungsi tambah item
    function tambahItem() {
        var selectObat = document.getElementById('id_obat_add');
        var inputJumlah = document.getElementById('jumlah_add');
        var inputHarga = document.getElementById('harga_add');

        if (!selectObat || !inputJumlah || !inputHarga) {
            alert('Element tidak ditemukan!');
            return false;
        }

        var idObat = selectObat.value;
        var namaObat = selectObat.options[selectObat.selectedIndex].text;
        var satuan = selectObat.options[selectObat.selectedIndex].getAttribute('data-satuan') || '';
        var jumlah = parseInt(inputJumlah.value) || 0;
        var harga = parseInt(inputHarga.value) || 0;

        console.log('Data Item:', {
            idObat: idObat,
            namaObat: namaObat,
            satuan: satuan,
            jumlah: jumlah,
            harga: harga
        });

        // Validasi
        if (!idObat) {
            alert('Pilih obat terlebih dahulu!');
            return false;
        }

        if (jumlah <= 0) {
            alert('Jumlah harus lebih dari 0!');
            return false;
        }

        if (harga <= 0) {
            alert('Harga harus lebih dari 0!');
            return false;
        }

        // Cek duplikat
        var isDuplicate = items.some(function(item) {
            return item.id == idObat;
        });

        if (isDuplicate) {
            alert('Obat sudah ditambahkan! Hapus terlebih dahulu jika ingin mengubah.');
            return false;
        }

        // Tambah ke array
        var subtotal = jumlah * harga;
        items.push({
            id: idObat,
            nama: namaObat,
            satuan: satuan,
            jumlah: jumlah,
            harga: harga,
            subtotal: subtotal
        });

        console.log('Item ditambahkan. Total items:', items.length);

        // Update tampilan
        renderTable();
        resetForm();

        return false;
    }

    // Fungsi render table
    function renderTable() {
        var tbody = document.getElementById('itemTableBody');
        var totalHarga = document.getElementById('totalHarga');
        var itemsDataInput = document.getElementById('items_data');

        if (!tbody) {
            console.error('tbody itemTableBody tidak ditemukan!');
            return;
        }

        var html = '';
        var total = 0;

        if (items.length === 0) {
            html = '<tr><td colspan="5" class="text-center text-muted">Belum ada item yang ditambahkan</td></tr>';
        } else {
            items.forEach(function(item, index) {
                html += '<tr>';
                html += '<td>' + item.nama + '</td>';
                html += '<td>' + item.jumlah + ' ' + item.satuan + '</td>';
                html += '<td>Rp ' + item.harga.toLocaleString('id-ID') + '</td>';
                html += '<td>Rp ' + item.subtotal.toLocaleString('id-ID') + '</td>';
                html += '<td><button type="button" class="btn btn-danger btn-sm" onclick="removeItem(' + index + '); return false;"><i class="ti ti-trash"></i></button></td>';
                html += '</tr>';
                total += item.subtotal;
            });
        }

        tbody.innerHTML = html;
        
        if (totalHarga) {
            totalHarga.textContent = 'Rp ' + total.toLocaleString('id-ID');
        }

        if (itemsDataInput) {
            itemsDataInput.value = JSON.stringify(items);
        }

        console.log('Table dirender, total:', total);
    }

    // Fungsi hapus item
    function removeItem(index) {
        console.log('Menghapus item index:', index);
        items.splice(index, 1);
        renderTable();
    }

    // Fungsi reset form
    function resetForm() {
        var selectObat = document.getElementById('id_obat_add');
        var inputJumlah = document.getElementById('jumlah_add');
        var inputHarga = document.getElementById('harga_add');
        var infoEoq = document.getElementById('info_eoq_add');

        if (selectObat) selectObat.value = '';
        if (inputJumlah) inputJumlah.value = '';
        if (inputHarga) inputHarga.value = '';
        if (infoEoq) infoEoq.innerHTML = '';

        console.log('Form direset');
    }

    // Fungsi tambah dari rekomendasi EOQ
    function tambahObatDariRekomendasi(idObat, eoq, harga) {
        console.log('Tambah dari rekomendasi:', idObat, eoq, harga);
        
        items = []; // Reset
        renderTable();
        
        // Buka modal terlebih dahulu
        var modal = document.getElementById('addPembelianModal');
        if (modal) {
            // Gunakan Bootstrap jika tersedia
            if (typeof bootstrap !== 'undefined') {
                var bsModal = bootstrap.Modal.getOrCreateInstance(modal);
                bsModal.show();
            }
        }
        
        // Tunggu modal terbuka
        setTimeout(function() {
            var selectObat = document.getElementById('id_obat_add');
            var inputJumlah = document.getElementById('jumlah_add');
            var inputHarga = document.getElementById('harga_add');

            console.log('Mengisi form dengan:', idObat, eoq, harga);

            if (selectObat) {
                selectObat.value = idObat;
                // Trigger change event
                var event = new Event('change', { bubbles: true });
                selectObat.dispatchEvent(event);
            }
            
            if (inputJumlah) inputJumlah.value = eoq;
            if (inputHarga) inputHarga.value = harga;

            console.log('Form sudah diisi dari rekomendasi');
        }, 800);
    }
    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'; ?>