<?php
include 'koneksi.php';

// Hanya Super Admin yang bisa import user
if($_SESSION['role'] != 'Super Admin') {
    echo json_encode(['success' => false, 'message' => 'Akses ditolak!']);
    exit();
}

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

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 = [];
    
    $valid_roles = ['Super Admin', 'Pimpinan', 'Kepala', 'Guru'];
    $valid_units = ['MIJ', 'Kelompok Bermain', 'Raudhatul Athfal', 'Madrasah Ibtidaiyah', 'Madrasah Tsanawiyah', 'Madrasah Aliyah', 'Istiqlal Boarding School'];
    
    foreach($data as $index => $row) {
        $username = mysqli_real_escape_string($conn, trim($row[0]));
        $password = md5(trim($row[1]));
        $full_name = mysqli_real_escape_string($conn, trim($row[2]));
        $role = mysqli_real_escape_string($conn, trim($row[3]));
        $unit = mysqli_real_escape_string($conn, trim($row[4]));
        
        // Validasi data tidak boleh kosong
        if(empty($username) || empty($row[1]) || empty($full_name) || empty($role) || empty($unit)) {
            $error_count++;
            $errors[] = "Baris " . ($index + 2) . ": Data tidak lengkap";
            continue;
        }
        
        // Validasi role
        if(!in_array($role, $valid_roles)) {
            $error_count++;
            $errors[] = "Baris " . ($index + 2) . ": Role '$role' tidak valid";
            continue;
        }
        
        // Validasi unit
        if(!in_array($unit, $valid_units)) {
            $error_count++;
            $errors[] = "Baris " . ($index + 2) . ": Unit '$unit' tidak valid";
            continue;
        }
        
        // Cek apakah username sudah ada
        $cek_user = "SELECT id FROM users WHERE username = '$username'";
        $result_cek = mysqli_query($conn, $cek_user);
        
        if(mysqli_num_rows($result_cek) > 0) {
            $error_count++;
            $errors[] = "Baris " . ($index + 2) . ": Username '$username' sudah terdaftar";
            continue;
        }
        
        $query = "INSERT INTO users (username, password, full_name, role, unit) 
                  VALUES ('$username', '$password', '$full_name', '$role', '$unit')";
        
        if(mysqli_query($conn, $query)) {
            $success_count++;
        } else {
            $error_count++;
            $errors[] = "Baris " . ($index + 2) . ": Gagal menyimpan - " . mysqli_error($conn);
        }
    }
    
    $response['success'] = true;
    $response['success_count'] = $success_count;
    $response['error_count'] = $error_count;
    $response['message'] = "Import selesai! " . ($error_count > 0 ? "Beberapa data gagal diimport." : "Semua data berhasil diimport.");
    $response['errors'] = $errors;
}

echo json_encode($response);
?>