<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once '../koneksi.php';

// 1. Ambil ID Tahun Pelajaran & Semester Aktif
$q_tp = mysqli_query($koneksi, "SELECT id_tp_tahun FROM tahun_pelajaran WHERE status = 'Aktif' LIMIT 1");
$data_tp = mysqli_fetch_assoc($q_tp);
$id_tp_aktif = $data_tp['id_tp_tahun'] ?? 0;

$q_smt = mysqli_query($koneksi, "SELECT id_semester FROM semester WHERE status = 'Aktif' LIMIT 1");
$data_smt = mysqli_fetch_assoc($q_smt);
$id_sem_aktif = $data_smt['id_semester'] ?? 0;

if ($id_tp_aktif == 0 || $id_sem_aktif == 0) {
    echo "<script>alert('Error: Pastikan Tahun Pelajaran & Semester Aktif sudah disetting!'); window.location='guru.php';</script>";
    exit;
}
if (isset($_GET['hapus'])) {
    $id_guru = mysqli_real_escape_string($koneksi, $_GET['hapus']);
    
    // 1. Hapus dulu tugas-tugas guru tersebut agar tidak ada data yatim (orphan)
    mysqli_query($koneksi, "DELETE FROM tugas_guru WHERE id_guru = '$id_guru'");
    
    // 2. Baru hapus data gurunya
    $hapus = mysqli_query($koneksi, "DELETE FROM master_guru WHERE id_guru = '$id_guru'");
    
    if ($hapus) {
        echo "<script>alert('Guru berhasil dihapus!'); window.location='guru.php';</script>";
    } else {
        echo "<script>alert('Gagal: " . mysqli_error($koneksi) . "'); window.location='guru.php';</script>";
    }
    exit;
}
if (isset($_POST['simpan'])) {
    $id_guru = mysqli_real_escape_string($koneksi, $_POST['id_guru']);
    
    // Mulai Transaksi
    mysqli_begin_transaction($koneksi);

    try {
        // 2. Hapus tugas lama
        $query_del = "DELETE FROM tugas_guru 
                      WHERE id_guru = '$id_guru' 
                      AND id_semester = '$id_sem_aktif' 
                      AND id_tp_tahun = '$id_tp_aktif'";
        
        if (!mysqli_query($koneksi, $query_del)) {
            throw new Exception(mysqli_error($koneksi));
        }

        // 3. Masukkan data baru
        if (!empty($_POST['tugas'])) {
            foreach ($_POST['tugas'] as $val) {
                $data = explode('_', $val);
                $id_m = $data[0];
                $id_r = $data[1];

                $query_ins = "INSERT INTO tugas_guru (id_guru, id_mapel, id_rombel, id_semester, id_tp_tahun) 
                              VALUES ('$id_guru', '$id_m', '$id_r', '$id_sem_aktif', '$id_tp_aktif')";
                
                if (!mysqli_query($koneksi, $query_ins)) {
                    throw new Exception(mysqli_error($koneksi));
                }
            }
        }

        mysqli_commit($koneksi);
        echo "<script>alert('Data tugas berhasil disimpan!'); window.location='guru.php';</script>";

    } catch (Exception $e) {
        mysqli_rollback($koneksi);
        echo "<script>alert('Terjadi kesalahan: " . $e->getMessage() . "'); window.location='guru.php';</script>";
    }
}
?>