<?php
include 'koneksi.php';
cek_akses(['Super Admin', 'Kepala']);

$response = ['success' => false, 'message' => '', 'total' => 0, 'success_count' => 0, 'error_count' => 0, 'errors' => []];

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['data'])) {
    $data = json_decode($_POST['data'], true);
    $response['total'] = count($data);
    $success_count = 0;
    $error_count = 0;
    $errors = [];
    
    foreach($data as $index => $row) {
        // Pastikan NIS tidak berubah format - baca sebagai string
        $nis = trim((string)$row[0]);
        $nama = trim((string)$row[1]);
        $kelas_nama = trim((string)$row[2]);
        $unit = trim((string)$row[3]);
        $status = isset($row[4]) ? trim((string)$row[4]) : 'Aktif';
        
        // Validasi NIS tidak boleh kosong
        if(empty($nis)) {
            $error_count++;
            $errors[] = "Baris " . ($index + 2) . ": NIS tidak boleh kosong";
            continue;
        }
        
        // Validasi data lainnya
        if(empty($nama) || empty($kelas_nama) || empty($unit)) {
            $error_count++;
            $errors[] = "Baris " . ($index + 2) . ": Data tidak lengkap (Nama, Kelas, Unit harus diisi)";
            continue;
        }
        
        // Cari atau buat kelas
        $query_kelas = "SELECT id FROM classes WHERE name = '$kelas_nama' AND unit = '$unit'";
        $result_kelas = mysqli_query($conn, $query_kelas);
        
        if(!$result_kelas) {
            $error_count++;
            $errors[] = "Baris " . ($index + 2) . ": Error query kelas - " . mysqli_error($conn);
            continue;
        }
        
        if(mysqli_num_rows($result_kelas) > 0) {
            $kelas = mysqli_fetch_assoc($result_kelas);
            $kelas_id = $kelas['id'];
        } else {
            // Buat kelas baru
            $insert_kelas = "INSERT INTO classes (name, unit) VALUES ('$kelas_nama', '$unit')";
            if(mysqli_query($conn, $insert_kelas)) {
                $kelas_id = mysqli_insert_id($conn);
            } else {
                $error_count++;
                $errors[] = "Baris " . ($index + 2) . ": Gagal membuat kelas baru - " . mysqli_error($conn);
                continue;
            }
        }
        
        // Cek apakah siswa sudah ada berdasarkan NIS
        $cek_siswa = "SELECT id FROM students WHERE nis = '$nis'";
        $result_cek = mysqli_query($conn, $cek_siswa);
        
        if(!$result_cek) {
            $error_count++;
            $errors[] = "Baris " . ($index + 2) . ": Error cek siswa - " . mysqli_error($conn);
            continue;
        }
        
        if(mysqli_num_rows($result_cek) == 0) {
            // Insert siswa baru dengan NIS asli
            $query = "INSERT INTO students (nis, name, class_id, unit, status) VALUES ('$nis', '$nama', '$kelas_id', '$unit', '$status')";
            if(mysqli_query($conn, $query)) {
                $success_count++;
            } else {
                $error_count++;
                $errors[] = "Baris " . ($index + 2) . ": Gagal menyimpan - " . mysqli_error($conn);
            }
        } else {
            // Update data siswa jika NIS sudah ada
            $query = "UPDATE students SET name='$nama', class_id='$kelas_id', unit='$unit', status='$status' WHERE nis='$nis'";
            if(mysqli_query($conn, $query)) {
                $success_count++;
            } else {
                $error_count++;
                $errors[] = "Baris " . ($index + 2) . ": Gagal update - " . mysqli_error($conn);
            }
        }
    }
    
    $response['success'] = true;
    $response['success_count'] = $success_count;
    $response['error_count'] = $error_count;
    $response['errors'] = $errors;
    $response['message'] = "Import selesai! Berhasil: $success_count, Gagal: $error_count";
}

echo json_encode($response);
?>