<form id="form-wa" method="post">
	<input type="hidden" id="wa_blocked" value="<?= isset($wa_blocked) ? (int)$wa_blocked : 0; ?>">
	<input type="hidden" id="wa_block_msg" value="<?= isset($wa_block_msg) ? htmlspecialchars($wa_block_msg, ENT_QUOTES) : ''; ?>">

	<div class="form-group mb-1">
		<label for="device">Device</label>
		<div class="input-group input-group-sm">
			<select name="device" id="device" class="custom-select form-control form-control-sm"
				data-source="<?= url_https(); ?>whatsapp/load_device" data-valueKey="id" data-displayKey="name" required>
			</select>
			<div class="input-group-prepend">
				<button class="btn btn-secondary" type="button" id="cek_status">STATUS</button>
			</div>
		</div>
	</div>

	<div class="form-group mb-1">
		<label for="nomor_tujuan">Nomor Tujuan</label>
		<input type="text" class="form-control form-control-sm fcs" id="nomor_tujuan" name="nomor_tujuan" value="<?= $nomor; ?>" readonly required>
	</div>

	<div class="form-group mb-1">
		<label for="nomor_order">Nomor Order</label>
		<input type="hidden" class="form-control" id="id" name="id" value="<?= $id; ?>">
		<input type="hidden" class="form-control" id="tgl_order" name="tgl_order" value="<?= $tgl; ?>">
		<input type="hidden" class="form-control" id="user" name="user" value="<?= $user; ?>">
		<input type="text" class="form-control form-control-sm fcs" id="nomor_order" name="nomor_order" value="<?= $id_invoice; ?>" readonly required>
	</div>

	<div class="form-group mb-1">
		<label for="jenis_pesan">Jenis Pesan</label>
		<select name="jenis_pesan" id="jenis_pesan" class="custom-select form-control form-control-sm" required>
			<option value="" selected>Pilih Jenis Pesan</option>
			<?php foreach ($jenis as $val) {
				echo '<option value="' . $val->id . '">' . $val->title . '</option>';
			} ?>
		</select>
	</div>

	<!--div class="form-group mb-1">
		<label for="tracking_link_preview">Link Tracking</label>
		<input type="text" class="form-control form-control-sm fcs" id="tracking_link_preview" value="<?= isset($tracking_link) ? htmlspecialchars($tracking_link, ENT_QUOTES) : ''; ?>" readonly>
	</div-->

	<div class="form-group mb-1 isi_pesan" style="display:none">
		<label for="isi_pesan">Pesan</label>
		<textarea class="form-control form-control-sm fcs" rows="8" id="isi_pesan" name="isi_pesan" required></textarea>
	</div>
</form>

<script>
	(function () {

		function startLoading() { $('body').loading(); }
		function stopLoading() { $('body').loading('stop'); }

		// ✅ popup warning saat modal dibuka
		var blocked = ($('#wa_blocked').val() === '1');
		if (blocked) {
			var msg = $('#wa_block_msg').val() || 'Aplikasi harus online.';
			setTimeout(function () {
				sweet('Peringatan!!!', msg, 'warning', 'warning');
			}, 150);

			// disable semua input supaya user tidak bingung
			$('#device, #jenis_pesan, #isi_pesan').prop('disabled', true);
			$('#cek_status').prop('disabled', true);
			return; // stop script lain
		}

		// load device options
		(function loadDevice() {
			$("select[data-source]").each(function () {
				var element = $(this);
				element.empty().append('<option value="">Pilih Device</option>');
				$.ajax({ url: element.attr("data-source") })
					.then(function (items) {
						(items || []).map(function (match) {
							var opt = $("<option>");
							opt.val(match[element.attr("data-valueKey")]).text(match[element.attr("data-displayKey")]);
							element.append(opt);
						});
					});
			});
		})();

		// change jenis pesan
		$("#jenis_pesan").on("change", function () {
			var id = $(this).val();
			if (id !== '') {
				$('.isi_pesan').show();
			} else {
				$('.isi_pesan').hide();
				$('#isi_pesan').val('');
				return;
			}

			var idorder = $('#id').val();
			var nomor_order = $('#nomor_order').val();
			var tgl = $('#tgl_order').val();
			var user = $('#user').val();

			$.ajax({
				url: base_url + 'whatsapp/get_pesan',
				data: { status: id, idorder: idorder, nomor_order: nomor_order, tgl: tgl, user: user },
				method: 'POST',
				dataType: 'json',
				beforeSend: startLoading,
				success: function (data) {
					var ok = data && (data.status === true || data.status === 1 || data.status === 'true');

					if (!ok) {
						$('#jenis_pesan').val('');
						$('#isi_pesan').val('');
						$('.isi_pesan').hide();
						sweet('Peringatan!!!', (data && data.msg) ? data.msg : 'Gagal mengambil pesan.', 'warning', 'warning');
						return;
					}

					// ✅ tampilkan langsung (tanpa decodeURIComponent agar "%" tidak bikin error)
					var text = data.msg || data.pesan || '';
					if (typeof text !== 'string') text = '';
					$("#isi_pesan").val(text);
				},
				error: function (xhr) {
					var err = xhr.responseText;
					sweet('Server!!!', err, 'error', 'danger');
				},
				complete: stopLoading
			});
		});

		// cek status device
		$("#device").change(function () {
			var id = $(this).val();
			if (id === '') {
				$('#cek_status').removeClass('btn-success btn-warning').addClass('btn-secondary').html('STATUS');
				return;
			}
			$.ajax({
				url: base_url + 'whatsapp/cek_status',
				method: 'POST',
				dataType: 'json',
				data: { token: id },
				beforeSend: startLoading,
				success: function (data) {
					if (data && data.device_status == 'connect') {
						$('#cek_status').html('CONNECTED').removeClass('btn-secondary btn-warning').addClass('btn-success');
					} else {
						$('#cek_status').html('DISCONNECTED').removeClass('btn-secondary btn-success').addClass('btn-warning');
					}
				},
				error: function (xhr) {
					var err = xhr.responseText;
					sweet('Server!!!', err, 'error', 'danger');
				},
				complete: stopLoading
			});
		});

	})();
</script>
