<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php $pmg_is_admin = ($this->session->userdata('role_name') == 'administrator'); ?>

<style>
.brb-act.pmg{color:#5a32a3;background:#f1ecfb;border:1px dashed #c9b8f0;box-shadow:0 2px 6px rgba(111,66,193,.15);}
.pmg-numlist{max-height:220px;overflow:auto;border:1px solid var(--line);border-radius:10px;padding:8px;margin-bottom:12px;background:#fbfdfc;}
.pmg-num{display:flex;align-items:center;gap:8px;padding:7px 8px;border-radius:8px;font-size:12.5px;font-weight:700;cursor:pointer;}
.pmg-num:hover{background:#eef1f5;}
.pmg-num input{accent-color:#6f42c1;width:16px;height:16px;}
.pmg-num .nobox{min-width:44px;text-align:center;background:#6f42c1;color:#fff;border-radius:8px;padding:3px 6px;font-weight:800;font-size:12px;}
.pmg-num.blocked{opacity:.45;cursor:not-allowed;}
.pmg-num .blk{font-size:10px;color:#b3261f;font-weight:800;}
.pmg-reason{display:flex;flex-direction:column;gap:6px;margin-bottom:12px;}
.pmg-reason label{display:flex;gap:8px;align-items:center;border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-size:12.5px;font-weight:600;background:#fbfdfc;cursor:pointer;}
.pmg-reason input{accent-color:#6f42c1;}
</style>

<div class="brb-overlay" id="pmgOverlay">
	<div class="brb-modal" role="dialog" aria-modal="true">
		<div class="brb-modal-head">
			<div class="brb-modal-ico">&#128204;</div>
			<div>
				<div style="font-weight:800;font-size:15px;">PENGAJUAN MARKER PENGGANTI (PMG)</div>
				<div style="font-size:11px;opacity:.8;">Marker 5×3 cm · 1 num = 1 pcs · hanya cetak 1 kali</div>
			</div>
		</div>
		<div style="padding:14px 18px;overflow:auto;">
			<div id="pmgInfo" style="font-size:12.5px;margin-bottom:10px;"></div>
			<div class="set-label">1. Centang num yang diajukan</div>
			<div class="pmg-numlist" id="pmgNums"><div class="empty">Memuat…</div></div>
			<div class="set-label">2. Pilih alasan</div>
			<div class="pmg-reason">
				<label><input type="radio" name="pmg_reason" value="HILANG"> Marker lepas saat proses pencucian dan hilang</label>
				<label><input type="radio" name="pmg_reason" value="TIDAK_TAMPAK"> Tulisan marker tidak tampak 95%</label>
			</div>
			<div class="set-label">3. Foto bukti (maksimal 3)</div>
			<input type="file" id="pmgPhotos" accept="image/*" multiple>
		</div>
		<div class="brb-modal-foot">
			<button type="button" class="brb-btn ghost" id="pmgCancel">Batal</button>
			<button type="button" class="brb-btn confirm" id="pmgSubmit" style="background:linear-gradient(120deg,#6f42c1,#5a32a3);">&#128228; Ajukan PMG</button>
		</div>
	</div>
</div>

<script>
(function(){
	var PMG_SHOW = <?php echo $pmg_is_admin ? '0' : '1'; ?>;
	if (!PMG_SHOW) return;
	var URL = '<?php echo app_url(); ?>';
	var curId = 0;

	function esc(s){ s = (s == null ? '' : String(s)); return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }

	function injectButtons(){
		var added = 0;
		document.querySelectorAll('tr.brb-row').forEach(function(tr){
			if (tr.querySelector('.pmg-open')) { added++; return; }
			var id = tr.getAttribute('data-id');
			var nwsBtn = null;
			tr.querySelectorAll('button, a').forEach(function(b){
				if (!nwsBtn && (b.textContent || '').indexOf('NWS') >= 0) nwsBtn = b;
			});
			var html = '<button type="button" class="brb-act pmg pmg-open" data-id="'+id+'"><span class="ic">&#128204;</span> PMG</button>';
			if (nwsBtn) { nwsBtn.insertAdjacentHTML('afterend', html); }
			else if (tr.cells && tr.cells[1]) { tr.cells[1].insertAdjacentHTML('beforeend', html); }
			added++;
		});
		return added;
	}
	var tries = 0;
	function tryInject(){ tries++; if (injectButtons() === 0 && tries < 10) setTimeout(tryInject, 300); }
	if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', tryInject); } else { tryInject(); }

	function injectPrintButtons(){
		fetch(URL + 'pmg/printable_list', {method:'POST', body:new FormData()})
		.then(function(r){ return r.json(); })
		.then(function(res){
			if (res.err_code !== 0) return;
			(res.rows || []).forEach(function(p){
				var tr = document.querySelector('tr.brb-row[data-id="' + p.idtransaction_group + '"]');
				if (!tr || tr.querySelector('.pmg-print')) return;
				var html = '<button type="button" class="brb-act pmg pmg-print" data-pmg="' + p.idpmg + '" style="border-style:solid;"><span class="ic">&#128424;</span> Cetak PMG</button>';
				var pmgBtn = tr.querySelector('.pmg-open');
				if (pmgBtn) { pmgBtn.insertAdjacentHTML('afterend', html); }
				else {
					var nwsBtn = null;
					tr.querySelectorAll('button, a').forEach(function(b){ if (!nwsBtn && (b.textContent || '').indexOf('NWS') >= 0) nwsBtn = b; });
					if (nwsBtn) { nwsBtn.insertAdjacentHTML('afterend', html); }
					else if (tr.cells && tr.cells[1]) { tr.cells[1].insertAdjacentHTML('beforeend', html); }
				}
			});
		}).catch(function(){});
	}
	setTimeout(injectPrintButtons, 600);

	var overlay = document.getElementById('pmgOverlay');
	var numsBox = document.getElementById('pmgNums');
	var infoBox = document.getElementById('pmgInfo');
	var photosInput = document.getElementById('pmgPhotos');
	var submitBtn = document.getElementById('pmgSubmit');
	var cancelBtn = document.getElementById('pmgCancel');

	function closeModal(){ overlay.classList.remove('show'); document.body.classList.remove('brb-noscroll'); }

	function openModal(id){
		curId = parseInt(id, 10);
		numsBox.innerHTML = '<div class="empty">Memuat…</div>';
		infoBox.innerHTML = '';
		document.querySelectorAll('input[name="pmg_reason"]').forEach(function(r){ r.checked = false; });
		photosInput.value = '';
		overlay.classList.add('show');
		document.body.classList.add('brb-noscroll');

		var fd = new FormData(); fd.append('id', curId);
		fetch(URL + 'pmg/apply_data', {method:'POST', body:fd})
		.then(function(r){ return r.json(); })
		.then(function(res){
			if (res.err_code !== 0) { alert(res.err_message || 'Gagal memuat data'); closeModal(); return; }
			infoBox.innerHTML = '<b>'+esc(res.code)+'</b> · '+esc(res.customer);
			var html = '';
			(res.items || []).forEach(function(it){
				var dis = it.blocked ? ' disabled' : '';
				html += '<label class="pmg-num'+(it.blocked?' blocked':'')+'">'
					+ '<input type="checkbox" class="pmg-chk" value="'+it.idtransaction+'"'+dis+'>'
					+ '<span class="nobox">'+it.n+'/'+it.tot+'</span>'
					+ '<span>'+esc(it.product_name)+'</span>'
					+ (it.blocked ? '<span class="blk">PMG aktif</span>' : '')
					+ '</label>';
			});
			numsBox.innerHTML = html || '<div class="empty">Tidak ada item.</div>';
		}).catch(function(){ alert('Gagal menghubungi server'); closeModal(); });
	}

	cancelBtn.addEventListener('click', closeModal);
	overlay.addEventListener('click', function(e){ if (e.target === overlay) closeModal(); });

	document.addEventListener('click', function(e){
		var b = e.target.closest('.pmg-open');
		if (b) { openModal(b.getAttribute('data-id')); return; }
		var c = e.target.closest('.pmg-print');
		if (c) { window.open(URL + 'pmg/print_page/' + c.getAttribute('data-pmg'), '_blank'); }
	});

	submitBtn.addEventListener('click', function(){
		var tids = [];
		document.querySelectorAll('.pmg-chk:checked').forEach(function(c){ tids.push(c.value); });
		if (tids.length === 0) { alert('Centang minimal 1 num.'); return; }
		var reasonEl = document.querySelector('input[name="pmg_reason"]:checked');
		if (!reasonEl) { alert('Pilih alasan terlebih dahulu.'); return; }
		var files = photosInput.files;
		if (files.length > 3) { alert('Foto maksimal 3.'); return; }

		var fd = new FormData();
		fd.append('id', curId);
		fd.append('reason', reasonEl.value);
		fd.append('tids', tids.join(','));
		for (var i = 0; i < files.length; i++) fd.append('photos[]', files[i]);

		submitBtn.disabled = true;
		fetch(URL + 'pmg/apply_save', {method:'POST', body:fd})
		.then(function(r){ return r.json(); })
		.then(function(res){
			submitBtn.disabled = false;
			if (res.err_code === 0) {
				alert('Pengajuan ' + res.pmg_code + ' terkirim. Menunggu persetujuan admin.');
				closeModal();
				location.reload();
			} else {
				alert(res.err_message || 'Gagal menyimpan');
			}
		}).catch(function(){ submitBtn.disabled = false; alert('Gagal menghubungi server'); });
	});
})();
</script>