

<style type="text/css">
/* ============================================= */
/*  STYLES DASAR                                 */
/* ============================================= */
.subrow-items td { padding: 6px 10px; }
.item-line { padding: 3px 6px; font-size: 12px; border-bottom: 1px dashed #e3e8f0; border-radius: 4px; }
.item-line:last-child { border-bottom: none; }
.item-num { display:inline-block; min-width:36px; text-align:center; background:#e3f3f0; color:#0f766e; font-weight:800; border-radius:7px; padding:1px 6px; font-size:10px; margin-right:6px; }
.item-line .label { font-size:9px; font-weight:800; padding:2px 6px; border-radius:7px; margin-left:6px; }
.label-dikirim { background:#d4edda; color:#155724; border:1px solid #b6dfc4; }
.label-pu-pending { background:#fff3cd; color:#856404; border:1px solid #ffeeba; }
.label-pu-kirim { background:#d1ecf1; color:#0c5460; border:1px solid #bee5eb; }
.pu-reason-text { font-size:10px; font-weight:700; color:#856404; margin-left:4px; }
.section-pu-kirim { background:#eaf7ef; border:1px solid #bfe3dc; border-radius:10px; padding:12px; margin-top:16px; }
.section-pu-kirim h4 { margin:0 0 10px; font-size:14px; color:#0c5460; }

/* ============================================= */
/*  WARNA BARIS BILL                             */
/* ============================================= */

/* Bill biasa (tanpa PU) → TANPA WARNA (default putih) */
/* Tidak perlu class tambahan */

/* Bill punya PU pending → KUNING MUDA */
.tr-bill-has-pu td { background-color: #fff9c4 !important; }
.sub-has-pu td { background: #fffde7 !important; }

/* Sudah diverifikasi → BIRU MUDA (override semua) */
.tr-verified td { background-color: #cfe9ff !important; }
.sub-verified td { background: #e3f2fd !important; }

/* Item PU di subrow → HIJAU MUDA */
.item-line-pu { background-color: #c8e6c9 !important; border-radius: 4px; padding: 3px 6px; }

/* Item non-PU di bill ber-PU → KUNING MUDA */
.item-line-nonpu { background-color: #fff9c4 !important; border-radius: 4px; padding: 3px 6px; }

/* ============================================= */
/*  JUMLAH PCS BESAR & TEGAS                     */
/* ============================================= */
.pcs-cell { text-align: center; vertical-align: middle; min-width: 90px; }
.pcs-big { font-size: 22px; font-weight: 900; color: #1a237e; display: block; line-height: 1.1; letter-spacing: -0.5px; }
.pcs-detail { font-size: 11px; font-weight: 700; color: #555; display: block; margin-top: 2px; line-height: 1.2; }
.pcs-detail .pu-count { color: #d84315; font-weight: 800; }

/* ============================================= */
/*  SECTION BARANG PU YANG DIKIRIM               */
/* ============================================= */
.pu-summary-big { display:inline-block; font-size:24px; font-weight:900; color:#1b5e20; margin-left:12px; vertical-align:middle; }
.pu-summary-detail { font-size:12px; font-weight:700; color:#666; display:block; margin-top:2px; }
.pu-bill-group { background:#c8e6c9; border:1px solid #a5d6a7; border-radius:8px; padding:8px 12px; margin-bottom:8px; }
.pu-bill-group-title { font-size:13px; font-weight:800; color:#1b5e20; margin-bottom:4px; }

/* ============================================= */
/*  LEGENDA WARNA                                */
/* ============================================= */
.legend-bar { margin-bottom:10px; font-size:11px; padding:6px 10px; background:#f9f9f9; border:1px solid #ddd; border-radius:6px; }
.legend-box { display:inline-block; width:14px; height:14px; border:1px solid #ccc; vertical-align:middle; margin-right:3px; border-radius:3px; }
</style>

<?php
if ($data->num_rows() == 0) {
?>
<div class="alert alert-danger">Data tidak valid</div>
<?php
}
else {
?>
<?php
$role_name = $this->session->userdata('role_name');
$the_title = 'HALAMAN KASIR';
if ($page_type == 'driver') { $the_title = 'HALAMAN DRIVER'; }
else if ($page_type == 'production') { $the_title = 'HALAMAN PRODUKSI'; }
echo "<h3 align='center'>".$the_title."</h3>";
$colspan = ($page_type == 'cashier') ? 11 : 10;
?>
<hr>
<input type="hidden" id="hd_type" value="<?php echo $page_type;?>">
<input type="hidden" id="hd_iddstb" value="<?php echo az_encode_url($data->row()->iddstb_clean);?>">
<div class="row">
    <div class="col-md-6">
        <table>
            <tr>
                <td>
                    <img style="display:inline-block" src="https://quickchart.io/qr?size=150&text=<?php echo $data->row()->dstb_code;?>">
                </td>
                <td>
                    <div style="font-size:30px;font-weight:bold;">DSTB BERSIH <?php echo $data->row()->outlet_name;?></div>
                    <table cellspacing="0">
                        <tr>
                            <td style="font-size:20px;font-weight:bold;">Tgl</td>
                            <td align="center" width="10px">:</td>
                            <td style="font-size:20px;font-weight:bold;"><?php echo Date('d-m-y H:i:s', strtotime($data->row()->dstb_date));?></td>
                        </tr>
                        <tr>
                            <td>No</td>
                            <td align="center">:</td>
                            <td><?php echo $data->row()->dstb_number;?></td>
                        </tr>
                        <tr>
                            <td colspan="3"><?php echo $data->row()->dstb_code;?></td>
                        </tr>
                        <tr>
                            <td>Driver</td>
                            <td align="center">:</td>
                            <td><?php echo $data->row()->driver_name;?></td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <table width="100%">
                        <tr>
                            <td align="center">Total Bill: <?php echo $data->row()->total_bill;?></td>
                            <td align="center">Total Pcs: <?php echo $data->row()->total_pcs_dstb;?></td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td align="center" colspan="2">
                    <div>
                        <?php
                        $lbl_status = '';
                        if (strlen($data->row()->tgl_diantar) > 0) {
                            $lbl_status .= "<label class='label label-info'>Diantar: ".Date('d-m-y H:i', strtotime($data->row()->tgl_diantar))."</label>";
                        }
                        if (strlen($data->row()->tgl_end_process) > 0) {
                            $lbl_status .= " &nbsp;<label class='label label-success'>End Process: ".Date('d-m-y H:i', strtotime($data->row()->tgl_end_process))."</label>";
                        }
                        echo $lbl_status;
                        ?>
                    </div>
                </td>
            </tr>
        </table>
    </div>
    <div class="col-md-6">
        Catatan DSTB: <?php echo $data->row()->dstb_note;?>
    </div>
</div>
<hr>

<!-- LEGENDA WARNA -->
<div class="legend-bar">
    <b>Legenda:</b> &nbsp;
    <span class="legend-box" style="background:#fff;"></span> Bill Biasa &nbsp;
    <span class="legend-box" style="background:#fff9c4;border-color:#f0e68c;"></span> Ada PU &nbsp;
    <span class="legend-box" style="background:#c8e6c9;border-color:#a5d6a7;"></span> Barang PU &nbsp;
    <span class="legend-box" style="background:#cfe9ff;border-color:#90caf9;"></span> Sudah Diverifikasi
</div>

<form id="form_dstb" class="form-horizontal">
<table class="table table-bordered table-condensed" id="table_dstb_list">
    <tr>
        <th width="10px">No</th>
        <th>No Bill</th>
        <th>Nama</th>
        <th>Status</th>
        <th>Jumlah PCS</th>
        <th>Tgl Masuk</th>
        <th>Tgl Selesai</th>
        <th>Detail</th>
        <?php if (in_array($page_type, array('driver','cashier'))) { ?>
        <th>Verifikasi</th>
        <?php } ?>
        <th>Catatan Bill</th>
        <?php if ($page_type == 'cashier') { ?>
        <th>Posisi Stok</th>
        <?php } ?>
    </tr>
    <?php
    foreach ($data->result() as $key => $value) {

        // =============================================
        //  AMBIL DATA ITEM & PU
        // =============================================
        $gid = $value->idtransaction_group;

        $this->db->select('transaction.idtransaction, product.product_name, item.item_code, transaction.trx_note');
        $this->db->from('transaction');
        $this->db->join('item', 'transaction.iditem = item.iditem', 'left');
        $this->db->join('product', 'item.idproduct = product.idproduct', 'left');
        $this->db->where('transaction.idtransaction_group', $gid);
        $this->db->where('transaction.status', 1);
        $this->db->order_by('transaction.idtransaction ASC');
        $items_q = $this->db->get()->result();
        $total_items = count($items_q);

        // Data PU untuk bill ini
        $this->db->where('idtransaction_group', $gid);
        $pu_rows = $this->db->get('dstb_clean_pu')->result();
        $pu_map = array();
        foreach ($pu_rows as $p) { $pu_map[$p->idtransaction] = $p; }

        // Hitung statistik PU
        $pu_total     = count($pu_rows);
        $pu_pending   = 0;
        $pu_sent_here = 0;
        foreach ($pu_rows as $p) {
            if (in_array((int)$p->status, array(0, 1))) $pu_pending++;
            else if ((int)$p->status == 2) $pu_sent_here++;
        }

        $has_pu      = ($pu_total > 0);
        $total_pcs   = (int)$value->total_pcs;
        $pcs_dikirim = $total_pcs - $pu_pending;
        if ($pcs_dikirim < 0) $pcs_dikirim = 0;

        // =============================================
        //  LOGIKA STATUS UNTUK KASIR (3 TINGKAT)
        // =============================================
        $display_status = $value->dstb_status;
        $verified = false;

        if ($page_type == 'driver') {
            if ($value->dstb_status == 'SELESAI') { $display_status = 'DIANTAR'; }
            if (in_array($value->dstb_status, array('DIANTAR', 'END PROCESS', 'ADA PU', 'END PROCESS LENGKAP'))) {
                $verified = true;
            }
        }
        else if ($page_type == 'cashier') {
            if ($value->dstb_status == 'SELESAI') {
                $display_status = 'END PROCESS';
            }

            if (!$has_pu) {
                // BILL BIASA (tanpa PU)
                if (in_array($value->dstb_status, array('SELESAI', 'END PROCESS'))) {
                    $display_status = 'END PROCESS';
                    $verified = true;
                }
            }
            else if ($has_pu && $pu_pending > 0) {
                // BILL NON-PU (punya PU, masih ada PU pending)
                if (in_array($value->dstb_status, array('SELESAI', 'END PROCESS', 'ADA PU'))) {
                    $display_status = 'ADA PU';
                    $verified = true;
                }
            }
            else if ($has_pu && $pu_pending == 0) {
                // BILL PU LENGKAP (semua PU sudah terkirim)
                if (in_array($value->dstb_status, array('SELESAI', 'END PROCESS', 'ADA PU', 'END PROCESS LENGKAP'))) {
                    $display_status = 'END PROCESS LENGKAP';
                    $verified = true;
                }
            }
        }

        // =============================================
        //  LOGIKA WARNA BARIS
        // =============================================
        if ($verified) {
            $tr_class = 'tr-verified';       // BIRU MUDA
            $sub_class = 'sub-verified';
        }
        else if ($has_pu && $pu_pending > 0) {
            $tr_class = 'tr-bill-has-pu';    // KUNING MUDA
            $sub_class = 'sub-has-pu';
        }
        else {
            $tr_class = '';                  // TANPA WARNA (bill biasa)
            $sub_class = '';
        }

        $no_item = 0;
    ?>
    <tr class="<?php echo $tr_class; ?>">
        <td align="center"><?php echo ($key + 1);?></td>
        <td><?php echo $value->code;?></td>
        <td><?php echo $value->customer_name;?></td>

        <!-- STATUS DENGAN BADGE WARNA -->
        <td>
            <?php if ($display_status == 'END PROCESS LENGKAP'): ?>
                <label class="label label-success" style="font-size:11px;">END PROCESS LENGKAP</label>
            <?php elseif ($display_status == 'END PROCESS'): ?>
                <label class="label label-success">END PROCESS</label>
            <?php elseif ($display_status == 'ADA PU'): ?>
                <label class="label label-warning" style="font-size:11px;">ADA PU</label>
            <?php elseif ($display_status == 'DIANTAR'): ?>
                <label class="label label-info">DIANTAR</label>
            <?php else: ?>
                <label class="label label-default"><?php echo $display_status; ?></label>
            <?php endif; ?>
        </td>

        <!-- JUMLAH PCS BESAR & TEGAS -->
        <td class="pcs-cell">
            <?php if ($has_pu): ?>
                <span class="pcs-big"><?php echo $pcs_dikirim; ?></span>
                <span class="pcs-detail">
                    (dari <?php echo $total_pcs; ?>, <span class="pu-count">PU <?php echo $pu_pending; ?></span>)
                </span>
            <?php else: ?>
                <span class="pcs-big"><?php echo $total_pcs; ?></span>
            <?php endif; ?>
        </td>

        <td><?php echo Date('d-m-Y', strtotime($value->date));?></td>
        <td><?php echo Date('d-m-Y', strtotime($value->duedate));?></td>
        <td align="center" width="10px">
            <button class="btn btn-info btn-xs btn-detail-bill" type="button"
                    data-code="<?php echo $value->code;?>"
                    data-id="<?php echo $value->idtransaction_group;?>">
                <i class="fa fa-list"></i> Detail Baju
            </button>
        </td>

        <!-- VERIFIKASI -->
        <?php if (in_array($page_type, array('driver','cashier'))) { ?>
        <td align="center">
            <?php if ($verified): ?>
                <label class="label label-success"><i class="fa fa-check"></i> Sudah</label>
            <?php else: ?>
                <button class="btn btn-success btn-xs btn-verif-bill" type="button"
                        data-code="<?php echo $value->code;?>"
                        data-id="<?php echo $value->idtransaction_group;?>"
                        data-has-pu="<?php echo $has_pu ? '1' : '0';?>"
                        data-pu-pending="<?php echo $pu_pending;?>">
                    <i class="fa fa-check"></i> Verifikasi
                </button>
            <?php endif; ?>
        </td>
        <?php } ?>

        <td><?php echo $value->note;?></td>

        <?php if ($page_type == 'cashier') { ?>
        <td align="center">
            <button class="btn btn-xs btn-primary btn-stock-position" type="button"
                    data-id="<?php echo $value->idtransaction_group;?>">
                <i class='fa fa-cube'></i> Posisi Stok
            </button>
        </td>
        <?php } ?>
    </tr>

    <!-- SUBROW ITEMS -->
    <tr class="subrow-items <?php echo $sub_class; ?>">
        <td colspan="<?php echo $colspan; ?>">
            <?php foreach ($items_q as $it): $no_item++;
                $pu = isset($pu_map[$it->idtransaction]) ? $pu_map[$it->idtransaction] : null;

                // Warna per item line
                $item_class = '';
                if ($pu) {
                    $item_class = 'item-line-pu';      // HIJAU MUDA
                }
                else if ($has_pu) {
                    $item_class = 'item-line-nonpu';   // KUNING MUDA
                }

                // Badge + Alasan PU
                if ($pu && in_array((int)$pu->status, array(0,1))) {
                    $reason_text = !empty($pu->reason) ? ' <b>(' . htmlspecialchars($pu->reason) . ')</b>' : '';
                    $badge = '<span class="label label-pu-pending">PU &middot; belum dikirim' . $reason_text . '</span>';
                }
                else if ($pu && (int)$pu->status == 2) {
                    $reason_text = !empty($pu->reason) ? ' <b>(' . htmlspecialchars($pu->reason) . ')</b>' : '';
                    $badge = '<span class="label label-pu-kirim">PU &middot; dikirim' . $reason_text . '</span>';
                }
                else {
                    $badge = '<span class="label label-dikirim">Dikirim</span>';
                }
            ?>
            <div class="item-line <?php echo $item_class; ?>">
                <span class="item-num"><?php echo $no_item.'/'.$total_items;?></span>
                &bull; <?php echo htmlspecialchars($it->product_name.' ('.$it->item_code.')'); ?>
                <?php if (strlen($it->trx_note) > 0) { echo ' &mdash; '.htmlspecialchars($it->trx_note); } ?>
                <?php echo $badge; ?>
            </div>
            <?php endforeach; ?>
        </td>
    </tr>
    <?php
    }
    ?>
</table>
</form>

<?php
// =============================================
//  BARANG PU YANG DIKIRIM DI DSTB INI
// =============================================
$this->db->select('dstb_clean_pu.*, transaction.idtransaction_group, transaction_group.code as bill_code, product.product_name, item.item_code');
$this->db->from('dstb_clean_pu');
$this->db->join('transaction', 'dstb_clean_pu.idtransaction = transaction.idtransaction', 'left');
$this->db->join('transaction_group', 'transaction.idtransaction_group = transaction_group.idtransaction_group', 'left');
$this->db->join('item', 'transaction.iditem = item.iditem', 'left');
$this->db->join('product', 'item.idproduct = product.idproduct', 'left');
$this->db->where('dstb_clean_pu.iddstb_clean', $data->row()->iddstb_clean);
$this->db->where('dstb_clean_pu.status', 2);
$pu_kirim = $this->db->get()->result();

if (count($pu_kirim) > 0) {
    // Group by bill asal
    $pu_grouped = array();
    foreach ($pu_kirim as $p) {
        $gid = $p->idtransaction_group;
        if (!isset($pu_grouped[$gid])) {
            $pu_grouped[$gid] = array(
                'bill_code' => $p->bill_code,
                'items' => array(),
                'sent_here' => 0
            );
        }
        $pu_grouped[$gid]['items'][] = $p;
        $pu_grouped[$gid]['sent_here']++;
    }
    $total_pu_kirim = count($pu_kirim);
?>
<div class="section-pu-kirim">
    <h4>
        <i class="fa fa-shopping-basket"></i> Barang PU yang dikirim di DSTB ini
        <span class="pu-summary-big"><?php echo $total_pu_kirim; ?></span>
        <span class="pu-summary-detail">barang PU dikirim di DSTB ini</span>
    </h4>

    <?php foreach ($pu_grouped as $gid => $group):
        // Hitung total PU di bill asal
        $this->db->where('idtransaction_group', $gid);
        $all_pu_in_bill = $this->db->get('dstb_clean_pu')->result();
        $total_pu_in_bill = count($all_pu_in_bill);
        $pu_already_sent_before = 0;
        foreach ($all_pu_in_bill as $ap) {
            if ((int)$ap->status == 2 && (int)$ap->iddstb_clean != (int)$data->row()->iddstb_clean) {
                $pu_already_sent_before++;
            }
        }
        $sent_here = $group['sent_here'];
    ?>
    <div class="pu-bill-group">
        <div class="pu-bill-group-title">
            <i class="fa fa-file-text-o"></i> Bill: <?php echo $group['bill_code']; ?>
            <span style="float:right; font-size:18px; font-weight:900; color:#1b5e20;">
                <?php echo $sent_here; ?>
                <span style="font-size:11px; font-weight:700; color:#555;">
                    (dari <?php echo $total_pu_in_bill; ?> PU, sudah dikirim <?php echo $pu_already_sent_before; ?>)
                </span>
            </span>
        </div>
        <table class="table table-bordered table-condensed" style="margin-bottom:0;">
            <tr>
                <th width="10px">No</th>
                <th>Nama Barang</th>
                <th>Alasan PU</th>
                <th>Est. Selesai</th>
                <th>Foto</th>
            </tr>
            <?php $n = 0; foreach ($group['items'] as $p): $n++; ?>
            <tr>
                <td align="center"><?php echo $n; ?></td>
                <td><?php echo htmlspecialchars($p->product_name.' ('.$p->item_code.')'); ?></td>
                <td><?php echo htmlspecialchars($p->reason); ?></td>
                <td><?php echo Date('d-m-Y', strtotime($p->est_finish_date)); ?></td>
                <td align="center">
                    <?php if (strlen($p->photo_proof) > 0) { ?>
                    <a href="<?php echo base_url().AZAPP.'assets/pu_proof/'.$p->photo_proof; ?>" target="_blank">
                        <button class="btn btn-info btn-xs" type="button"><i class="fa fa-camera"></i> Lihat</button>
                    </a>
                    <?php } else { echo '-'; } ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </table>
    </div>
    <?php endforeach; ?>
</div>
<?php } ?>

<?php
if (in_array($page_type, array('driver', 'cashier'))) {
?>
<button class="btn btn-info" type="button" data-id="<?php echo $page_type;?>" id="btn_scan">
    <i class="fa fa-qrcode"></i> Scan QR Code Bill
</button>
<div class="box-manual-scan">
    <div class="input-group">
        <input type="text" class="form-control" name="inp_code" id="inp_code" placeholder="Masukkan Kode Bill">
        <span class="input-group-addon btn-go-data" data-id="<?php echo $page_type;?>">
            <i class="fa fa-refresh"></i>
        </span>
    </div>
</div>
<?php
}
?>
<hr>
<a href="<?php echo app_url();?>dstb_clean">
    <button class="btn btn-default" type="button"><i class="fa fa-arrow-left"></i> Kembali</button>
</a> &nbsp;
<a href="<?php echo app_url();?>dstb_clean/print_detail/?id=<?php echo az_encode_url($data->row()->iddstb_clean).'&type='.$page_type;?>" target="_blank">
    <button class="btn btn-info" type="button"><i class="fa fa-print"></i> Cetak</button>
</a> &nbsp;
<?php
if ($page_type == 'driver') {
?>
<button class="btn btn-warning" type="button" id="btn_verif_driver">
    <i class="fa fa-check"></i> Verifikasi Driver
</button>
<?php
}
else if ($page_type == 'cashier') {
?>
<button class="btn btn-success" type="button" id="btn_verif_cashier">
    <i class="fa fa-check"></i> Verifikasi Penerimaan
</button>
<?php
}
?>
<?php
}
?>