<?php

    if(isset($_GET['kode'])){
        $sql_cek = "SELECT * FROM tb_pdd WHERE id_pend='".$_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">No Sistem</label>
				<div class="col-sm-2">
					<input type="text" class="form-control" id="id_pend" name="id_pend" value="<?php echo $data_cek['id_pend']; ?>"
					 readonly/>
				</div>
			</div>

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">Foto KTP</label>
				<div class="col-sm-6">
					<?php if(!empty($data_cek['foto_ktp'])): ?>
						<img id="preview_ktp" src="foto/ktp/<?php echo $data_cek['foto_ktp']; ?>" width="200px" style="border: 2px solid #6c757d; padding: 3px; border-radius: 5px; cursor: pointer; display:block;" class="mb-2">
					<?php else: ?>
						<img id="preview_ktp" 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_ktp" name="foto_ktp" accept=".jpg, .jpeg, .png">
                    <button type="button" class="btn btn-info btn-block" id="btnScanKTP">
                        <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">NIK</label>
				<div class="col-sm-6">
					<input type="text" class="form-control" id="nik" name="nik" value="<?php echo $data_cek['nik']; ?>"
					 required>
				</div>
			</div>

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

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">Tempat/Tanggal Lahir</label>
				<div class="col-sm-3">
					<input type="text" class="form-control" id="tempat_lh" name="tempat_lh" value="<?php echo $data_cek['tempat_lh']; ?>"
					/>
				</div>
				<div class="col-sm-3">
					<input type="date" class="form-control" id="tgl_lh" name="tgl_lh" value="<?php echo $data_cek['tgl_lh']; ?>"
					/>
				</div>
			</div>

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">Jenis Kelamin</label>
				<div class="col-sm-3">
					<select name="jekel" id="jekel" class="form-control">
						<option value="">-- Pilih jekel --</option>
						<?php
                //menhecek data yg dipilih sebelumnya
                //menhecek data yg dipilih sebelumnya
                if ($data_cek['jekel'] == "LK") echo "<option value='LK' selected>LAKI-LAKI</option>";
                else echo "<option value='LK'>LAKI-LAKI</option>";

                if ($data_cek['jekel'] == "PR") echo "<option value='PR' selected>PEREMPUAN</option>";
                else echo "<option value='PR'>PEREMPUAN</option>";
            ?>
					</select>
				</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">Kecamatan</label>
				<div class="col-sm-6">
					<input type="text" class="form-control" id="kecamatan" name="kecamatan" value="<?php echo $data_cek['kecamatan']; ?>"
					 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="kabupaten" name="kabupaten" value="<?php echo $data_cek['kabupaten']; ?>"
					 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="provinsi" name="provinsi" value="<?php echo $data_cek['provinsi']; ?>"
					 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']; ?>"
					/>
				</div>
				<div class="col-sm-3">
					<input type="text" class="form-control" id="rw" name="rw" value="<?php echo $data_cek['rw']; ?>"
					/>
				</div>
			</div>

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

			<div class="form-group row">
				<label class="col-sm-2 col-form-label">Status Perkawinan</label>
				<div class="col-sm-3">
					<select name="kawin" id="kawin" class="form-control">
						<option value="">-- Pilih Status --</option>
						<?php
                //menhecek data yg dipilih sebelumnya
                if ($data_cek['kawin'] == "Sudah") echo "<option value='Sudah' selected>Sudah</option>";
                else echo "<option value='Sudah'>Sudah</option>";

                if ($data_cek['kawin'] == "Belum") echo "<option value='Belum' selected>Belum</option>";
				else echo "<option value='Belum'>Belum</option>";
				
				if ($data_cek['kawin'] == "Cerai Mati") echo "<option value='Cerai Mati' selected>Cerai Mati</option>";
                else echo "<option value='Cerai Mati'>Cerai Mati</option>";

                if ($data_cek['kawin'] == "Cerai Hidup") echo "<option value='Cerai Hidup' selected>Cerai Hidup</option>";
                else echo "<option value='Cerai Hidup'>Cerai Hidup</option>";
            ?>
					</select>
				</div>
			</div>

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

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


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

<script>
    // Preview Image
    window.addEventListener('load', function() {
    // Scanner Logic
    var inputImage = document.getElementById('foto_ktp');
    var preview = document.getElementById('preview_ktp');
    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('btnScanKTP').addEventListener('click', function() {
        var fileInput = document.getElementById('foto_ktp');
        var croppedVal = document.getElementById('foto_cropped').value;

        if(fileInput.files.length === 0 && !croppedVal) {
            Swal.fire('Info', 'Silakan pilih foto KTP 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) {
            // Convert Base64 to Blob
            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_ktp_edit.jpg');
        } else if (fileInput.files.length > 0) {
             formData.append('image', fileInput.files[0]);
        } else {
             // Handle case where specific file input is empty but user wants to rescan existing? 
             // Currently flow requires NEW photo for scan.
             Swal.fire('Info', 'Belum ada foto baru yang dipilih / dicrop.', 'warning');
             btn.disabled = false;
             btn.innerHTML = originalText;
             return;
        }

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

        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 AI',
                    html: `
                        <div style="text-align: left; font-size: 0.9rem;">
                            <table class="table table-bordered table-sm">
                                <tr><td width="30%">NIK</td><td><b>${d.nik || '-'}</b></td></tr>
                                <tr><td>Nama</td><td><b>${d.nama || '-'}</b></td></tr>
                                <tr><td>TTL</td><td>${d.tempat_lh || '-'}, ${d.tgl_lh || '-'}</td></tr>
                                <tr><td>JK</td><td>${d.je_kel || '-'}</td></tr>
                                <tr><td>RT/RW</td><td>${d.rt || '000'}/${d.rw || '000'}</td></tr>
                                <tr><td>Desa</td><td>${d.desa || '-'}</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>
                                <tr><td>Warga Negara</td><td>${d.kewarganegaraan || '-'}</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) {
                         // Auto-fill logic
                        if(d.nik) document.getElementsByName('nik')[0].value = d.nik;
                        if(d.nama) document.getElementsByName('nama')[0].value = d.nama;
                        if(d.tempat_lh) document.getElementsByName('tempat_lh')[0].value = d.tempat_lh;
                        if(d.tgl_lh) document.getElementsByName('tgl_lh')[0].value = d.tgl_lh;
                        if(d.je_kel) {
                            var jkSelect = document.getElementsByName('jekel')[0];
                            for (var i = 0; i < jkSelect.options.length; i++) {
                                // Check value (LK/PR) or Text
                                if (jkSelect.options[i].value === d.je_kel || jkSelect.options[i].text === d.je_kel) {
                                    jkSelect.selectedIndex = i;
                                    break;
                                }
                            }
                        }
                        if(d.desa) document.getElementsByName('desa')[0].value = d.desa;
                        if(d.kecamatan) document.getElementsByName('kecamatan')[0].value = d.kecamatan;
                        if(d.kabupaten) document.getElementsByName('kabupaten')[0].value = d.kabupaten;
                        if(d.provinsi) document.getElementsByName('provinsi')[0].value = d.provinsi;
                        document.getElementsByName('rt')[0].value = d.rt || '000';
                        document.getElementsByName('rw')[0].value = d.rw || '000';
                        if(d.agama) document.getElementsByName('agama')[0].value = d.agama;
                        if(d.kewarganegaraan) document.getElementsByName('kewarganegaraan')[0].value = d.kewarganegaraan;
                        
                        if(d.status) {
                            var kawinSelect = document.getElementsByName('kawin')[0];
                            for (var i = 0; i < kawinSelect.options.length; i++) {
                                if (kawinSelect.options[i].text === d.status || kawinSelect.options[i].text.includes(d.status)) {
                                    kawinSelect.selectedIndex = i;
                                    break;
                                }
                            }
                        }
                        if(d.pekerjaan) document.getElementsByName('pekerjaan')[0].value = d.pekerjaan;
                        
                        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/ktp/';
		$nama_file = @$_FILES['foto_ktp']['name'];
        $sumber = @$_FILES['foto_ktp']['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 = "KTP-" . time() . ".jpg";
            file_put_contents($target . $nama_file, $data);
            $has_new_photo = true;
        } elseif (!empty($sumber)) {
            // Normal Upload
            move_uploaded_file($sumber, $target.$nama_file);
            $has_new_photo = true;
        }

        // Sanitize Input
        $id_pend = mysqli_real_escape_string($koneksi, $_POST['id_pend']);
        $nik = mysqli_real_escape_string($koneksi, $_POST['nik']);
        $nama = mysqli_real_escape_string($koneksi, $_POST['nama']);
        $tempat_lh = mysqli_real_escape_string($koneksi, $_POST['tempat_lh']);
        $tgl_lh = mysqli_real_escape_string($koneksi, $_POST['tgl_lh']);
        $jekel = mysqli_real_escape_string($koneksi, $_POST['jekel']);
        $desa = mysqli_real_escape_string($koneksi, $_POST['desa']);
        $rt = mysqli_real_escape_string($koneksi, $_POST['rt']);
        $rw = mysqli_real_escape_string($koneksi, $_POST['rw']);
        $agama = mysqli_real_escape_string($koneksi, $_POST['agama']);
        $kawin = mysqli_real_escape_string($koneksi, $_POST['kawin']);
        $pekerjaan = mysqli_real_escape_string($koneksi, $_POST['pekerjaan']);
        $kecamatan = mysqli_real_escape_string($koneksi, $_POST['kecamatan']);
        $kabupaten = mysqli_real_escape_string($koneksi, $_POST['kabupaten']);
        $provinsi = mysqli_real_escape_string($koneksi, $_POST['provinsi']);
        $kewarganegaraan = mysqli_real_escape_string($koneksi, $_POST['kewarganegaraan']);

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

			$sql_ubah = "UPDATE tb_pdd SET 
			nik='$nik',
			nama='$nama',
			tempat_lh='$tempat_lh',
			tgl_lh='$tgl_lh',
			jekel='$jekel',
			desa='$desa',
			rt='$rt',
			rw='$rw',
			agama='$agama',
			kawin='$kawin',
			pekerjaan='$pekerjaan',
			kecamatan='$kecamatan',
			kabupaten='$kabupaten',
			provinsi='$provinsi',
			kewarganegaraan='$kewarganegaraan',
            foto_ktp='$nama_file'
			WHERE id_pend='$id_pend'";
			$query_ubah = mysqli_query($koneksi, $sql_ubah);

		}else{
			$sql_ubah = "UPDATE tb_pdd SET 
			nik='$nik',
			nama='$nama',
			tempat_lh='$tempat_lh',
			tgl_lh='$tgl_lh',
			jekel='$jekel',
			desa='$desa',
			rt='$rt',
			rw='$rw',
			agama='$agama',
			kawin='$kawin',
			pekerjaan='$pekerjaan',
			kecamatan='$kecamatan',
			kabupaten='$kabupaten',
			provinsi='$provinsi',
			kewarganegaraan='$kewarganegaraan'
			WHERE id_pend='$id_pend'";
			$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-pend';
        }
      })</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-pend';
        }
      })</script>";
    }}
