<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Farmasi Data PO</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    
    <style>
        .card { border: 1px solid #e3e6f0; border-radius: 8px; box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15); }
        .form-control-sm { height: calc(1.5em + 0.5rem + 2px); padding: 0.25rem 0.5rem; font-size: 0.875rem; }
        .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.875rem; }
        #loadingIcon { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 9999; background: rgba(255,255,255,0.9); padding: 20px; border-radius: 10px; border: 1px solid #ccc; }
        th, td { white-space: nowrap; vertical-align: middle !important; }
        
        /* Style agar tombol detail rapi */
        .wrapper-kd-po {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 10px;
        }

        /* ========================================================
           TAMBAHAN: Style untuk mewarnai full 1 baris jika PO Selesai 
           ======================================================== */
        .row-po-selesai td {
            background-color: #f8d7da !important; /* Warna background merah muda/danger */
            color: #842029 !important; /* Warna teks merah gelap agar kontras */
        }
    </style>
</head>

<body class="bg-light">
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4 mt-4">
                <h1 class="h3 mb-2 text-gray-800">Farmasi DATA PO OBAT</h1>
                <ol class="breadcrumb mb-4">
                    <li class="breadcrumb-item"><a href="#">Dashboard</a></li>
                    <li class="breadcrumb-item active">Data PO Obat Farmasi</li>
                </ol>

                <div class="card mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-filter mr-1"></i> Filter Data PO</h6>
                    </div>
                    <div class="card-body">
                        <form id="filterFormPO"> 
                            <div class="row align-items-end">
                                <div class="col-md-4">
                                    <div class="form-group mb-0">
                                        <label class="small mb-1 font-weight-bold">Tanggal Awal</label>
                                        <input type="date" id="tgl_awal" name="TANGGAL_AWAL" class="form-control form-control-sm" value="<?= $tgl_awal ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group mb-0">
                                        <label class="small mb-1 font-weight-bold">Tanggal Akhir</label>
                                        <input type="date" id="tgl_akhir" name="TANGGAL_AKHIR" class="form-control form-control-sm" value="<?= $tgl_akhir ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group mb-0 d-flex">
                                        <button type="submit" class="btn btn-primary btn-sm mr-2 flex-fill">
                                            <i class="fas fa-search"></i> Tampilkan
                                        </button>
                                        <button type="button" id="btnDownloadPO" class="btn btn-success btn-sm flex-fill" style="display: none;">
                                            <i class="fas fa-file-excel"></i> <span id="lblDownload">Download</span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-body">
                        <div id="tableContainer" class="table-responsive">
                            <div class="text-center text-muted py-5">Silakan filter data terlebih dahulu.</div>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <footer class="py-4 bg-light mt-auto">
            <div class="container-fluid px-4">
                <div class="small text-muted text-center">Copyright &copy; IT Farmasi 2024</div>
            </div>
        </footer>
    </div>

    <div id="loadingIcon" style="display: none;">
        <div class="text-center">
            <div class="spinner-border text-primary" role="status"></div>
            <div class="mt-2 font-weight-bold text-primary">Memuat Data...</div>
        </div>
    </div>

    <form id="formDetailPO" action="<?= base_url('POfarmasidetail/tampildatadtlPO') ?>" method="POST" target="_blank" style="display:none;">
        <input type="hidden" name="KD_PO" id="hidden_kd_po">
    </form>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap4.min.js"></script>

    <script>
        $(document).ready(function() {
            
            // 1. Set Default Date
            const today = new Date().toISOString().split('T')[0];
            // $('#tgl_awal').val(today); // Biarkan ikut controller
            $('#tgl_akhir').val(today);

            // 2. Logika Submit Filter (Hanya Load Tabel)
            $('#filterFormPO').on('submit', function(e) {
                e.preventDefault();
                
                let tglAwal = $('#tgl_awal').val();
                let tglAkhir = $('#tgl_akhir').val();

                $('#loadingIcon').show();
                $('#tableContainer').hide();
                $('#btnDownloadPO').hide();

                $.ajax({
                    url: '<?= base_url("POfarmasi/tampildataPO") ?>',
                    type: 'POST',
                    data: {
                        TANGGAL_AWAL: tglAwal,
                        TANGGAL_AKHIR: tglAkhir
                    },
                    dataType: 'json',
                    success: function(data) {
                        $('#loadingIcon').hide();
                        
                        if (data && data.response && Array.isArray(data.response) && data.response.length > 0) {
                            
                            if ($.fn.DataTable.isDataTable('#dataTablePO')) {
                                $('#dataTablePO').DataTable().destroy();
                            }

                            let html = `<table id="dataTablePO" class="table table-bordered table-striped table-sm w-100" style="white-space: nowrap;">
                                <thead class="thead-dark">
                                    <tr>
                                        <th class="text-center" style="min-width: 80px;">Detail PO</th>
                                        <th>Kode PO</th>
                                        <th>No Urut</th>
                                        <th>No PO</th>
                                        <th>Nama Suplier</th>
                                        <th>Tgl PO</th>
                                        <th>CP Internal</th>
                                        <th>HP CP</th>
                                        <th>PJ</th>
                                        <th>Nama PJ</th>
                                        <th>Pencatat</th>
                                        <th>Nama Pencatat</th>
                                        <th>Kd Gudang</th>
                                        <th>Nama Gudang</th>
                                        <th>Sub Total</th>
                                        <th>% Pajak</th>
                                        <th>Nilai Pajak</th>
                                        <th>% Disc</th>
                                        <th>Nilai Disc</th>
                                        <th>Total</th>
                                        <th>Status</th>
                                        <th>Status PO</th>
                                    </tr>
                                </thead>
                                <tbody>`;
                            
                            data.response.forEach(item => {
                                let statusPoText = item.status_po || "";
                                
                                // Tentukan warna badge untuk kolom status di paling ujung
                                let badgeColor = (statusPoText.toUpperCase() === "PO SELESAI") ? "badge-danger" : "badge-secondary";
                                
                                // =====================================================================
                                // PERUBAHAN: Tentukan Class untuk mewarnai SATU BARIS FULL (<tr>)
                                // Jika PO Selesai, berikan class "row-po-selesai" yg sudah dibuat di CSS
                                // =====================================================================
                                let rowClass = (statusPoText.toUpperCase() === "PO SELESAI") ? "row-po-selesai" : "";
                                
                                html += `<tr class="${rowClass}">
                                    <td class="text-center">
                                        <button type="button" class="btn btn-info btn-sm btn-detail-po py-0 px-2" 
                                            data-kdpo="${item.kd_po}" 
                                            title="Lihat Detail di Tab Baru">
                                            <i class="fas fa-search-plus" style="font-size: 11px;"></i> Detail PO
                                        </button>
                                    </td>
                                    <td class="font-weight-bold">${item.kd_po}</td> <td>${item.urut_nomor}</td>
                                    <td>${item.no_po}</td>
                                    <td>${item.nm_suplier}</td>
                                    <td>${item.tgl_po}</td>
                                    <td>${item.cp}</td>
                                    <td>${item.hp_cp}</td>
                                    <td>${item.penanggung_jawab}</td>
                                    <td>${item.nm_penanggung_jawab}</td>
                                    <td>${item.pencatat}</td>
                                    <td>${item.nm_pencatat}</td>
                                    <td>${item.kd_gudang}</td>
                                    <td>${item.nm_gudang}</td>
                                    <td class="text-right">${parseFloat(item.sub_total || 0).toLocaleString('id-ID')}</td>
                                    <td class="text-center">${item.prosen_pajak}</td>
                                    <td class="text-right">${parseFloat(item.nilai_pajak || 0).toLocaleString('id-ID')}</td>
                                    <td class="text-center">${item.prosen_disc}</td>
                                    <td class="text-right">${parseFloat(item.nilai_disc || 0).toLocaleString('id-ID')}</td>
                                    <td class="text-right font-weight-bold">${parseFloat(item.total || 0).toLocaleString('id-ID')}</td>
                                    <td class="text-center">${item.status}</td>
                                    <td class="text-center"><span class="badge ${badgeColor}">${item.status_po}</span></td>
                                </tr>`;
                            });

                            html += `</tbody></table>`;
                            
                            $('#tableContainer').html(html).show();

                            $('#dataTablePO').DataTable({
                                "language": { "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Indonesian.json" },
                                "pageLength": 10,
                                "scrollX": true 
                            });

                            $('#lblDownload').text('Download Data PO');
                            $('#btnDownloadPO').show();

                        } else {
                            $('#tableContainer').html('<div class="alert alert-info text-center">Tidak ada data ditemukan.</div>').show();
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#loadingIcon').hide();
                        $('#tableContainer').html(`<div class="alert alert-danger text-center">Gagal mengambil data.</div>`).show();
                    }
                });
            });

            // 3. EVENT KLIK TOMBOL DETAIL (Membuka Tab Baru)
            $(document).on('click', '.btn-detail-po', function(e) {
                e.preventDefault();
                let kdPo = $(this).data('kdpo');
                
                // Isi value ke hidden form dan submit
                $('#hidden_kd_po').val(kdPo);
                $('#formDetailPO').submit();
            });

            // 4. Download Excel Rekap
            $('#btnDownloadPO').on('click', function() {
                let tglAwal = $('#tgl_awal').val();
                let tglAkhir = $('#tgl_akhir').val();
                let downloadUrl = `<?= base_url("POfarmasi/unduhdataPO") ?>?TANGGAL_AWAL=${tglAwal}&TANGGAL_AKHIR=${tglAkhir}`;
                window.location.href = downloadUrl;
            });

        });
    </script>
</body>
</html>