<?php
$draft = is_array($draft) ? $draft : [];
$value = static function ($key, $default = '') use ($draft) { return isset($draft[$key]) ? $draft[$key] : $default; };
$checked = static function ($key) use ($draft) { return in_array($key, isset($draft['finishing']) && is_array($draft['finishing']) ? $draft['finishing'] : [], true); };
$customerName = $customer && !empty($customer->nama) ? $customer->nama : '-';
if ($customer && isset($customer->tampil) && (int)$customer->tampil === 1 && !empty($customer->perusahaan)) $customerName = $customer->perusahaan;
$date = static function ($date) { $time = $date ? strtotime($date) : false; return $time ? date('d/m/Y', $time) : '-'; };
$spkNumber = !empty($item->no_spk) ? $item->no_spk : 'SPK-'.$item->id_rincianinvoice.tgl_spk($item->tgl_trx);
$jenisCetakan = trim((string)$item->bahan);
$savedStockId = (int)$value('stock_bahan_id');
$savedMaterialName = trim((string)$value('jenis_nama_bahan'));
$savedPlanoSize = preg_replace('/\s+/', '', strtolower((string)$value('ukuran_plano')));
$autoStockChosen = false;
$finishingProcesses = isset($draft['finishing_proses']) && is_array($draft['finishing_proses']) ? $draft['finishing_proses'] : [];
$finishingProcessLabels = ['laminating'=>'LAMINATING','spot_uv'=>'SPOT UV','foil'=>'FOIL','potong_paska_cetak'=>'POTONG PASKA CETAK','pond'=>'POND','lem'=>'LEM','packing'=>'PACKING'];
$activeProcessKeys = [];
if ($checked('laminating_glossy') || $checked('laminating_doff')) $activeProcessKeys[] = 'laminating';
foreach (['spot_uv','foil','potong_paska_cetak','pond','lem','packing'] as $processKey) if ($checked($processKey)) $activeProcessKeys[] = $processKey;
$additionalPages = isset($draft['additional_pages']) && is_array($draft['additional_pages']) ? array_values($draft['additional_pages']) : [];
?>
<style>
.spk-sheet{max-width:900px;margin:auto;background:#fff;color:#303846;border:1px solid #dfe4eb;border-radius:8px;padding:24px 28px;font-family:Arial,sans-serif}.spk-sheet-title{text-align:center;font-size:25px;font-weight:700;margin:0 0 10px}.spk-plate{display:flex;justify-content:center;gap:42px;margin-bottom:11px}.spk-check-label{display:inline-flex;align-items:center;gap:7px;margin:0;cursor:pointer}.spk-check-label input{width:17px;height:17px;margin:0}.spk-sheet-row{display:grid;grid-template-columns:300px 16px minmax(0,1fr);min-height:31px;align-items:center}.spk-sheet-label{font-size:14px}.spk-sheet-colon{text-align:center}.spk-sheet-line{display:flex;align-items:center;gap:8px;min-width:0;border-bottom:1px dotted #68707c;padding:3px 6px}.spk-sheet-fixed{font-size:14px;white-space:nowrap}.spk-sheet-grow{flex:1;min-width:80px}.spk-sheet-input{width:100%;height:25px;border:0!important;outline:0!important;background:rgba(49,95,189,.045);padding:2px 6px;box-shadow:none!important}.spk-sheet-pair{display:grid;grid-template-columns:minmax(0,1fr) minmax(220px,.72fr);gap:18px;width:100%}.spk-finishing{display:grid;grid-template-columns:repeat(4,minmax(105px,1fr));gap:9px 12px;width:100%;padding:5px 0}.spk-finishing .spk-check-label{font-size:12px;white-space:nowrap}.spk-editor-bottom{margin-top:18px}.spk-cut-title{text-align:center;font-size:17px;margin-bottom:5px}.spk-cut-box{height:260px;border:3px double #858b94;padding:8px}.spk-cut-box textarea{width:100%;height:100%;border:0;resize:none;outline:0;background:#f9fafc;padding:8px}.spk-production .spk-sheet-row{grid-template-columns:220px 16px minmax(0,1fr)}.spk-note{font-size:13px;margin-top:9px}.spk-signatures{display:grid;grid-template-columns:1fr 1fr;text-align:center;margin-top:48px;gap:35px}.spk-sign-line{margin-top:58px;border-bottom:1px dotted #555;padding-bottom:2px}.spk-visual-row{display:grid;grid-template-columns:1fr 1fr;gap:16px;align-items:stretch;margin-top:18px}.spk-visual-row>div{min-width:0}.spk-visual-row .spk-image-upload{height:100%;margin-top:0}.spk-visual-row .spk-image-drop{min-height:205px}.spk-visual-row .spk-image-preview img{max-height:215px}@media(max-width:768px){.spk-sheet{padding:18px;min-width:760px}.spk-editor-scroll{overflow-x:auto}.spk-sheet-row{grid-template-columns:270px 16px minmax(0,1fr)}}
.spk-sheet-pair{grid-template-columns:minmax(0,1fr) auto;align-items:center}.spk-sheet-pair>span:last-child{white-space:nowrap}.spk-finishing{grid-template-columns:minmax(0,1.45fr) minmax(0,1.28fr) minmax(0,.78fr) minmax(0,.62fr);column-gap:10px;row-gap:9px}.spk-finishing .spk-check-label{display:grid;grid-template-columns:17px minmax(0,1fr);align-items:center;column-gap:6px;font-size:11px;line-height:14px;white-space:nowrap;min-width:0}.spk-finishing .spk-check-label input{position:static;display:block;margin:0}
.spk-plano-pair{display:grid;grid-template-columns:minmax(100px,1fr) 235px;gap:16px;width:100%;align-items:center}.spk-plano-size{display:grid;grid-template-columns:auto minmax(80px,1fr);gap:7px;align-items:center;white-space:nowrap}
.spk-paper-pair{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(150px,.85fr);gap:14px;width:100%;align-items:center}.spk-paper-field{display:grid;grid-template-columns:auto minmax(70px,1fr);gap:7px;align-items:center;white-space:nowrap}
.spk-cut-tools{display:grid;grid-template-columns:repeat(3,1fr);gap:5px;margin-bottom:7px}.spk-cut-mode{border:1px solid #cfd6e4;background:#fff;border-radius:5px;padding:5px 3px;font-size:10px}.spk-cut-mode.is-active{background:#4f46e5;border-color:#4f46e5;color:#fff}.spk-cut-settings{display:grid;grid-template-columns:1fr 1fr;gap:7px;margin-bottom:7px}.spk-cut-settings label{font-size:9px;text-align:left;margin:0}.spk-cut-settings input{width:100%;height:24px;border:1px solid #d6dce7;padding:2px 5px}.spk-cut-map-wrap{height:150px;background:#fbfcff;border:1px dashed #cdd6e8;padding:5px}.spk-cut-map{width:100%;height:100%;display:block}.spk-cut-stats{display:flex;justify-content:space-between;gap:5px;margin-top:6px;font-size:9px;font-weight:700}.spk-cut-error{font-size:10px;color:#c0392b;padding:45px 5px;text-align:center}
.spk-cut-box{height:225px}.spk-image-upload{margin-top:18px;border:1px solid #dbe2ec;border-radius:8px;padding:12px;background:#fbfcfe}.spk-image-upload-title{font-size:13px;font-weight:700;margin-bottom:8px}.spk-image-drop{min-height:115px;border:2px dashed #b9c5d8;border-radius:8px;display:flex;align-items:center;justify-content:center;text-align:center;padding:12px;cursor:pointer;transition:.2s;background:#fff}.spk-image-drop:hover,.spk-image-drop.is-dragging{border-color:#4f46e5;background:#f4f3ff}.spk-image-drop i{font-size:24px;color:#4f46e5;display:block;margin-bottom:5px}.spk-image-drop small{display:block;color:#7b8495;margin-top:3px}.spk-image-preview{display:none;position:relative;min-height:150px;text-align:center}.spk-image-preview.is-visible{display:block}.spk-image-preview img{max-width:100%;max-height:260px;border-radius:6px;box-shadow:0 3px 12px rgba(30,41,59,.12)}.spk-image-actions{display:flex;justify-content:center;gap:8px;margin-top:9px}
.spk-finish-processes{margin-top:4px}.spk-finish-process{border-top:1px solid #e6e9ef;padding-top:3px;margin-top:3px}.spk-finish-process-title{font-size:11px;font-weight:700;color:#4f46e5;margin:2px 0 1px}
.spk-visual-row .spk-cut-panel,.spk-visual-row .spk-image-upload{box-sizing:border-box;height:100%}.spk-visual-row .spk-cut-panel{display:flex;flex-direction:column;border:1px solid #dbe2ec;border-radius:8px;padding:12px;background:#fbfcfe}.spk-visual-row .spk-cut-title{text-align:left;font-size:13px;font-weight:700;margin-bottom:8px}.spk-visual-row .spk-cut-box{height:auto;min-height:225px;flex:1;background:#fff}
.spk-additional-section{margin-top:18px;border-top:1px solid #e4e8ef;padding-top:16px}.spk-additional-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:10px}.spk-additional-head h3{font-size:15px;font-weight:700;margin:0}.spk-add-page{border:1px solid #4f46e5;background:#fff;color:#4f46e5;border-radius:7px;padding:7px 12px;font-weight:600}.spk-add-page:hover{background:#4f46e5;color:#fff}.spk-additional-actions{display:flex;justify-content:flex-end;margin-top:12px}.spk-extra-page{border:1px solid #dbe2ec;border-radius:9px;background:#fbfcfe;padding:14px;margin-top:10px}.spk-extra-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:9px}.spk-extra-title{font-size:14px;font-weight:700;color:#303846}.spk-remove-page{border:0;background:#fff1f2;color:#dc2626;border-radius:6px;padding:5px 9px}.spk-extra-fields{display:grid;grid-template-columns:1fr 1fr;gap:8px 14px}.spk-extra-field label{display:block;font-size:10px;font-weight:700;color:#667085;margin-bottom:3px}.spk-extra-field input,.spk-extra-field select{width:100%;height:31px;border:1px solid #d6dce7;border-radius:5px;background:#fff;padding:3px 7px}.spk-extra-cut{margin-top:11px;border:1px solid #dbe2ec;border-radius:7px;padding:9px;background:#fff}.spk-extra-cut .spk-cut-map-wrap{height:175px}.spk-extra-empty{text-align:center;color:#7b8495;padding:14px;border:1px dashed #d5dbe6;border-radius:8px}
.spk-extra-document{background:#fff;border:1px solid #dfe4eb;border-radius:8px;padding:22px}.spk-extra-summary{font-size:12px;line-height:1.8;border-bottom:1px dotted #8b93a1;margin-bottom:12px}.spk-extra-finishing{margin-top:13px}.spk-extra-production{display:grid;grid-template-columns:repeat(3,1fr);gap:9px;margin-top:12px}.spk-extra-processes{display:grid;grid-template-columns:1fr 1fr;gap:9px;margin-top:10px}.spk-extra-process-card{border:1px solid #dbe2ec;border-radius:6px;padding:8px}.spk-extra-process-card b{font-size:11px;color:#4f46e5}.spk-extra-reference{margin-top:10px;border:1px solid #dbe2ec;border-radius:7px;padding:12px;text-align:center}.spk-extra-reference-drop{min-height:125px;border:2px dashed #b9c5d8;border-radius:8px;margin-top:8px;display:flex;align-items:center;justify-content:center;cursor:pointer;background:#fff}.spk-extra-reference-drop:hover,.spk-extra-reference-drop.is-dragging{border-color:#4f46e5;background:#f4f3ff}.spk-extra-reference-preview{display:none;margin-top:8px}.spk-extra-reference-preview.is-visible{display:block}.spk-extra-reference-preview img{max-width:100%;max-height:220px;border-radius:6px}.spk-extra-reference-actions{display:flex;justify-content:center;gap:7px;margin-top:7px}.spk-extra-reference small{color:#7b8495;display:block}
</style>
<div class="spk-editor-scroll"><div class="spk-sheet">
  <input type="hidden" name="detail_id" value="<?=(int)$item->id_rincianinvoice;?>">
  <h2 class="spk-sheet-title">SURAT PERINTAH KERJA</h2>
  <div class="spk-plate">
    <label class="spk-check-label"><input type="radio" name="plat" value="baru" <?=$value('plat')==='baru'?'checked':'';?>> PLAT BARU</label>
    <label class="spk-check-label"><input type="radio" name="plat" value="lama" <?=$value('plat')==='lama'?'checked':'';?>> PLAT LAMA</label>
    <label class="spk-check-label"><input type="radio" name="plat" value="tanpa" <?=$value('plat')==='tanpa'?'checked':'';?>> TANPA CETAK / PLAT</label>
  </div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">NO. SPK</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><span class="spk-sheet-fixed"><?=html_escape($spkNumber);?></span><span class="spk-sheet-grow"></span><span class="spk-sheet-fixed">NO. ORDER : <?=html_escape($item->id_transaksi);?></span></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">NAMA PELANGGAN</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><span class="spk-sheet-fixed"><?=html_escape($customerName);?></span></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">TANGGAL ORDER</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><div class="spk-sheet-pair"><span><?=html_escape($date($item->tgl_trx));?></span><span>TANGGAL DEADLINE : <?=html_escape($date($item->tgl_ambil));?></span></div></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">JENIS CETAKAN</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><span class="spk-sheet-fixed"><?=html_escape($jenisCetakan);?></span><span class="spk-sheet-grow"></span><span class="spk-sheet-fixed">QTY : <?=html_escape($item->jumlah);?> Set</span></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">KETERANGAN</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="keterangan" value="<?=html_escape($value('keterangan'));?>"></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">JENIS / NAMA BAHAN</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><select class="spk-sheet-input" name="stock_bahan_id" required><option value="">Pilih bahan dari data stok</option><?php foreach ((isset($stockMaterials) && is_array($stockMaterials) ? $stockMaterials : []) as $stock): $stockSize=preg_replace('/\s+/', '', strtolower((string)$stock->varian_ukuran)); $selectedStock=$savedStockId===(int)$stock->id; if(!$selectedStock && !$savedStockId && !$autoStockChosen && $savedMaterialName!=='' && stripos($stock->title,$savedMaterialName)===0 && $savedPlanoSize!=='' && $stockSize===$savedPlanoSize){$selectedStock=true;$autoStockChosen=true;} ?><option value="<?=(int)$stock->id;?>" data-size="<?=html_escape($stock->varian_ukuran);?>" <?=$selectedStock?'selected':'';?>><?=html_escape($stock->title);?> — Stok: <?=number_format((float)$stock->total_stok,0,',','.');?> <?=html_escape($stock->satuan);?></option><?php endforeach; ?></select></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">JUMLAH BAHAN PLANO</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="jumlah_bahan_plano" value="<?=html_escape($value('jumlah_bahan_plano'));?>"></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">UKURAN PLANO</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="ukuran_plano" value="<?=html_escape($value('ukuran_plano'));?>"></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">UKURAN POTONG KERTAS MASUK MESIN</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="ukuran_kertas_masuk" placeholder="" value="<?=html_escape($value('ukuran_kertas_masuk', $value('ukuran_jumlah_kertas')));?>"></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">JUMLAH KERTAS MASUK MESIN</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="jumlah_kertas_masuk" readonly title="Dihitung otomatis: jumlah bahan plano × hasil potong per plano" value="<?=html_escape($value('jumlah_kertas_masuk'));?>"><span>LEMBAR</span></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">MESIN CETAK</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="mesin_cetak" value="<?=html_escape($value('mesin_cetak'));?>"></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">JUMLAH PLAT</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="jumlah_plat" value="<?=html_escape($value('jumlah_plat'));?>"></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">WARNA CETAKAN</span><span class="spk-sheet-colon">:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="warna_cetakan" value="<?=html_escape($value('warna_cetakan'));?>"></div></div>
  <div class="spk-sheet-row"><span class="spk-sheet-label">FINISHING</span><span class="spk-sheet-colon">:</span><div class="spk-finishing">
    <?php foreach (['laminating_glossy'=>'LAMINATING GLOSSY','laminating_doff'=>'LAMINATING DOFF','spot_uv'=>'SPOT UV','foil'=>'FOIL','potong_paska_cetak'=>'POTONG PASKA CETAK','pond'=>'POND','lem'=>'LEM','packing'=>'PACKING'] as $key=>$label): ?>
    <label class="spk-check-label"><input type="checkbox" name="finishing[]" value="<?=$key;?>" <?=$checked($key)?'checked':'';?>> <?=html_escape($label);?></label>
    <?php endforeach; ?>
  </div></div>
  <div class="spk-editor-bottom">
    <div class="spk-production">
      <div class="spk-sheet-row"><span>MULAI CETAK</span><span>:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="mulai_cetak" value="<?=html_escape($value('mulai_cetak'));?>"></div></div>
      <div class="spk-sheet-row"><span>SELESAI CETAK</span><span>:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="selesai_cetak" value="<?=html_escape($value('selesai_cetak'));?>"></div></div>
      <div class="spk-sheet-row"><span>HASIL AKHIR CETAK</span><span>:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="hasil_akhir" value="<?=html_escape($value('hasil_akhir'));?>"><span>LEMBAR</span></div></div>
      <div class="spk-finish-processes" id="spkFinishProcesses"><?php foreach ($activeProcessKeys as $processKey): $processValue=isset($finishingProcesses[$processKey])&&is_array($finishingProcesses[$processKey])?$finishingProcesses[$processKey]:[]; ?><div class="spk-finish-process" data-process="<?=html_escape($processKey);?>"><div class="spk-finish-process-title"><?=html_escape($finishingProcessLabels[$processKey]);?></div><?php foreach (['mulai'=>'MULAI','selesai'=>'SELESAI','hasil'=>'HASIL AKHIR'] as $fieldKey=>$fieldLabel): ?><div class="spk-sheet-row"><span><?=$fieldLabel;?> <?=html_escape($finishingProcessLabels[$processKey]);?></span><span>:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="finishing_proses[<?=html_escape($processKey);?>][<?=$fieldKey;?>]" value="<?=html_escape(isset($processValue[$fieldKey])?$processValue[$fieldKey]:'');?>"><?php if($fieldKey==='hasil'): ?><span>LEMBAR</span><?php endif; ?></div></div><?php endforeach; ?></div><?php endforeach; ?></div>
    </div>
  </div>
  <?php $existingSpkImage=trim((string)$value('gambar_spk')); ?>
  <div class="spk-visual-row">
  <div class="spk-cut-panel"><div class="spk-cut-title">CARA POTONG KERTAS</div><div class="spk-cut-box">
    <div class="spk-cut-tools"><button type="button" class="spk-cut-mode" data-mode="auto">AUTO</button><button type="button" class="spk-cut-mode" data-mode="portrait">POTRET</button><button type="button" class="spk-cut-mode" data-mode="landscape">LANSKAP</button></div>
    <input type="hidden" name="potong_margin" value="0"><input type="hidden" name="potong_gap" value="0">
    <div class="spk-cut-map-wrap"><svg class="spk-cut-map" id="spkCutMap" xmlns="http://www.w3.org/2000/svg"></svg></div>
    <div class="spk-cut-stats"><span id="spkCutCount">0 potong/plano</span><span id="spkCutUsed">0% terpakai</span><span id="spkCutNeed">0 plano</span></div>
    <input type="hidden" name="potong_mode" value="<?=html_escape($value('potong_mode','auto'));?>"><input type="hidden" name="cara_potong" value="<?=html_escape($value('cara_potong'));?>"><input type="hidden" name="cara_potong_svg" value="<?=html_escape($value('cara_potong_svg'));?>">
  </div></div>
  <div class="spk-image-upload">
    <div class="spk-image-upload-title"><i class="fa fa-image mr-1"></i> GAMBAR REFERENSI SPK</div>
    <input type="file" name="gambar_spk" id="spkImageInput" accept="image/jpeg,image/png,image/webp" hidden>
    <input type="hidden" name="gambar_hapus" value="0">
    <div class="spk-image-drop" id="spkImageDrop" <?=$existingSpkImage!==''?'style="display:none"':'';?>>
      <div><i class="fa fa-cloud-upload"></i><b>Klik atau tarik gambar ke area ini</b><small>JPG, PNG, atau WebP — maksimal 5 MB. Otomatis dikonversi menjadi WebP.</small></div>
    </div>
    <div class="spk-image-preview <?=$existingSpkImage!==''?'is-visible':'';?>" id="spkImagePreview"><img alt="Preview gambar SPK" src="<?=$existingSpkImage!==''?html_escape(base_url($existingSpkImage)):'';?>"><div class="spk-image-actions"><button type="button" class="btn btn-sm btn-outline-primary" id="spkImageChange"><i class="fa fa-refresh"></i> Ganti</button><button type="button" class="btn btn-sm btn-outline-danger" id="spkImageRemove"><i class="fa fa-trash"></i> Hapus</button></div></div>
  </div>
  </div>
  <div class="spk-additional-section">
    <div class="spk-additional-head"><div><h3>HALAMAN BAHAN TAMBAHAN</h3><small>Tambahkan bila produk ini memakai bahan stok atau pola potong lain.</small></div></div>
    <div id="spkAdditionalPages"><div class="spk-extra-empty">Belum ada halaman bahan tambahan.</div></div>
    <div class="spk-additional-actions"><button type="button" class="spk-add-page" data-add-spk-page><i class="fa fa-plus"></i> Tambah Halaman</button></div>
  </div>
</div></div>
<script>
(function(){
 var root=document.getElementById('formSpkItemEditor'); if(!root)return;
 var svg=root.querySelector('#spkCutMap'), modeInput=root.querySelector('[name="potong_mode"]'), summary=root.querySelector('[name="cara_potong"]'), svgInput=root.querySelector('[name="cara_potong_svg"]');
 function nums(value){var m=String(value||'').replace(/,/g,'.').match(/\d+(?:\.\d+)?/g);return m&&m.length>1?[parseFloat(m[0]),parseFloat(m[1])]:null}
 function val(name,fallback){var el=root.querySelector('[name="'+name+'"]'),n=parseFloat(String(el&&el.value||'').replace(',','.'));return isFinite(n)&&n>=0?n:fallback}
 function fit(area,piece,gap){return piece>0&&area>=piece?Math.floor((area+gap)/(piece+gap)):0}
 function grid(pw,ph,cw,ch,margin,gap,type){var aw=Math.max(0,pw-margin*2),ah=Math.max(0,ph-margin*2),cols=fit(aw,cw,gap),rows=fit(ah,ch,gap),pieces=[];for(var r=0;r<rows;r++)for(var c=0;c<cols;c++)pieces.push({x:margin+c*(cw+gap),y:margin+r*(ch+gap),w:cw,h:ch,type:type});return{pieces:pieces,count:pieces.length,label:type}}
 function mixed(pw,ph,cw,ch,margin,gap,vertical,firstLandscape){var inner={x:margin,y:margin,w:Math.max(0,pw-margin*2),h:Math.max(0,ph-margin*2)},a=firstLandscape?{w:ch,h:cw,t:'landscape'}:{w:cw,h:ch,t:'portrait'},b=firstLandscape?{w:cw,h:ch,t:'portrait'}:{w:ch,h:cw,t:'landscape'},best=null,max=vertical?fit(inner.w,a.w,gap):fit(inner.h,a.h,gap);for(var n=1;n<=max;n++){var pcs=[],used=n*(vertical?a.w:a.h)+Math.max(0,n-1)*gap,cols=vertical?n:fit(inner.w,a.w,gap),rows=vertical?fit(inner.h,a.h,gap):n;for(var r=0;r<rows;r++)for(var c=0;c<cols;c++)pcs.push({x:inner.x+c*(a.w+gap),y:inner.y+r*(a.h+gap),w:a.w,h:a.h,type:a.t});var area=vertical?{x:inner.x+used+gap,y:inner.y,w:inner.w-used-gap,h:inner.h}:{x:inner.x,y:inner.y+used+gap,w:inner.w,h:inner.h-used-gap};var bc=fit(area.w,b.w,gap),br=fit(area.h,b.h,gap);for(var rr=0;rr<br;rr++)for(var cc=0;cc<bc;cc++)pcs.push({x:area.x+cc*(b.w+gap),y:area.y+rr*(b.h+gap),w:b.w,h:b.h,type:b.t});if(!best||pcs.length>best.count)best={pieces:pcs,count:pcs.length,label:'Kombinasi'};}return best}
 function choose(pw,ph,cw,ch,margin,gap,mode){var p=grid(pw,ph,cw,ch,margin,gap,'Potret'),l=grid(pw,ph,ch,cw,margin,gap,'Lanskap');if(mode==='portrait')return p;if(mode==='landscape')return l;var all=[p,l,mixed(pw,ph,cw,ch,margin,gap,true,false),mixed(pw,ph,cw,ch,margin,gap,true,true),mixed(pw,ph,cw,ch,margin,gap,false,false),mixed(pw,ph,cw,ch,margin,gap,false,true)].filter(Boolean);all.sort(function(a,b){return b.count-a.count});return all[0]}
 var extraStocks=<?=json_encode(array_map(static function($stock){return ['id'=>(int)$stock->id,'title'=>(string)$stock->title,'size'=>(string)$stock->varian_ukuran,'stock'=>(float)$stock->total_stok,'unit'=>(string)$stock->satuan];},isset($stockMaterials)&&is_array($stockMaterials)?$stockMaterials:[]),JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT);?>;
 var savedExtraPages=<?=json_encode($additionalPages,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT);?>,extraIndex=0,extraBox=root.querySelector('#spkAdditionalPages');
 function esc(v){var d=document.createElement('div');d.textContent=v==null?'':String(v);return d.innerHTML}
 function extraOptions(selected){var html='<option value="">Pilih bahan dari data stok</option>';extraStocks.forEach(function(s){html+='<option value="'+s.id+'" data-size="'+esc(s.size)+'" '+(String(selected||'')===String(s.id)?'selected':'')+'>'+esc(s.title)+' — Stok: '+Number(s.stock||0).toLocaleString('id-ID')+' '+esc(s.unit)+'</option>'});return html}
 var pageMeta={spk:<?=json_encode($spkNumber);?>,order:<?=json_encode($item->id_transaksi);?>,customer:<?=json_encode($customerName);?>,orderDate:<?=json_encode($date($item->tgl_trx));?>,deadline:<?=json_encode($date($item->tgl_ambil));?>,product:<?=json_encode($jenisCetakan);?>,qty:<?=json_encode($item->jumlah);?>};
 var finishLabels={laminating_glossy:'LAMINATING GLOSSY',laminating_doff:'LAMINATING DOFF',spot_uv:'SPOT UV',foil:'FOIL',potong_paska_cetak:'POTONG PASKA CETAK',pond:'POND',lem:'LEM',packing:'PACKING'};
 function field(i,key,label,value,readonly){return '<div class="spk-extra-field"><label>'+label+'</label><input name="additional_pages['+i+']['+key+']" '+(readonly?'readonly':'')+' value="'+esc(value||'')+'"></div>'}
 function extraMarkup(i,d){d=d||{};var mode=d.potong_mode||'auto',fin=Array.isArray(d.finishing)?d.finishing:[],html='<div class="spk-extra-page" data-extra-page><div class="spk-extra-head"><span class="spk-extra-title">HALAMAN TAMBAHAN</span><button type="button" class="spk-remove-page"><i class="fa fa-trash"></i> Hapus</button></div><div class="spk-extra-document"><h2 class="spk-sheet-title">SURAT PERINTAH KERJA</h2><div class="spk-plate"><label class="spk-check-label"><input type="radio" name="additional_pages['+i+'][plat]" value="baru" '+((d.plat||'baru')==='baru'?'checked':'')+'> PLAT BARU</label><label class="spk-check-label"><input type="radio" name="additional_pages['+i+'][plat]" value="lama" '+(d.plat==='lama'?'checked':'')+'> PLAT LAMA</label><label class="spk-check-label"><input type="radio" name="additional_pages['+i+'][plat]" value="tanpa" '+(d.plat==='tanpa'?'checked':'')+'> TANPA CETAK / PLAT</label></div><div class="spk-extra-summary"><b>NO. SPK:</b> '+esc(pageMeta.spk)+' &nbsp; <b>NO. ORDER:</b> '+esc(pageMeta.order)+'<br><b>NAMA PELANGGAN:</b> '+esc(pageMeta.customer)+' &nbsp; <b>TANGGAL:</b> '+esc(pageMeta.orderDate)+' / '+esc(pageMeta.deadline)+'<br><b>JENIS CETAKAN:</b> '+esc(pageMeta.product)+' &nbsp; <b>QTY:</b> '+esc(pageMeta.qty)+' Set</div><div class="spk-extra-fields">';
 html+=field(i,'keterangan','KETERANGAN',d.keterangan)+ '<div class="spk-extra-field"><label>JENIS / NAMA BAHAN</label><select name="additional_pages['+i+'][stock_bahan_id]" required>'+extraOptions(d.stock_bahan_id)+'</select></div>'+field(i,'jumlah_bahan_plano','JUMLAH BAHAN PLANO',d.jumlah_bahan_plano)+field(i,'ukuran_plano','UKURAN PLANO',d.ukuran_plano)+field(i,'ukuran_kertas_masuk','UKURAN POTONG KERTAS MASUK MESIN',d.ukuran_kertas_masuk)+'<div class="spk-extra-field"><label>JUMLAH KERTAS MASUK MESIN</label><input data-role="total" name="additional_pages['+i+'][jumlah_kertas_masuk]" readonly value="'+esc(d.jumlah_kertas_masuk||'')+'"></div>'+field(i,'mesin_cetak','MESIN CETAK',d.mesin_cetak)+field(i,'jumlah_plat','JUMLAH PLAT',d.jumlah_plat)+field(i,'warna_cetakan','WARNA CETAKAN',d.warna_cetakan)+'</div><div class="spk-extra-finishing"><b>FINISHING</b><div class="spk-finishing">';
 Object.keys(finishLabels).forEach(function(key){html+='<label class="spk-check-label"><input type="checkbox" name="additional_pages['+i+'][finishing][]" value="'+key+'" '+(fin.indexOf(key)>-1?'checked':'')+'> '+finishLabels[key]+'</label>'});
 html+='</div></div><div class="spk-extra-production">'+field(i,'mulai_cetak','MULAI CETAK',d.mulai_cetak)+field(i,'selesai_cetak','SELESAI CETAK',d.selesai_cetak)+field(i,'hasil_akhir','HASIL AKHIR CETAK',d.hasil_akhir)+'</div><div class="spk-extra-processes" data-role="processes"></div><div class="spk-extra-cut"><div class="spk-cut-title">CARA POTONG KERTAS</div><div class="spk-cut-tools"><button type="button" class="spk-cut-mode" data-mode="auto">AUTO</button><button type="button" class="spk-cut-mode" data-mode="portrait">POTRET</button><button type="button" class="spk-cut-mode" data-mode="landscape">LANSKAP</button></div><input type="hidden" data-role="mode" name="additional_pages['+i+'][potong_mode]" value="'+esc(mode)+'"><input type="hidden" data-role="summary" name="additional_pages['+i+'][cara_potong]" value="'+esc(d.cara_potong||'')+'"><input type="hidden" data-role="svg-value" name="additional_pages['+i+'][cara_potong_svg]" value=""><div class="spk-cut-map-wrap"><svg class="spk-cut-map" data-role="map" xmlns="http://www.w3.org/2000/svg"></svg></div><div class="spk-cut-stats"><span data-role="count">0 potong/plano</span><span data-role="used">0% terpakai</span><span data-role="plano">0 plano</span></div></div><div class="spk-extra-reference"><b>GAMBAR REFERENSI SPK</b><small>Mengikuti gambar referensi SPK utama.</small></div></div></div>';return html}
 function renumberExtras(){var cards=extraBox.querySelectorAll('[data-extra-page]');cards.forEach(function(card,n){card.querySelector('.spk-extra-title').textContent='HALAMAN TAMBAHAN '+(n+2)});var empty=extraBox.querySelector('.spk-extra-empty');if(!cards.length&&!empty)extraBox.innerHTML='<div class="spk-extra-empty">Belum ada halaman bahan tambahan.</div>';else if(cards.length&&empty)empty.remove()}
 function initExtra(card){var select=card.querySelector('select'),planoInput=card.querySelector('[name$="[ukuran_plano]"]'),cutInput=card.querySelector('[name$="[ukuran_kertas_masuk]"]'),qtyInput=card.querySelector('[name$="[jumlah_bahan_plano]"]'),total=card.querySelector('[data-role="total"]'),map=card.querySelector('[data-role="map"]'),modeInputExtra=card.querySelector('[data-role="mode"]'),summaryExtra=card.querySelector('[data-role="summary"]'),svgValue=card.querySelector('[data-role="svg-value"]');function draw(){var plano=nums(planoInput.value),cut=nums(cutInput.value),jumlah=Math.max(0,Math.floor(parseFloat(String(qtyInput.value||0).replace(',','.'))||0)),mode=modeInputExtra.value||'auto';card.querySelectorAll('.spk-cut-mode').forEach(function(b){b.classList.toggle('is-active',b.dataset.mode===mode)});if(!plano||!cut){map.innerHTML='<text x="50%" y="50%" text-anchor="middle" fill="#b42318" font-size="6">Isi ukuran plano dan ukuran potong</text>';total.value='';return}var layout=choose(plano[0],plano[1],cut[0],cut[1],0,0,mode),used=layout.count*cut[0]*cut[1]/(plano[0]*plano[1])*100,ns='http://www.w3.org/2000/svg';map.setAttribute('viewBox','0 0 '+plano[0]+' '+plano[1]);map.innerHTML='<defs><pattern id="w'+card.dataset.extraIndex+'" width="5" height="5" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><line y2="5" stroke="#f43f5e" stroke-width=".35" opacity=".4"/></pattern></defs><rect width="'+plano[0]+'" height="'+plano[1]+'" fill="url(#w'+card.dataset.extraIndex+')" stroke="#f43f5e" stroke-width=".6" stroke-dasharray="2 1"/>';layout.pieces.forEach(function(p,n){var r=document.createElementNS(ns,'rect'),t=document.createElementNS(ns,'text');[['x',p.x],['y',p.y],['width',p.w],['height',p.h]].forEach(function(a){r.setAttribute(a[0],a[1])});r.setAttribute('fill',p.type==='landscape'?'rgba(244,63,94,.12)':'rgba(79,70,229,.12)');r.setAttribute('stroke',p.type==='landscape'?'#f43f5e':'#4f46e5');r.setAttribute('stroke-width','.5');t.setAttribute('x',p.x+p.w/2);t.setAttribute('y',p.y+p.h/2);t.setAttribute('text-anchor','middle');t.setAttribute('dominant-baseline','middle');t.setAttribute('font-size',Math.max(3,Math.min(p.w,p.h)*.18));t.textContent=n+1;map.appendChild(r);map.appendChild(t)});var result=layout.count*jumlah;total.value=result;card.querySelector('[data-role="count"]').textContent=layout.count+' potong/plano';card.querySelector('[data-role="used"]').textContent=used.toFixed(1)+'% terpakai';card.querySelector('[data-role="plano"]').textContent=jumlah+' plano';summaryExtra.value=layout.label+'; '+layout.count+' potong/plano × '+jumlah+' plano = '+result+' lembar';svgValue.value=new XMLSerializer().serializeToString(map)}select.addEventListener('change',function(){var o=this.options[this.selectedIndex];if(o&&o.dataset.size){planoInput.value=o.dataset.size;draw()}});[planoInput,cutInput,qtyInput].forEach(function(el){el.addEventListener('input',draw)});card.querySelectorAll('.spk-cut-mode').forEach(function(b){b.addEventListener('click',function(){modeInputExtra.value=b.dataset.mode;draw()})});card.querySelector('.spk-remove-page').addEventListener('click',function(){card.remove();renumberExtras()});draw()}
 function processKeyForFinish(key){return key.indexOf('laminating_')===0?'laminating':key}
 function renderExtraProcesses(card,d){var i=card.dataset.extraIndex,box=card.querySelector('[data-role="processes"]'),selected={};card.querySelectorAll('[name*="[finishing][]"]:checked').forEach(function(el){selected[processKeyForFinish(el.value)]=true});box.innerHTML='';Object.keys(selected).forEach(function(key){var label=key.replace(/_/g,' ').toUpperCase(),vals=d&&d.finishing_proses&&d.finishing_proses[key]||{};box.insertAdjacentHTML('beforeend','<div class="spk-extra-process-card"><b>'+label+'</b>'+field(i,'finishing_proses]['+key+'][mulai','MULAI '+label,vals.mulai)+field(i,'finishing_proses]['+key+'][selesai','SELESAI '+label,vals.selesai)+field(i,'finishing_proses]['+key+'][hasil','HASIL AKHIR '+label,vals.hasil)+'</div>')})}
 function initExtraImage(card,d){var i=card.dataset.extraIndex,box=card.querySelector('.spk-extra-reference'),has=!!(d&&d.gambar_spk),url=has?<?=json_encode(base_url());?>+d.gambar_spk:'';box.innerHTML='<b>GAMBAR REFERENSI SPK</b><input type="file" name="additional_image_'+i+'" data-role="image-input" accept="image/jpeg,image/png,image/webp" hidden><input type="hidden" name="additional_pages['+i+'][gambar_hapus]" data-role="image-remove" value="0"><div class="spk-extra-reference-drop" data-role="image-drop" '+(has?'style="display:none"':'')+'><div><i class="fa fa-cloud-upload"></i><b> Klik atau tarik gambar</b><small>JPG, PNG, atau WebP — maksimal 5 MB. Otomatis menjadi WebP.</small></div></div><div class="spk-extra-reference-preview '+(has?'is-visible':'')+'" data-role="image-preview"><img src="'+esc(url)+'"><div class="spk-extra-reference-actions"><button type="button" class="btn btn-sm btn-outline-primary" data-role="image-change">Ganti</button><button type="button" class="btn btn-sm btn-outline-danger" data-role="image-delete">Hapus</button></div></div>';var input=box.querySelector('[data-role="image-input"]'),drop=box.querySelector('[data-role="image-drop"]'),preview=box.querySelector('[data-role="image-preview"]'),img=preview.querySelector('img'),remove=box.querySelector('[data-role="image-remove"]');function setFile(file){if(!file)return;if(!/^image\/(jpeg|png|webp)$/i.test(file.type)){alert('Format gambar harus JPG, PNG, atau WebP.');return}if(file.size>5*1024*1024){alert('Ukuran gambar maksimal 5 MB.');return}var transfer=new DataTransfer();transfer.items.add(file);input.files=transfer.files;remove.value='0';var reader=new FileReader();reader.onload=function(e){img.src=e.target.result;preview.classList.add('is-visible');drop.style.display='none'};reader.readAsDataURL(file)}drop.addEventListener('click',function(){input.click()});drop.addEventListener('dragover',function(e){e.preventDefault();drop.classList.add('is-dragging')});drop.addEventListener('dragleave',function(){drop.classList.remove('is-dragging')});drop.addEventListener('drop',function(e){e.preventDefault();drop.classList.remove('is-dragging');setFile(e.dataTransfer.files[0])});input.addEventListener('change',function(){setFile(this.files[0])});box.querySelector('[data-role="image-change"]').addEventListener('click',function(){input.click()});box.querySelector('[data-role="image-delete"]').addEventListener('click',function(){input.value='';remove.value='1';img.src='';preview.classList.remove('is-visible');drop.style.display='flex'})}
 function addExtra(d){var i=extraIndex++;extraBox.insertAdjacentHTML('beforeend',extraMarkup(i,d));var card=extraBox.lastElementChild;card.dataset.extraIndex=i;initExtra(card);renderExtraProcesses(card,d);initExtraImage(card,d);card.querySelectorAll('[name*="[finishing][]"]').forEach(function(el){el.addEventListener('change',function(){renderExtraProcesses(card,{})})});renumberExtras()}
 function inputValue(scope,name){var el=scope.querySelector('[name="'+name+'"]');return el?el.value:''}
 function cloneMainPage(){var d={};['plat','keterangan','stock_bahan_id','jumlah_bahan_plano','ukuran_plano','ukuran_kertas_masuk','jumlah_kertas_masuk','mesin_cetak','jumlah_plat','warna_cetakan','mulai_cetak','selesai_cetak','hasil_akhir','potong_mode'].forEach(function(key){d[key]=inputValue(root,key)});d.finishing=[];root.querySelectorAll('[name="finishing[]"]:checked').forEach(function(el){d.finishing.push(el.value)});d.finishing_proses={};root.querySelectorAll('[name^="finishing_proses["]').forEach(function(el){var m=el.name.match(/^finishing_proses\[([^\]]+)\]\[([^\]]+)\]$/);if(m){d.finishing_proses[m[1]]=d.finishing_proses[m[1]]||{};d.finishing_proses[m[1]][m[2]]=el.value}});return d}
 function cloneExtraPage(card){var d={finishing:[],finishing_proses:{}};card.querySelectorAll('input,select').forEach(function(el){var m=el.name&&el.name.match(/^additional_pages\[\d+\]\[([^\]]+)\](?:\[([^\]]*)\])?(?:\[([^\]]*)\])?$/);if(!m)return;if(m[1]==='finishing'&&el.checked)d.finishing.push(el.value);else if(m[1]==='finishing_proses'&&m[2]&&m[3]){d.finishing_proses[m[2]]=d.finishing_proses[m[2]]||{};d.finishing_proses[m[2]][m[3]]=el.value}else if((el.type!=='radio'&&el.type!=='checkbox')||el.checked)d[m[1]]=el.value});return d}
 function addNextExtraPage(){var cards=extraBox.querySelectorAll('[data-extra-page]'),source=cards.length?cloneExtraPage(cards[cards.length-1]):cloneMainPage();addExtra(source);setTimeout(function(){extraBox.lastElementChild.scrollIntoView({behavior:'smooth',block:'start'})},30)}
 root.querySelectorAll('[data-add-spk-page]').forEach(function(button){button.addEventListener('click',addNextExtraPage)});savedExtraPages.forEach(addExtra);renumberExtras();
 function update(){var plano=nums(root.querySelector('[name="ukuran_plano"]').value),cut=nums(root.querySelector('[name="ukuran_kertas_masuk"]').value),qty=val('jumlah_kertas_masuk',0),margin=val('potong_margin',0),gap=val('potong_gap',0),mode=modeInput.value||'auto';root.querySelectorAll('.spk-cut-mode').forEach(function(b){b.classList.toggle('is-active',b.getAttribute('data-mode')===mode)});if(!plano||!cut){svg.innerHTML='<text x="50%" y="50%" text-anchor="middle" fill="#b42318" font-size="6">Isi ukuran plano dan ukuran potong</text>';return}var layout=choose(plano[0],plano[1],cut[0],cut[1],margin,gap,mode),ns='http://www.w3.org/2000/svg';svg.setAttribute('viewBox','0 0 '+plano[0]+' '+plano[1]);svg.innerHTML='<defs><pattern id="spkWaste" width="5" height="5" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><line x1="0" y1="0" x2="0" y2="5" stroke="#f43f5e" stroke-width=".35" opacity=".4"/></pattern></defs><rect width="'+plano[0]+'" height="'+plano[1]+'" fill="url(#spkWaste)" stroke="#f43f5e" stroke-width=".6" stroke-dasharray="2 1"/>';layout.pieces.forEach(function(p,i){var g=document.createElementNS(ns,'g'),r=document.createElementNS(ns,'rect'),t=document.createElementNS(ns,'text');r.setAttribute('x',p.x);r.setAttribute('y',p.y);r.setAttribute('width',p.w);r.setAttribute('height',p.h);r.setAttribute('fill',p.type==='landscape'?'rgba(244,63,94,.12)':'rgba(79,70,229,.12)');r.setAttribute('stroke',p.type==='landscape'?'#f43f5e':'#4f46e5');r.setAttribute('stroke-width','.5');t.setAttribute('x',p.x+p.w/2);t.setAttribute('y',p.y+p.h/2);t.setAttribute('text-anchor','middle');t.setAttribute('dominant-baseline','middle');t.setAttribute('fill','#3730a3');t.setAttribute('font-size',Math.max(3,Math.min(p.w,p.h)*.18));t.setAttribute('font-weight','bold');t.textContent=i+1;g.appendChild(r);g.appendChild(t);svg.appendChild(g)});var used=plano[0]*plano[1]>0?(layout.count*cut[0]*cut[1]/(plano[0]*plano[1])*100):0,need=layout.count?Math.ceil(qty/layout.count):0;root.querySelector('#spkCutCount').textContent=layout.count+' potong/plano';root.querySelector('#spkCutUsed').textContent=used.toFixed(1)+'% terpakai';root.querySelector('#spkCutNeed').textContent=need+' plano';summary.value=layout.label+'; '+layout.count+' potong/plano; kebutuhan '+need+' plano';svgInput.value=new XMLSerializer().serializeToString(svg)}
 root.querySelectorAll('.spk-cut-mode').forEach(function(b){b.addEventListener('click',function(){modeInput.value=b.getAttribute('data-mode');update()})});['jumlah_bahan_plano','ukuran_plano','ukuran_kertas_masuk','potong_margin','potong_gap'].forEach(function(n){var el=root.querySelector('[name="'+n+'"]');if(el)el.addEventListener('input',update)});update();
 function syncJumlahKertas(){var count=parseInt(root.querySelector('#spkCutCount').textContent,10)||0,jumlahPlano=Math.max(0,Math.floor(val('jumlah_bahan_plano',0))),total=count*jumlahPlano;root.querySelector('[name="jumlah_kertas_masuk"]').value=total;root.querySelector('#spkCutNeed').textContent=jumlahPlano+' plano';summary.value=(summary.value.split(';')[0]||'Layout')+'; '+count+' potong/plano × '+jumlahPlano+' plano = '+total+' lembar'}
 root.querySelectorAll('.spk-cut-mode').forEach(function(b){b.addEventListener('click',syncJumlahKertas)});['jumlah_bahan_plano','ukuran_plano','ukuran_kertas_masuk','potong_margin','potong_gap'].forEach(function(n){var el=root.querySelector('[name="'+n+'"]');if(el)el.addEventListener('input',syncJumlahKertas)});syncJumlahKertas();
 var stockSelect=root.querySelector('[name="stock_bahan_id"]');if(stockSelect)stockSelect.addEventListener('change',function(){var option=this.options[this.selectedIndex],size=option?option.getAttribute('data-size'):'';if(size){var planoInput=root.querySelector('[name="ukuran_plano"]');planoInput.value=size;planoInput.dispatchEvent(new Event('input',{bubbles:true}))}});
 var processLabels={laminating:'LAMINATING',spot_uv:'SPOT UV',foil:'FOIL',potong_paska_cetak:'POTONG PASKA CETAK',pond:'POND',lem:'LEM',packing:'PACKING'},processBox=root.querySelector('#spkFinishProcesses');
 function activeProcesses(){var active=[];if(root.querySelector('[name="finishing[]"][value="laminating_glossy"]:checked')||root.querySelector('[name="finishing[]"][value="laminating_doff"]:checked'))active.push('laminating');['spot_uv','foil','potong_paska_cetak','pond','lem','packing'].forEach(function(key){if(root.querySelector('[name="finishing[]"][value="'+key+'"]:checked'))active.push(key)});return active}
 function processHtml(key){var label=processLabels[key],html='<div class="spk-finish-process" data-process="'+key+'"><div class="spk-finish-process-title">'+label+'</div>';[['mulai','MULAI'],['selesai','SELESAI'],['hasil','HASIL AKHIR']].forEach(function(field){html+='<div class="spk-sheet-row"><span>'+field[1]+' '+label+'</span><span>:</span><div class="spk-sheet-line"><input class="spk-sheet-input" name="finishing_proses['+key+']['+field[0]+']">'+(field[0]==='hasil'?'<span>LEMBAR</span>':'')+'</div></div>'});return html+'</div>'}
 function syncFinishingProcesses(){var active=activeProcesses();Array.prototype.slice.call(processBox.querySelectorAll('.spk-finish-process')).forEach(function(group){if(active.indexOf(group.getAttribute('data-process'))===-1)group.remove()});active.forEach(function(key){if(!processBox.querySelector('[data-process="'+key+'"]'))processBox.insertAdjacentHTML('beforeend',processHtml(key))})}
 root.querySelectorAll('[name="finishing[]"]').forEach(function(box){box.addEventListener('change',syncFinishingProcesses)});syncFinishingProcesses();
 var imageInput=root.querySelector('#spkImageInput'),imageDrop=root.querySelector('#spkImageDrop'),imagePreview=root.querySelector('#spkImagePreview'),imagePreviewImg=imagePreview?imagePreview.querySelector('img'):null,imageRemove=root.querySelector('[name="gambar_hapus"]');
 function setImageFile(file){if(!file)return;if(!/^image\/(jpeg|png|webp)$/i.test(file.type)){alert('Format gambar harus JPG, PNG, atau WebP.');return}if(file.size>5*1024*1024){alert('Ukuran gambar maksimal 5 MB.');return}var transfer=new DataTransfer();transfer.items.add(file);imageInput.files=transfer.files;imageRemove.value='0';var reader=new FileReader();reader.onload=function(e){imagePreviewImg.src=e.target.result;imagePreview.classList.add('is-visible');imageDrop.style.display='none'};reader.readAsDataURL(file)}
 if(imageDrop){imageDrop.addEventListener('click',function(){imageInput.click()});imageDrop.addEventListener('dragover',function(e){e.preventDefault();imageDrop.classList.add('is-dragging')});imageDrop.addEventListener('dragleave',function(){imageDrop.classList.remove('is-dragging')});imageDrop.addEventListener('drop',function(e){e.preventDefault();imageDrop.classList.remove('is-dragging');setImageFile(e.dataTransfer.files[0])})}if(imageInput)imageInput.addEventListener('change',function(){setImageFile(this.files[0])});var changeButton=root.querySelector('#spkImageChange');if(changeButton)changeButton.addEventListener('click',function(){imageInput.click()});var removeButton=root.querySelector('#spkImageRemove');if(removeButton)removeButton.addEventListener('click',function(){imageInput.value='';imageRemove.value='1';imagePreview.classList.remove('is-visible');imagePreviewImg.src='';imageDrop.style.display='flex'});
})();
</script>
