<?php

    if(isset($_GET['kode'])){
        $sql_cek = "SELECT * FROM tb_kk WHERE id_kk='".$_GET['kode']."'";
        $query_cek = mysqli_query($koneksi, $sql_cek);
        $data_cek = mysqli_fetch_array($query_cek,MYSQLI_BOTH);
    }
?>

<div class="card card-success">
	<div class="card-header">
		<h3 class="card-title">
			<i class="fa fa-edit"></i> Ubah Data</h3>
	</div>
	<form action="" method="post" enctype="multipart/form-data">
		<div class="card-body">

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">Foto KK</label>
				<div class="col-sm-6">
					<?php if(!empty($data_cek['foto_kk'])): ?>
						<img id="preview_kk" src="foto/kk/<?php echo $data_cek['foto_kk']; ?>" width="200px" style="border: 2px solid #6c757d; padding: 3px; border-radius: 5px; cursor: pointer; display: block;" class="mb-2">
					<?php else: ?>
						<img id="preview_kk" src="dist/img/noimage.png" width="200px" style="border: 2px solid #6c757d; padding: 3px; border-radius: 5px; display: block;" class="mb-2">
					<?php endif; ?>
					
					<input type="file" class="form-control mb-2" id="foto_kk" name="foto_kk" accept=".jpg, .jpeg, .png">
                    <button type="button" class="btn btn-success btn-block" id="btnScanKK">
                        <i class="fas fa-magic"></i> Scan Ulang dengan AI
                    </button>
                    <small class="text-muted">Pilih foto, crop, lalu scan.</small>
                    <input type="hidden" id="foto_cropped" name="foto_cropped">
				</div>
			</div>

            <?php include 'admin/scanner_modal.php'; ?>

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">No Sistem</label>
				<div class="col-sm-3">
					<input type='text' class="form-control" id="id_kk" name="id_kk" value="<?php echo $data_cek['id_kk']; ?>"
					 readonly/>
				</div>
			</div>

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">No KK</label>
				<div class="col-sm-6">
					<input type="text" class="form-control" id="no_kk" name="no_kk" value="<?php echo $data_cek['no_kk']; ?>"
					 required>
				</div>
			</div>

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">Kpl Keluarga</label>
				<div class="col-sm-6">
					<input type="text" class="form-control" id="kepala" name="kepala" value="<?php echo $data_cek['kepala']; ?>"
					 required>
				</div>
			</div>

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">Desa</label>
				<div class="col-sm-6">
					<input type="text" class="form-control" id="desa" name="desa" value="<?php echo $data_cek['desa']; ?>"
					 required>
				</div>
			</div>

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">RT/RW</label>
				<div class="col-sm-3">
					<input type="text" class="form-control" id="rt" name="rt" value="<?php echo $data_cek['rt']; ?>"
					 required>
				</div>
				<div class="col-sm-3">
					<input type="text" class="form-control" id="rw" name="rw" value="<?php echo $data_cek['rw']; ?>"
					 required>
				</div>
			</div>

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">Kecamatan</label>
				<div class="col-sm-6">
					<input type="text" class="form-control" id="kec" name="kec" value="<?php echo $data_cek['kec']; ?>"
					 required>
				</div>
			</div>

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">Kabupaten</label>
				<div class="col-sm-6">
					<input type="text" class="form-control" id="kab" name="kab" value="<?php echo $data_cek['kab']; ?>"
					 required>
				</div>
			</div>

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">Provinsi</label>
				<div class="col-sm-6">
					<input type="text" class="form-control" id="prov" name="prov" value="<?php echo $data_cek['prov']; ?>"
					 required>
				</div>
			</div>




		</div>
		<div class="card-footer">
			<input type="submit" name="Ubah" value="Simpan" class="btn btn-success">
			<a href="?page=data-kartu" title="Kembali" class="btn btn-secondary">Batal</a>
		</div>
	</form>
</div>

<script>
window.addEventListener('load', function() {
    // Scanner Logic
    var inputImage = document.getElementById('foto_kk');
    var preview = document.getElementById('preview_kk');
    var hiddenInput = document.getElementById('foto_cropped');

    window.handleScannerResult = function(base64) {
        preview.src = base64;
        hiddenInput.value = base64;
    };

    inputImage.addEventListener('change', function(e) {
        var files = e.target.files;
        if (files && files.length > 0) {
            if (window.openScanner) {
                window.openScanner(files[0]);
            }
             inputImage.value = ''; 
        }
    });

    // Scan
    document.getElementById('btnScanKK').addEventListener('click', function() {
        var fileInput = document.getElementById('foto_kk');
        var croppedVal = document.getElementById('foto_cropped').value;

        if(fileInput.files.length === 0 && !croppedVal) {
            Swal.fire('Info', 'Silakan pilih foto KK baru terlebih dahulu.', 'warning');
            return;
        }

        var btn = this;
        var originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Menganalisa...';
        btn.disabled = true;

        var formData = new FormData();
        var croppedData = document.getElementById('foto_cropped').value;

        if (croppedData) {
            var byteString = atob(croppedData.split(',')[1]);
            var ab = new ArrayBuffer(byteString.length);
            var ia = new Uint8Array(ab);
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }
            var blob = new Blob([ab], { type: 'image/jpeg' });
            formData.append('image', blob, 'cropped_kk_edit.jpg');
        } else if (fileInput.files.length > 0) {
            formData.append('image', fileInput.files[0]);
        } else {
             Swal.fire('Info', 'Belum ada foto baru yang dipilih / dicrop.', 'warning');
             btn.disabled = false;
             btn.innerHTML = originalText;
             return;
        }

        formData.append('type', 'kk');

        fetch('admin/api/ocr_helper.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if(data.success) {
                var d = data.data;
                // Show Confirmation
                Swal.fire({
                    title: 'Hasil Scan KK',
                    html: `
                        <div style="text-align: left; font-size: 0.9rem;">
                            <table class="table table-bordered table-sm">
                                <tr><td width="30%">No KK</td><td><b>${d.no_kk || '-'}</b></td></tr>
                                <tr><td>Kepala Kel</td><td><b>${d.kepala_keluarga || '-'}</b></td></tr>
                                <tr><td>Alamat</td><td>${d.desa || '-'}</td></tr>
                                <tr><td>RT/RW</td><td>${d.rt || '-'}/${d.rw || '-'}</td></tr>
                                <tr><td>Kecamatan</td><td>${d.kecamatan || '-'}</td></tr>
                                <tr><td>Kabupaten</td><td>${d.kabupaten || '-'}</td></tr>
                                <tr><td>Provinsi</td><td>${d.provinsi || '-'}</td></tr>
                            </table>
                            <p class="mb-0 text-muted">Perbarui data formulir?</p>
                        </div>
                    `,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Ya, Update',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.value) {
                        if(d.no_kk) document.getElementsByName('no_kk')[0].value = d.no_kk;
                        if(d.kepala_keluarga) document.getElementsByName('kepala')[0].value = d.kepala_keluarga;
                        if(d.desa) document.getElementsByName('desa')[0].value = d.desa;
                        if(d.rt) document.getElementsByName('rt')[0].value = d.rt;
                        if(d.rw) document.getElementsByName('rw')[0].value = d.rw;
                        if(d.kecamatan) document.getElementsByName('kec')[0].value = d.kecamatan;
                        if(d.kabupaten) document.getElementsByName('kab')[0].value = d.kabupaten;
                        if(d.provinsi) document.getElementsByName('prov')[0].value = d.provinsi;
                        
                        Swal.fire('Berhasil!', 'Data formulir telah diperbarui.', 'success');
                    }
                });
            } else {
                Swal.fire('Gagal', data.message, 'error');
            }
        })
        .catch(err => {
            console.error(err);
             Swal.fire('Error', 'Terjadi kesalahan: ' + err.message, 'error');
        })
        .finally(() => {
            btn.innerHTML = originalText;
            btn.disabled = false;
        });
    });
});
</script>



<?php

    if (isset ($_POST['Ubah'])){
		
		$target = 'foto/kk/';
		$nama_file = @$_FILES['foto_kk']['name'];
        $sumber = @$_FILES['foto_kk']['tmp_name'];
        $has_new_photo = false;
        
        // Cek Crop
        if (!empty($_POST['foto_cropped'])) {
            $data = $_POST['foto_cropped'];
            $parts = explode(',', $data);
            $data = $parts[1];
            $data = base64_decode($data);
            $nama_file = "KK-" . time() . ".jpg";
            file_put_contents($target . $nama_file, $data);
            $has_new_photo = true;
        } elseif (!empty($sumber)) {
             move_uploaded_file($sumber, $target.$nama_file);
             $has_new_photo = true;
        }

        // Sanitize Inputs
        $id_kk = mysqli_real_escape_string($koneksi, $_POST['id_kk']);
        $no_kk = mysqli_real_escape_string($koneksi, $_POST['no_kk']);
        $kepala = mysqli_real_escape_string($koneksi, $_POST['kepala']);
        $desa = mysqli_real_escape_string($koneksi, $_POST['desa']);
        $rt = mysqli_real_escape_string($koneksi, $_POST['rt']);
        $rw = mysqli_real_escape_string($koneksi, $_POST['rw']);
        $kec = mysqli_real_escape_string($koneksi, $_POST['kec']);
        $kab = mysqli_real_escape_string($koneksi, $_POST['kab']);
        $prov = mysqli_real_escape_string($koneksi, $_POST['prov']);

		if($has_new_photo){
			$foto= $data_cek['foto_kk'];
			if (file_exists("foto/kk/$foto")){
			unlink("foto/kk/$foto");}

			$sql_ubah = "UPDATE tb_kk SET 
			no_kk='$no_kk',
			kepala='$kepala',
			desa='$desa',
			rt='$rt',
			rw='$rw',
			kec='$kec',
			kab='$kab',
			prov='$prov',
			foto_kk='$nama_file'
			WHERE id_kk='$id_kk'";
			$query_ubah = mysqli_query($koneksi, $sql_ubah);

		}else{
			$sql_ubah = "UPDATE tb_kk SET 
			no_kk='$no_kk',
			kepala='$kepala',
			desa='$desa',
			rt='$rt',
			rw='$rw',
			kec='$kec',
			kab='$kab',
			prov='$prov'
			WHERE id_kk='$id_kk'";
			$query_ubah = mysqli_query($koneksi, $sql_ubah);
		}
    	mysqli_close($koneksi);

    if ($query_ubah) {
        echo "<script>
      Swal.fire({title: 'Ubah Data Berhasil',text: '',icon: 'success',confirmButtonText: 'OK'
      }).then((result) => {if (result.value)
        {window.location = 'index.php?page=data-kartu';
        }
      })</script>";
      }else{
      echo "<script>
      Swal.fire({title: 'Ubah Data Gagal',text: '',icon: 'error',confirmButtonText: 'OK'
      }).then((result) => {if (result.value)
        {window.location = 'index.php?page=data-kartu';
        }
      })</script>";
    }}
