<div class="card card-primary">
	<div class="card-header">
		<h3 class="card-title">
			<i class="fa fa-edit"></i> Tambah 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 KTP</label>
				<div class="col-sm-6">
                    <img id="preview_ktp" src="#" alt="Preview Foto" class="img-fluid mb-2" style="display:none; max-height: 300px; border: 1px solid #ddd; border-radius: 5px;">
					<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 Foto 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" placeholder="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" placeholder="Nama Penduduk" required>
				</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" placeholder="Tempat Lahir" required>
				</div>
				<div class="col-sm-3">
					<input type="date" class="form-control" id="tgl_lh" name="tgl_lh" placeholder="Tanggal Lahir" required>
				</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>- Pilih -</option>
						<option>- Pilih -</option>
						<option value="LK">LAKI-LAKI</option>
						<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" placeholder="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" placeholder="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" placeholder="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" placeholder="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" placeholder="RT" required>
				</div>
				<div class="col-sm-3">
					<input type="text" class="form-control" id="rw" name="rw" placeholder="RW" required>
				</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" placeholder="Agama" required>
				</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>- Pilih -</option>
						<option>Sudah</option>
						<option>Belum</option>
						<option>Cerai Mati</option>
						<option>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" placeholder="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" placeholder="WNI/WNA" required>
				</div>
			</div>



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

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

    // Defines callback for scanner modal
    window.handleScannerResult = function(base64) {
        // Show Preview
        preview.src = base64;
        preview.style.display = 'block';
        // Set Hidden Input
        hiddenInput.value = base64;
    };

    inputImage.addEventListener('change', function(e) {
        var files = e.target.files;
        if (files && files.length > 0) {
            // Open Smart Scanner
            if (window.openScanner) {
                window.openScanner(files[0]);
            } else {
                alert("Scanner library not loaded!");
            }
             // Clear input so same file can be selected again if needed
             inputImage.value = ''; 
        }
    });

    // Scan Button
    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 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.jpg');
        } else if (fileInput.files.length > 0) {
            formData.append('image', fileInput.files[0]);
        } else {
             Swal.fire('Info', 'Belum ada foto 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 Dialog
                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>Alamat</td><td>${d.alamat || '-'}</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>Agama</td><td>${d.agama || '-'}</td></tr>
                                <tr><td>Status</td><td>${d.status || '-'}</td></tr>
                                <tr><td>Pekerjaan</td><td>${d.pekerjaan || '-'}</td></tr>
                                <tr><td>Warga Negara</td><td>${d.kewarganegaraan || '-'}</td></tr>
                            </table>
                            <p class="mb-0 text-muted">Gunakan data ini untuk mengisi formulir?</p>
                        </div>
                    `,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Ya, Isi Formulir',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.value) { // SweetAlert 2 uses result.value or result.isConfirmed
                        // 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];
                    // Direct match first (LK/PR)
                    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;
                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!', 'Formulir telah diisi otomatis.', 'success');
                    }
                });

            } else {
                Swal.fire('Gagal Scan', 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['Simpan'])){
		
		$target = 'foto/ktp/';
		$nama_file = @$_FILES['foto_ktp']['name'];
        
        // Cek apakah ada foto hasil crop?
        if (!empty($_POST['foto_cropped'])) {
            $data = $_POST['foto_cropped'];
            // Hapus header data URL (data:image/jpeg;base64,...)
            $parts = explode(',', $data);
            $data = $parts[1];
            $data = base64_decode($data);
            
            // Buat nama file baru
            $nama_file = "KTP-" . time() . ".jpg";
            file_put_contents($target . $nama_file, $data);
        } else {
            // Upload normal jika tidak crop
            $sumber = @$_FILES['foto_ktp']['tmp_name'];
            if(!empty($sumber)) {
                move_uploaded_file($sumber, $target.$nama_file);
            }
        }

    //mulai proses simpan data
        $nik = $_POST['nik'];
        $cek_nik = mysqli_query($koneksi, "SELECT * FROM tb_pdd WHERE nik='$nik'");
        if(mysqli_num_rows($cek_nik) > 0){
             echo "<script>
              Swal.fire({title: 'Gagal',text: 'NIK sudah terdaftar dalam sistem!',icon: 'error',confirmButtonText: 'OK'
              }).then((result) => {if (result.value){
                  window.location = 'index.php?page=add-pend';
                  }
              })</script>";
              return;
        }

        // Sanitize Input to prevent SQL Injection & Syntax Errors
        $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']);

        $sql_simpan = "INSERT INTO tb_pdd (nik, nama, tempat_lh, tgl_lh, jekel, desa, rt, rw, agama, kawin, pekerjaan, foto_ktp, status, kecamatan, kabupaten, provinsi, kewarganegaraan) VALUES (
            '$nik',
            '$nama',
			'$tempat_lh',
			'$tgl_lh',
            '$jekel',
            '$desa',
			'$rt',
			'$rw',
			'$agama',
			'$kawin',
			'$pekerjaan',
            '$nama_file',
            'Ada',
            '$kecamatan',
            '$kabupaten',
            '$provinsi',
            '$kewarganegaraan')";
        $query_simpan = mysqli_query($koneksi, $sql_simpan);
        mysqli_close($koneksi);

    if ($query_simpan) {
      echo "<script>
      Swal.fire({title: 'Tambah 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: 'Tambah Data Gagal',text: '<?php echo mysqli_error($koneksi); ?>',icon: 'error',confirmButtonText: 'OK'
      }).then((result) => {if (result.value){
          window.location = 'index.php?page=add-pend';
          }
      })</script>";
    }}
     //selesai proses simpan data
