<?php
include '../../koneksi.php';

if (!isset($_GET['kelas'])) {
  die("Kelas tidak ditemukan");
}

$kelas = mysqli_real_escape_string($koneksi, $_GET['kelas']);
$ruangDefault = $kelas;

/* ======================
   AJAX CEK BENTROK
====================== */
if(isset($_POST['action']) && $_POST['action']=='cek'){
  $kelas=$_POST['kelas'];
  $hari=$_POST['hari'];
  $guru=$_POST['guru'];
  $ruang=$_POST['ruang'];
  $mulai=$_POST['jam_mulai'];
  $selesai=$_POST['jam_selesai'];

  $cek=mysqli_query($koneksi,"
    SELECT id FROM jadwal_kelas
    WHERE hari='$hari'
      AND (
        (kelas='$kelas' AND ruang='$ruang')
        OR guru='$guru'
      )
      AND ('$mulai' < jam_selesai AND '$selesai' > jam_mulai)
  ");

  echo mysqli_num_rows($cek)>0?'bentrok':'aman';
  exit;
}

/* ======================
   AJAX SIMPAN DATA
====================== */
if(isset($_POST['action']) && $_POST['action']=='simpan'){
  mysqli_query($koneksi,"
    INSERT INTO jadwal_kelas
    (kelas,hari,jam_mulai,jam_selesai,mapel,guru,ruang)
    VALUES
    (
      '{$_POST['kelas']}',
      '{$_POST['hari']}',
      '{$_POST['jam_mulai']}',
      '{$_POST['jam_selesai']}',
      '{$_POST['mapel']}',
      '{$_POST['guru']}',
      '{$_POST['ruang']}'
    )
  ");
  echo 'ok';
  exit;
}

/* ======================
   MAPEL
====================== */
$mapelIPA=[
'Al-Qur’an Hadits','Akidah Akhlak','Fiqih','SKI',
'Bahasa Indonesia','Bahasa Inggris','Bahasa Arab',
'Matematika Wajib','Matematika Peminatan',
'Fisika','Kimia','Biologi',
'Sejarah Indonesia','PPKn',
'PJOK','Seni Budaya','Prakarya'
];

$mapelIPS=[
'Al-Qur’an Hadits','Akidah Akhlak','Fiqih','SKI',
'Bahasa Indonesia','Bahasa Inggris','Bahasa Arab',
'Matematika Wajib',
'Ekonomi','Geografi','Sosiologi','Sejarah Peminatan',
'Sejarah Indonesia','PPKn',
'PJOK','Seni Budaya','Prakarya'
];

$isIPA=str_contains($kelas,'IPA');
$mapelList=$isIPA?$mapelIPA:$mapelIPS;

/* ======================
   DATA GURU
====================== */
$qGuru=mysqli_query($koneksi,"
  SELECT nama_lengkap,mapel
  FROM guru WHERE status='Aktif'
");
$guruList=[];
while($g=mysqli_fetch_assoc($qGuru)) $guruList[]=$g;
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Tambah Jadwal</title>
<link href="../../bootstrap-5.3.8-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
body{background:#f4f6f9}
.card{border-radius:18px;box-shadow:0 12px 35px rgba(0,0,0,.12)}
</style>
</head>

<body>

<div class="container-fluid mt-3">
<div class="card p-4">

<h4 class="fw-bold mb-4">
Tambah Jadwal <span class="badge bg-primary"><?=$kelas?></span>
</h4>

<form id="formJadwal">

<input type="hidden" name="kelas" value="<?=$kelas?>">

<div class="row g-3">

<div class="col-md-4">
<label>Hari</label>
<select name="hari" class="form-select" required>
<?php foreach(['Senin','Selasa','Rabu','Kamis','Jumat'] as $h): ?>
<option><?=$h?></option>
<?php endforeach;?>
</select>
</div>

<div class="col-md-4">
<label>Jam Mulai</label>
<input type="time" name="jam_mulai" id="jam_mulai" class="form-control" required>
</div>

<div class="col-md-4">
<label>Jam Selesai</label>
<input type="time" name="jam_selesai" id="jam_selesai" class="form-control" readonly required>
</div>

<div class="col-md-6">
<label>Mapel</label>
<select name="mapel" id="mapel" class="form-select" required>
<option value="">-- Pilih --</option>
<?php foreach($mapelList as $m): ?>
<option><?=$m?></option>
<?php endforeach;?>
</select>
</div>

<div class="col-md-6">
<label>Guru</label>
<select name="guru" id="guru" class="form-select" required></select>
</div>

<div class="col-md-6">
<label>Ruang</label>
<input type="text" name="ruang" id="ruang" class="form-control" value="<?=$ruangDefault?>">
</div>

</div>

<div class="mt-4">
<button type="submit" class="btn btn-success rounded-pill px-4">
Simpan
</button>
</div>

</form>
</div>
</div>

<script>
const guruData=<?=json_encode($guruList)?>;

/* AUTO JAM +60 */
jam_mulai.onchange=()=>{
 let [h,m]=jam_mulai.value.split(':');
 h=(parseInt(h)+1)%24;
 jam_selesai.value=String(h).padStart(2,'0')+':'+m;
};

/* FILTER GURU */
mapel.onchange=()=>{
 guru.innerHTML='';
 guruData.forEach(g=>{
  if(g.mapel===mapel.value){
    guru.add(new Option(g.nama_lengkap,g.nama_lengkap));
  }
 });
};

/* SUBMIT FULL AJAX */
formJadwal.onsubmit=(e)=>{
 e.preventDefault();
 const fd=new FormData(formJadwal);
 fd.append('action','cek');

 fetch('',{method:'POST',body:fd})
 .then(r=>r.text())
 .then(res=>{
  if(res==='bentrok'){
    Swal.fire({
      toast:true,
      position:'top-end',
      icon:'warning',
      title:'Jadwal Bentrok',
      timer:2500,
      showConfirmButton:false
    });
  }else{
    fd.set('action','simpan');
    fetch('',{method:'POST',body:fd})
    .then(r=>r.text())
    .then(()=>{
      Swal.fire({
        icon:'success',
        title:'Berhasil',
        text:'Jadwal tersimpan',
        timer:1500,
        showConfirmButton:false
      }).then(()=>{
        parent.document.getElementById('iframeContent').src=
        'kelola_jadwal/jadwal.php?kelas=<?=$kelas?>';
      });
    });
  }
 });
};
</script>

</body>
</html>
