<?php
ini_set('max_execution_time', 300); 
require "../../config/koneksi.php";
require "../../config/function.php";

$datax = http_request($setting['url_host'] . "/syncsiswa.php?token=" . $setting['token_api'] .  "&server=" . $setting['id_server']);
$sr = json_decode($datax, TRUE);
$sw = mysqli_num_rows(mysqli_query($koneksi, "SELECT * FROM siswa"));
$soal = mysqli_num_rows(mysqli_query($koneksi, "SELECT * FROM soal"));
if ($sr <> null) {
$datetime = date('Y-m-d H:i:s');
$token = $setting['token_api'];
$data[]='siswa';
$data[]='soal';
$data[]='pel';
 foreach ($data as $data) {
            $gagal = $gagal2 = $gagal3 = $gagal4 = $gagal5 = $gagal6 = $gagal7 = $gagal8 = $gagal9 = 0;
            $masuk1 = $masuk2 = $masuk3 = $masuk4 = $masuk5 = $masuk6 = $masuk7 = $masuk8 = $masuk9 = 0;
              if ($data == 'siswa') {
              $syncdata = http_request($setting['url_host'] . "/tariksiswa.php?token=" . $token);
                $sync = json_decode($syncdata, TRUE);
                if ($sync <> null AND $sw=='0') {
                    $sql = mysqli_query($koneksi, "truncate table siswa");
					
                    $i = 1;
                    foreach ($sync['siswa'] as $r) {
                        $sql = mysqli_query($koneksi, "insert into siswa
                            (id_siswa,id_kelas,idpk,nis,no_peserta,nama,level,ruang,sesi,username,password,foto,server,agama,jenis_kelamin) values 			
                            ('$r[id_siswa]','$r[id_kelas]','$r[idpk]','$r[nis]','$r[no_peserta]','" . addslashes($r['nama']) . "','$r[level]','$r[ruang]','$r[sesi]','$r[username]','$r[password]','$r[foto]','$r[server]','$r[agama]','$r[jenis_kelamin]')");

                        $qkelas = mysqli_query($koneksi, "SELECT id_kelas FROM kelas WHERE id_kelas='$r[id_kelas]'");
                        $cekkelas = mysqli_num_rows($qkelas);
                        if (!$cekkelas <> 0) {
                            $exec = mysqli_query($koneksi, "INSERT INTO kelas (id_kelas,level,nama)VALUES('$r[id_kelas]','$r[level]','$r[id_kelas]')");
                        }
                        if ($setting['jenjang'] == 'SMK' OR $setting['jenjang'] == 'SMA') {

                            $qpk = mysqli_query($koneksi, "SELECT id_pk FROM pk WHERE id_pk='$r[idpk]'");
                            $cekpk = mysqli_num_rows($qpk);
                            if (!$cekpk <> 0) {
                                $exec = mysqli_query($koneksi, "INSERT INTO pk (id_pk,program_keahlian)VALUES('$r[idpk]','$r[idpk]')");
                            }
                        }
                        $qlevel = mysqli_query($koneksi, "SELECT kode_level FROM level WHERE kode_level='$r[level]'");
                        $ceklevel = mysqli_num_rows($qlevel);
                        if (!$ceklevel <> 0) {
                            $exec = mysqli_query($koneksi, "INSERT INTO level (kode_level,keterangan)VALUES('$r[level]','$r[level]')");
                        }
                        $qruang = mysqli_query($koneksi, "SELECT kode_ruang FROM ruang WHERE kode_ruang='$r[ruang]'");
                        $cekruang = mysqli_num_rows($qruang);
                        if (!$cekruang <> 0) {
                            $exec = mysqli_query($koneksi, "INSERT INTO ruang (kode_ruang,keterangan)VALUES('$r[ruang]','$r[ruang]')");
                        }
                        $qsesi = mysqli_query($koneksi, "SELECT kode_sesi FROM sesi WHERE kode_sesi='$r[sesi]'");
                        $ceksesi = mysqli_num_rows($qsesi);
                        if (!$ceksesi <> 0) {
                            $exec = mysqli_query($koneksi, "INSERT INTO sesi (kode_sesi,nama_sesi)VALUES('$r[sesi]','$r[sesi]')");
                         }
                        $qserver = mysqli_query($koneksi, "SELECT kode_server FROM server WHERE kode_server='$r[server]'");
                        $cekserver = mysqli_num_rows($qserver);
                         if (!$cekserver <> 0) {
                       $exec = mysqli_query($koneksi, "INSERT INTO server (kode_server,nama_server,status)VALUES('$r[server]','$r[server]','aktif')");
                         }
                        if (!$sql) {
                            $gagal++;
                        } else {
                            $masuk1++;
							
                        }
                    }
				
			  
					 $exec = mysqli_query($koneksi, "update sinkron set jumlah='$masuk1', status_sinkron='1', tanggal='$datetime' where nama_data='DATA1'");
					
				 echo "
				  <h4 class='sandik text-center' style='color:red'><i class='fas fa-sync-alt'></i> Data berhasil di tarik ...</h4><b>
                
                     			   
								   ";
					
		 }
			 
								   
}
 if ($data == 'pel') {
                $syncdata = http_request($setting['url_host'] . "/syncsoal.php?token=" . $token);

                $sync = json_decode($syncdata, TRUE);

                if ($sync <> null) {
                
                    $sql = mysqli_query($koneksi, "truncate table mata_pelajaran");
                    foreach ($sync['pel'] as $pel) {
                      
                        $sqlpel = mysqli_query($koneksi, "insert into mata_pelajaran
                                (kode_mapel,nama_mapel) values 			
                                ('$pel[kode_mapel]','$pel[nama_mapel]')");
                        if (!$sqlpel) {
                            $gagal9++;
                        } else {
                            $masuk9++;
                        }
					}
                 
                    $exec = mysqli_query($koneksi, "update sinkron set jumlah='$masuk9', status_sinkron='1',tanggal='$datetime' where nama_data='DATA9'");
                 
                 } else {
                    echo '<div class="alert alert-danger alert-dismissible">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        <h4><i class="icon fa fa-ban"></i> Sinkron Data Pengaturan Gagal!</h4>
        Silahkan periksa koneksi internet dan token
      </div>';
                }
            }
					
  if ($data == 'soal') {


                $syncdata = http_request($setting['url_host'] . "/syncsoal.php?token=" . $token);

                $sync = json_decode($syncdata, TRUE);

                if ($sync <> NULL AND $soal=='0') {
                    $sql = mysqli_query($koneksi, "truncate table banksoal");
                    $sql = mysqli_query($koneksi, "truncate table soal");

                    foreach ($sync['bank'] as $banksoal) {
                       
                        if ($banksoal['status'] == 1) {
                            $sql = mysqli_query($koneksi, "insert into banksoal
                            (id_bank,kode,idpk,idguru,nama,jml_soal,jml_esai,jml_multi,jml_bs,jml_urut,tampil_pg,tampil_esai,tampil_multi,tampil_bs,tampil_urut,opsi,level,groupsoal,bobot_pg,bobot_esai,bobot_bs,bobot_multi,bobot_urut,kelas,date,status,sts,kkm,soal_agama) values 			
                            ('$banksoal[id_bank]','$banksoal[kode]','$banksoal[idpk]','$banksoal[idguru]','$banksoal[nama]','$banksoal[jml_soal]','$banksoal[jml_esai]','$banksoal[jml_multi]','$banksoal[jml_bs]','$banksoal[jml_urut]',
							'$banksoal[tampil_pg]','$banksoal[tampil_esai]','$banksoal[tampil_multi]','$banksoal[tampil_bs]','$banksoal[tampil_urut]','$banksoal[opsi]','$banksoal[level]','$banksoal[groupsoal]','$banksoal[bobot_pg]','$banksoal[bobot_esai]','$banksoal[bobot_bs]','$banksoal[bobot_multi]','$banksoal[bobot_urut]',
							'$banksoal[kelas]','$banksoal[date]','$banksoal[status]','$banksoal[sts]','$banksoal[kkm]','$banksoal[soal_agama]')");
                            if (!$sql) {
                                $gagal2++;
                            } else {
                                $masuk2++;
                            }

                            foreach ($sync['soal'] as $soal) {
                                if ($soal['id_bank'] == $banksoal['id_bank']) {
                                    $soalx = addslashes($soal['soal']);
                                    $pilA = addslashes($soal['pilA']);
                                    $pilB = addslashes($soal['pilB']);
                                    $pilC = addslashes($soal['pilC']);
                                    $pilD = addslashes($soal['pilD']);
                                    $pilE = addslashes($soal['pilE']);
                                    $sqlsoal = mysqli_query($koneksi, "insert into soal
                    (id_soal,id_bank,nomor,soal,jenis,pilA,pilB,pilC,pilD,pilE,jawaban,file,file1,fileA,fileB,fileC,fileD,fileE,ket,sts,groupsoal) values 			
                    ('$soal[id_soal]','$soal[id_bank]','$soal[nomor]','$soalx','$soal[jenis]','$pilA','$pilB','$pilC','$pilD','$pilE','$soal[jawaban]','$soal[file]','$soal[file1]','$soal[fileA]','$soal[fileB]','$soal[fileC]','$soal[fileD]','$soal[fileE]','$soal[ket]','$soal[sts]','$soal[groupsoal]')");
                               $sqlfile = mysqli_query($koneksi, "insert into file_pendukung(id_bank,nama_file) VALUES('$soal[id_bank]','$soal[file]')");    
									
									if (!$sqlsoal) {
                                        $gagal3++;
                                    } else {
                                        $masuk3++;
                                    }
                                }
                            }

                            $urls = [];
                            $i = 0;
                            foreach ($sync['file'] as $file) {

                                if ($file['id_bank'] == $banksoal['id_bank']) {
                                    $urls[$i] = $setting['web'] . "/files/" . $file['nama_file'];
                                    $i++;
                                }
                            }
                            multiple_download($urls);
                            // }
                        }
                    }
                    $exec = mysqli_query($koneksi, "update sinkron set jumlah='$masuk2', status_sinkron='1',tanggal='$datetime'  where nama_data='DATA2'");
                    $exec = mysqli_query($koneksi, "update sinkron set jumlah='$masuk3', status_sinkron='1',tanggal='$datetime' where nama_data='DATA3'");
                   
                    echo "  
  <h4 class='sandik text-center' style='color:red'><i class='fas fa-sync-alt'></i> Data berhasil di tarik ...</h4><b>
           <div id='sinfile'></div>     
		   
          <script>
	setTimeout(function(){
        $('#mysandik').modal('hide');
      }, 10000);
	window.setTimeout(function(){ 
			window.location.replace('ujian');
		} ,10000);	
    </script>       
            ";
                } else {
                    echo "<h4 class='text-center'>Gagal Tarik data... Silakan Kosongkan dulu data lokal</h4>
					<script>
					setTimeout(function(){
						$('#mysandik').modal('hide');
					  }, 10000);
					
					</script>       
					<p class='text-center' style='color:red'>Jika Tidak akan tarik Bank Soal dan Soal, abaikan hingga Form menutup selama 10 detik..</p>
					<form id='formhapusdata'  action='' class='text-center'>
					
					 <button type='submit' name='submit3' class='btn btn-sm btn-warning'><i class='fa fa-trash'></i> Reset Data</button>
					 </form>
					 
					";
					
                }
            }
			
	
			
			
}
}
 ?>

           <script>
 $('#formhapusdata').submit(function(e) {
        e.preventDefault();
        var data = new FormData(this);
        $.ajax({
            type: 'POST',
            url: 'server/sinkronreset.php',
            enctype: 'multipart/form-data',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            beforeSend: function() {},
            success: function(data) {
                Swal.fire({	
				title: '<a href="#" class="sandik" style="color:blue">Reset data sedang diproses ..</a>',				
				showConfirmButton: false,
				 animation: false,
				  customClass: 'animated tada',				  
				  imageUrl: '../dist/img/sandik_kecil.gif',
                 footer: '<a href="#"><b style="color:red">Sistem Administrasi Pendidik (SANDIK)</b></a>'
                    });
                    setTimeout(function() {
                        window.location.reload();
                    }, 2000);
            }
        })
        return false;
    });
	</script>
	

<script>
$(document).ready(function(){
$('#sinfile').load('<?= $homeurl ?>/synfile.php');
});
</script>

 