<?php 
    if (!function_exists('spk_safe_prop')) {
        function spk_safe_prop($src, array $keys, $default = '')
        {
            foreach ($keys as $k) {
                if (is_object($src) && isset($src->$k) && $src->$k !== '' && $src->$k !== null) return $src->$k;
                if (is_array($src)  && isset($src[$k]) && $src[$k] !== '' && $src[$k] !== null) return $src[$k];
            }
            return $default;
        }
    }

    if (!function_exists('spk_image_src')) {
        function spk_image_src($rawPath = '')
        {
            $rawPath = trim((string)$rawPath);
            if ($rawPath === '') return '';

            if (strpos($rawPath, 'data:image/') === 0) {
                return $rawPath;
            }

            if (preg_match('#^https?://#i', $rawPath)) {
                return $rawPath;
            }

            $rel = ltrim(str_replace('\\', '/', $rawPath), '/');
            $abs = FCPATH . $rel;
            if (!is_file($abs)) {
                return base_url($rel);
            }

            $mime = function_exists('mime_content_type') ? @mime_content_type($abs) : 'image/jpeg';
            if (!is_string($mime) || strpos($mime, 'image/') !== 0) {
                return base_url($rel);
            }

            $bin = @file_get_contents($abs);
            if ($bin === false) {
                return base_url($rel);
            }

            return 'data:' . $mime . ';base64,' . base64_encode($bin);
        }
    }

    // Kumpulkan gambar finishing untuk ditampilkan di QC CHECKLIST -> Catatan.
    $qc_finishing_images = [];
    $qc_seen_images = [];
    if (!empty($detail) && is_array($detail)) {
        foreach ($detail as $__d) {
            $__rawDetail = '';
            $__bahan = '';
            $__ket = '';
            if (is_array($__d) && isset($__d['detail'])) {
                $__rawDetail = $__d['detail'];
                $__bahan = trim((string) spk_safe_prop($__d, ['nbahan', 'bahan', 'nama_bahan'], ''));
                $__ket = trim((string) spk_safe_prop($__d, ['keterangan', 'ket', 'catatan'], ''));
            } elseif (is_object($__d) && isset($__d->detail)) {
                $__rawDetail = $__d->detail;
                $__bahan = trim((string) spk_safe_prop($__d, ['nbahan', 'bahan', 'nama_bahan'], ''));
                $__ket = trim((string) spk_safe_prop($__d, ['keterangan', 'ket', 'catatan'], ''));
            }
            if ($__rawDetail === '' || $__rawDetail === null) {
                continue;
            }

            $__decoded = @json_decode($__rawDetail);
            if (!is_object($__decoded) || empty($__decoded->data) || !is_array($__decoded->data)) {
                continue;
            }

            foreach ($__decoded->data as $__f) {
                $__imgPath = trim((string) spk_safe_prop($__f, ['gambar', 'image', 'img'], ''));
                if ($__imgPath === '') {
                    continue;
                }

                $__src = spk_image_src($__imgPath);
                if ($__src === '') {
                    continue;
                }

                $__finishing = trim((string) spk_safe_prop($__f, ['isi', 'title', 'name', 'keterangan'], ''));
                $__bahan_label = ($__bahan !== '') ? $__bahan : '-';
                $__ket_label = ($__ket !== '') ? $__ket : '-';
                $__finishing_label = ($__finishing !== '') ? $__finishing : '-';
                $__hash = md5($__src . '|' . $__bahan_label . '|' . $__ket_label . '|' . $__finishing_label);
                if (isset($qc_seen_images[$__hash])) {
                    continue;
                }
                $qc_seen_images[$__hash] = true;

                $qc_finishing_images[] = [
                    'src' => $__src,
                    'info_line' => $__bahan_label . ' | ' . $__ket_label . ' | ' . $__finishing_label
                ];
            }
        }
    }

    $coun = count($detail); 
    $top = 0;
    if($coun==2){
        $top = '8cm';
    }elseif($coun==3){
        $top = '7cm';
    }elseif($coun==4){
        $top = '8cm';
    }elseif($coun==5){
        $top = '9cm';
    }elseif($coun==6){
        $top = '10cm';
    }elseif($coun==7){
        $top = '11cm';
    }elseif($coun==8){
        $top = '12cm';
    }elseif($coun==9){
        $top = '9cm';
    }elseif($coun==10){
        $top = '10cm';
    }elseif($coun==11){
        $top = '11cm';
    }elseif($coun==12){
        $top = '12cm';
    }else{
        $top = '6cm';
    }
    
    if($konsumen['no_hp']=='-'){
        $no_hp = '-';
    }else{
        $no_hp = hp_1(hp_2($konsumen['no_hp']));
    }

    if($tdetail == $total->total AND $pajak==0){
        $stamp   = $lunas;
        $alt     = '';
        $logo    = $logo_lunas;
        $color   = $info['warna_lunas'];
        $_waicon = $waicon['color'];
        $_mail   = $mail['color'];
        $_fbicon = $fbicon['color'];
        $_igicon = $igicon['color'];
    }elseif($tdetail == $total->total AND $pajak>0){
        $stamp   = $lunas;
        $alt     = '';
        $logo    = $logo_lunas;
        $color   = $info['warna_lunas'];
        $_waicon = $waicon['color'];
        $_mail   = $mail['color'];
        $_fbicon = $fbicon['color'];
        $_igicon = $igicon['color'];
    }elseif($tdetail != $total->total AND $pajak==0){
        $stamp   = $blunas;
        $alt     = '';
        $logo    = $logo_blunas;
        $color   = $info['warna_blunas'];
        $_waicon = $waicon['bw'];
        $_mail   = $mail['bw'];
        $_fbicon = $fbicon['bw'];
        $_igicon = $igicon['bw'];
    }elseif($tdetail != $total->total AND $pajak>0){
        $stamp   = $blunas;
        $alt     = '';
        $logo    = $logo_blunas;
        $color   = $info['warna_blunas'];
        $_waicon = $waicon['bw'];
        $_mail   = $mail['bw'];
        $_fbicon = $fbicon['bw'];
        $_igicon = $igicon['bw'];
    }else{
        $stamp   = $blunas;
        $alt     = '';
        $logo    = $logo_blunas;
        $color   = $info['warna_blunas'];
        $_waicon = $waicon['bw'];
        $_mail   = $mail['bw'];
        $_fbicon = $fbicon['bw'];
        $_igicon = $igicon['bw'];
    }
    if($cetak->status=='batal'){
        $stamp   = '';
        $alt     = 'BATAL';
        $color   = "#333";
        $_waicon = $waicon['bw'];
        $_mail   = $mail['bw'];
        $_fbicon = $fbicon['bw'];
        $_igicon = $igicon['bw'];
    }
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Cetak Laporan Pekerjaan</title>
    <link href="<?= $favicon;?>" rel="icon">
    <style>
        /* orientasi & ukuran kertas A5 portrait */
        @page { 
            size: A5 portrait;
            margin: 0;
        }

        body {
            margin-top: 0cm;
            margin-left: 0.5cm;
            margin-right: 1cm;
            margin-bottom: 0cm;
            font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif;
        }

        .invoice-box {
            width:100%;
            margin: 0 auto;
            padding: 10px;
            font-size: 11px;              /* sedikit dikecilkan agar muat portrait */
            line-height: 17px;
            font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif;
            color: #555;
        }

        footer {
            position: fixed; 
            bottom: 0cm; 
            left: 0cm; 
            right: 0cm;
            height: 0.5cm;
            padding:5px;
            background-color: <?=$color;?>;
            color: white;
            text-align: center;
            font-size:10px;
            line-height:1.2;
        }

        .invoice-box table { 
            width: 100%; 
            line-height: inherit; 
            text-align: left; 
            border-collapse: collapse; 
        }
        .invoice-box table td { 
            padding: 0 5px; 
            vertical-align: top; 
        }

        .invoice-box table tr.heading td {
            background: <?=$color;?>;
            color: #fff;
            font-weight: normal;
            padding: 5px;
            text-transform: uppercase;
            font-size:10px;
            line-height:1.3;
        }

        .invoice-box table tr.item td { 
            border-bottom: 1px solid <?=$color;?>; 
        }
        .invoice-box table tr.item1:first-child td { 
            border-bottom:1px dotted <?=$color;?>; 
        }
        .invoice-box table tr.item2:first-child td { 
            border-bottom:1px solid <?=$color;?>; 
        }
        .invoice-box table tr.item2:last-child td {
            border-top:1px dotted <?=$color;?>;  
            border-bottom:1px solid <?=$color;?>;  
        }

        .invoice-box table tr.total{ 
            font-weight: bold; 
            text-align:right; 
        }
        .invoice-box table tr.hormat{ 
            font-weight: bold; 
            text-align:left; 
        }
        .invoice-box table tr.pelanggan{ 
            font-weight: bold; 
            text-align:center; 
        }
        .invoice-box table td.total { 
            text-align:right; 
        }

        .invoice-box table td.tgl { 
            font-weight:bold; 
            border-bottom:1px dotted #000; 
        }

        /* garis-garis total / bayar */
        .invoice-box table td.total1 { 
            border-left:1px solid <?=$color;?>; 
            border-top:1px solid <?=$color;?>; 
            border-bottom:1px dotted <?=$color;?>; 
        }
        .invoice-box table td.total2 { 
            border-top:1px solid <?=$color;?>; 
            border-right:1px solid <?=$color;?>; 
            border-bottom:1px dotted <?=$color;?>; 
            text-align:right; 
            font-weight:bold; 
        }

        .invoice-box table td.lunas1 { 
            border-left:1px solid <?=$color;?>; 
            border-bottom:1px solid <?=$color;?>; 
            background:<?=$color;?>; 
            color:#fff; 
        }
        .invoice-box table td.lunas2 { 
            border-right:1px solid <?=$color;?>; 
            border-bottom:1px solid <?=$color;?>; 
            text-align:right; 
            font-weight:bold; 
            background:<?=$color;?>; 
            color:#fff; 
        }
        .invoice-box table td.umuka1 { 
            border-left:1px solid <?=$color;?>; 
            border-bottom:1px dotted <?=$color;?>; 
        }
        .invoice-box table td.umuka2 { 
            border-right:1px solid <?=$color;?>; 
            border-bottom:1px dotted <?=$color;?>; 
            text-align:right; 
            font-weight:bold; 
        }
        .invoice-box table td.sisa1 { 
            border-left:1px solid <?=$color;?>; 
            border-bottom:1px solid <?=$color;?>; 
        }
        .invoice-box table td.sisa2 { 
            border-right:1px solid <?=$color;?>; 
            border-bottom:1px solid <?=$color;?>; 
            text-align:right; 
            font-weight:bold; 
        }
        .invoice-box table td.ttd { 
            border-bottom:1px dotted <?=$color;?>; 
            text-align:center; 
            font-weight:bold; 
        }
        .invoice-box table td.border { 
            border-right:1px dotted <?=$color;?>; 
        }

        .invoice-box .table img{ 
            position: fixed; 
            z-index:-1000; 
            width:200px; 
        }
        .watermark{
            top:<?=$top;?>;
            right:4cm;
            width:4.5cm;
            height:auto;
            opacity:0.2;
            position:absolute;
            z-index:-1
        }

        .alamat {font-size:11px; line-height:1.4;}
        .sosmed {font-size:8px; line-height:1.3;}

        /* ===========================
           KOP HEADER A5 PORTRAIT
           =========================== */
        .kop{
            width:100%;
            border-collapse:collapse;
            table-layout:fixed;
            margin-bottom:6px;
        }
        .kop td{
            vertical-align:top;
            padding:6px 8px;
        }

        .brand{
            width:56%;
        }
        .brand .logo{
            max-width:220px;
            max-height:80px;
            display:block;
        }
        .brand .alamat-box{
            font-size:11px;
            line-height:1.35;
            word-wrap:break-word;
            overflow-wrap:anywhere;
            hyphens:auto;
        }

        .meta{
            width:44%;
            font-size:10px;
            line-height:1.4;
        }

        .meta .tgl{
            font-weight:bold;
            
            padding:6px 8px;
            font-size:10px;
            line-height:1.4;
        }

        .metatable{
            width:100%;
            border-collapse:collapse;
            table-layout:fixed;
            font-size:10px;
            line-height:1.4;
        }
        .metatable td{
            padding:4px 6px;
            vertical-align:top;
            word-wrap:break-word;
            overflow-wrap:anywhere;
            hyphens:auto;
        }
        .metatable td.head{
            background: <?=$color?>;
            color:#fff;
            width:34%;
            text-transform:uppercase;
            font-weight:bold;
            font-size:8px;
            line-height:1.4;
        }
        .metatable td.val{
            background: rgba(0,0,0,.04);
            color:#000;
        }

        .invno{
            font-weight:bold;
            padding:4px 8px 0 8px;
            font-size:10px;
            line-height:1.4;
        }

        /* === QC Checklist Styles (UPDATED) === */
        .qc-wrap{ 
            margin-top:10px; 
        }
        .qc-title{
            background: <?=$color;?>;
            color:#fff;
            font-weight:bold;
            padding:6px 8px;
            text-transform:uppercase;
            border:1px solid <?=$color;?>;
            border-bottom:none;
            font-size:10px;
            line-height:1.3;
        }
        .qc-table{
            width:100%;
            border:1px solid <?=$color;?>;
            border-collapse:collapse;
            font-size:10px;
            line-height:1.4;
        }
        .qc-table td,
        .qc-table th{
            
            padding:6px 8px;
            vertical-align:middle;
        }
        .qc-table tr:last-child td{
            border-bottom:none;
        }

        /* tiap item QC = checkbox di depan, teks di belakang */
        .qc-item{
            white-space:nowrap;
            vertical-align:middle;
        }
        .qc-item input[type="checkbox"]{
            margin-right:4px;
        }

        .qc-notes{
            width:100%;
        }
        .notesbox{
            min-height:60px;
            border:1px dashed <?=$color;?>;
            padding:10px;
        }
        .qc-media-wrap{
            display:flex;
            flex-wrap:wrap;
            column-gap:22px;
            row-gap:20px;
            align-items:flex-start;
        }
        .qc-media-item{
            display:flex;
            flex-direction:column;
            align-items:flex-start;
            margin-bottom:12px;
        }
        .qc-media-item img{
            height:86px;
            width:auto;
            border:1px solid <?=$color;?>;
            display:block;
        }
        .qc-media-cap{
            margin-top:8px;
            padding-bottom:6px;
            font-size:8px;
            line-height:1.3;
            white-space:nowrap;
            overflow:visible;
            text-overflow:clip;
            max-width:none;
        }

        input[type="checkbox"]{
            width:14px; 
            height:14px;
            transform: translateY(2px);
            accent-color: <?=$color;?>;
        }

        @media print{
            input[type="checkbox"]{
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
    </style>

    <?php if($html=="Y"){ ?>
    <style>
        @media print {
            @page {
                size: A5 portrait;
                margin: 0;
            }

            .invoice-box { 
                width:100%; 
                margin:auto; 
                padding:10px; 
                font-size:11px; 
                line-height:17px; 
                color:#555; 
            }
            .invoice-box table { width:100%; line-height:inherit; text-align:left; }
            .invoice-box table td { padding:0 5px; vertical-align:top; }
            .invoice-box table tr.heading td { 
                background: <?=$color;?>; 
                color:#fff; 
                padding:5px; 
                text-transform:uppercase; 
                font-size:10px;
                line-height:1.3;
            }
            .invoice-box table tr.item td{ border-bottom:1px solid #000; }
            .invoice-box table td.tgl { font-weight:bold; border-bottom:1px dotted #000; }
            .invoice-box table td.ttd { border-bottom:1px dotted #000; text-align:center; font-weight:bold; }
            .invoice-box table td.border { border-right:1px dotted #000; }

            .watermark{ 
                top:<?=$top;?>; 
                right:4cm; 
                width:4.5cm; 
                height:auto; 
                opacity:0.2; 
                z-index:-1 
            }

            /* QC print tweaks (UPDATED) */
            .qc-title{ 
                background: <?=$color;?>; 
                color:#fff; 
            }
            .qc-table{ 
                border:1px solid <?=$color;?>; 
            }
            .qc-table td,
            .qc-table th{ 
                border-bottom:1px dotted <?=$color;?>; 
            }

            /* kop print tweaks */
            .metatable td.head{
                background: <?=$color?> !important;
                color:#fff !important;
            }
            .metatable td.val{
                background: rgba(0,0,0,.06) !important;
            }
        }
    </style>
    <script type="text/javascript">
        window.print();
        window.onfocus=function(){ window.close(); }
    </script>
    <?php }
        $deskripsi = base64_decode($info['deskripsi']);
        $deskripsi = cleanString($deskripsi);

        $wa = $email = $_fb = $fb = '';
        if($info['phone']!='-'){ $_wa = '<img src="'.$_waicon.'" alt="" height="10" />'; $wa = $info['phone']; }
        if($info['email']!='-'){ $_email = '<img src="'.$_mail.'" alt="" height="10" />'; $email = $info['email']; }
        if($info['fb']!='-'){ $_fb = '<img src="'.$_fbicon.'" alt="" height="10" />'; $fb = $info['fb']; }
        $_ig =''; $ig =''; 
        if($info['ig']!='-'){ $_ig = '<img src="'.$_igicon.'" alt="" height="10" />'; $ig = $info['ig']; }

        if($konsumen['tampil']==1){
            $nama = $konsumen['perusahaan'];
            $perusahaan = cek_jenis_lembaga($konsumen['jenis']);
            $telp = $konsumen['no_telp'];
            $alamat = $konsumen['alamat_lembaga'];
        }else{
            $nama = $konsumen['nama'];
            $perusahaan = cek_jenis_lembaga($konsumen['jenis']);
            $telp = $konsumen['no_hp'];
            $alamat = $konsumen['alamat'];
        }
    ?>
</head>
<body>
<footer>
    <?=$info['title'];?> © <?php echo date("Y");?> 
</footer>

<div class="invoice-box">

    <!-- ===========================
         KOP / HEADER
         =========================== -->
    <table class="kop">
        <tr>
            <!-- Kiri: Brand / Alamat / Kontak -->
            <td class="brand">
                <img class="logo" src="<?=$logo;?>" alt="">
                <div class="alamat-box">
                    <?=$deskripsi;?><br>
                    <?=$_wa;?> <span class="sosmed"><?=$wa;?></span>
                    &nbsp;<?=$_email;?> <span class="sosmed"><?=$email;?></span>
                    &nbsp;<?=$_fb;?> <span class="sosmed"><?=$fb;?></span>
                    &nbsp;<?=$_ig;?> <span class="sosmed"><?=$ig;?></span>
                </div>
            </td>

            <!-- Kanan: Info Transaksi & Customer -->
            <td class="meta">
                <div class="tgl">
                    <?=$info['keywords'];?>, <?=date_time($cetak->tgl_ambil,true);?>
                </div>

                <table class="metatable">
                    <tr>
                        <td class="head">Kepada yth.</td>
                        <td class="val"><?=$nama;?></td>
                    </tr>
                    <tr>
                        <td class="head">Perusahaan</td>
                        <td class="val"><?=$perusahaan;?></td>
                    </tr>
                    <tr>
                        <td class="head">Telp</td>
                        <td class="val"><?=$telp;?></td>
                    </tr>
                    <tr>
                        <td class="head">Alamat</td>
                        <td class="val"><?=$alamat;?></td>
                    </tr>
                </table>
            </td>
        </tr>

        <tr>
            <td class="invno" colspan="2">
                INVOICE #<?=$cetak->id_transaksi;?>
            </td>
        </tr>
    </table>
    <!-- =========================== -->
    <!-- END KOP                     -->
    <!-- =========================== -->


    <!-- Tabel Item + Finishing -->
    <table style="width:100%;margin-top:5px" cellpadding="0" cellspacing="0">
        <tr class="heading">
            <td align="center" style="width:6%!important">QTY</td>
            <td style="width:20%!important">PRODUK</td>
            <td style="width:18%!important">BAHAN/MERK</td>
            <td align="left" style="width:10%!important">UKURAN</td>
            <td style="width:26%!important">KETERANGAN</td>
            <td style="width:20%!important">FINISHING</td>
        </tr>
        <?php 
            $no=1; 
            $totalb=0; 
            $subtotal=0; 
            $sisa=0; 
            $diskon=0; 

            foreach($detail as $val){
                $diskon = $val['jumlah'] * $val['harga'] * $val['diskon']/100;
                $totalb = $val['jumlah'] * $val['harga'] - $diskon;
                $subtotal += $totalb;

                // gabung semua finishing jadi string 1 kolom
                $finText = '';
                if(!empty($val['detail'])){
                    $__detail = json_decode($val['detail']);
                    if($__detail && isset($__detail->data) && is_array($__detail->data)){
                        $parts = [];
                        foreach($__detail->data as $_f){
                            $parts[] = isset($_f->isi) ? trim($_f->isi) : '';
                        }
                        $parts = array_filter($parts, function($x){ return $x!==''; });
                        $finText = implode(', ', $parts);
                    }
                }

                if($val['status_hitung'] == 1){
                    $qty = $val['jumlah'];
                }else{
                    $qty = $val['jumlah'].' '.get_satuan($val['satuan']);
                }
        ?>
        <tr class="item">
            <td align="center" class="border"><?=$qty;?></td>
            <td class="border"><?=$val['title'];?></td>
            <td class="border"><?=$val['nbahan'];?></td>
            <td class="border"><?=$val['ukuran'];?></td>
            <td class="border"><?=$val['keterangan'];?></td>
            <td><?=$finText;?></td>
        </tr>
        <?php 
            $no++; 
            } 
            $pajak = ($subtotal * $cetak->pajak) /100;
            $sisa = $pajak + $subtotal - $total->total;
            $cek_bayar = $pajak + $subtotal;
        ?>
    </table>

    <!-- QC CHECKLIST (UPDATED STRUCTURE) -->
    <div class="qc-wrap">
        <div class="qc-title">QC CHECKLIST</div>
        <table class="qc-table">
            <tr>
                <td class="qc-item"><input type="checkbox">Bahan</td>
                <td class="qc-item"><input type="checkbox">Ukuran</td>
                <td class="qc-item"><input type="checkbox">QTY</td>
                <td class="qc-item"><input type="checkbox">Hasil Cetak</td>
                <td class="qc-item"><input type="checkbox">Hasil Finishing</td>
            </tr>
            <tr>
                <td class="qc-notes" colspan="5">
                    <strong>Catatan:</strong><br>
                    <div class="notesbox">
                        <?php if (!empty($qc_finishing_images)): ?>
                            <div class="qc-media-wrap">
                                <?php foreach ($qc_finishing_images as $__img): ?>
                                    <div class="qc-media-item">
                                        <img src="<?= htmlspecialchars($__img['src'], ENT_QUOTES, 'UTF-8'); ?>" alt="Gambar finishing">
                                        <div class="qc-media-cap"><?= htmlspecialchars((string) $__img['info_line'], ENT_QUOTES, 'UTF-8'); ?></div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            &nbsp;
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
        </table>
    </div>
    <!-- /QC CHECKLIST -->

</div>
</body>
</html>
