<?php
require_once '../../includes/functions.php';
require_once '../../includes/validation.php';
requireAdmin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['data_file'])) {
    header('Location: list.php?error=No file uploaded');
    exit;
}

if ($_FILES['data_file']['error'] !== UPLOAD_ERR_OK) {
    header('Location: list.php?error=Gagal upload file. Kode error: ' . $_FILES['data_file']['error']);
    exit;
}

// Hanya terima CSV
$fileName = $_FILES['data_file']['name'];
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

if (!in_array($fileExt, ['csv', 'txt'])) {
    header('Location: list.php?error=Hanya file CSV yang didukung. Simpan file Excel Anda sebagai CSV terlebih dahulu.');
    exit;
}

$updateIfExists = isset($_POST['update_if_exists']);
$tmpFile = $_FILES['data_file']['tmp_name'];

$successCount = 0;
$errorCount = 0;
$errors = [];

global $pdo;

// Fungsi manual untuk insert/update (menghindari error parameter)
function insertUser($data) {
    global $pdo;
    $sql = "INSERT INTO users (username, password, nama_lengkap, role, status, created_at) 
            VALUES (:username, :password, :nama_lengkap, :role, :status, :created_at)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($data);
    return $pdo->lastInsertId();
}

function insertGuru($data) {
    global $pdo;
    $sql = "INSERT INTO guru (user_id, nip, nama, jenis_kelamin, tempat_lahir, tanggal_lahir, pendidikan_terakhir, status, created_at) 
            VALUES (:user_id, :nip, :nama, :jenis_kelamin, :tempat_lahir, :tanggal_lahir, :pendidikan_terakhir, :status, :created_at)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($data);
    return $pdo->lastInsertId();
}

function updateGuru($id, $data) {
    global $pdo;
    $sql = "UPDATE guru SET 
            nama = :nama,
            jenis_kelamin = :jenis_kelamin,
            tempat_lahir = :tempat_lahir,
            tanggal_lahir = :tanggal_lahir,
            pendidikan_terakhir = :pendidikan_terakhir,
            status = :status,
            updated_at = :updated_at
            WHERE id = :id";
    $data['id'] = $id;
    $stmt = $pdo->prepare($sql);
    return $stmt->execute($data);
}

function updateUser($id, $data) {
    global $pdo;
    $sql = "UPDATE users SET 
            username = :username,
            nama_lengkap = :nama_lengkap,
            status = :status,
            updated_at = :updated_at
            WHERE id = :id";
    $data['id'] = $id;
    $stmt = $pdo->prepare($sql);
    return $stmt->execute($data);
}

function updateUserGuruId($userId, $guruId) {
    global $pdo;
    $sql = "UPDATE users SET guru_id = :guru_id WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    return $stmt->execute(['guru_id' => $guruId, 'id' => $userId]);
}

function getUserByGuruId($guruId) {
    global $pdo;
    $sql = "SELECT * FROM users WHERE guru_id = :guru_id";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['guru_id' => $guruId]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function getGuruByNip($nip) {
    global $pdo;
    $sql = "SELECT * FROM guru WHERE nip = :nip";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['nip' => $nip]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function isUsernameExists($username) {
    global $pdo;
    $sql = "SELECT id FROM users WHERE username = :username";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['username' => $username]);
    return $stmt->fetch() ? true : false;
}

// Fungsi utama proses baris
function processRow($data, $rowNumber, $updateIfExists) {
    global $pdo, $errors, $successCount, $errorCount;
    
    if (count($data) < 7) {
        $errors[] = "Baris " . ($rowNumber + 1) . ": Jumlah kolom tidak lengkap (harus 7 kolom)";
        $errorCount++;
        return false;
    }
    
    // Bersihkan data
    $nip = trim($data[0] ?? '');
    $nama = trim($data[1] ?? '');
    $jenis_kelamin = strtoupper(trim($data[2] ?? ''));
    $tempat_lahir = trim($data[3] ?? '');
    $tanggal_lahir_raw = trim($data[4] ?? '');
    $pendidikan_terakhir = trim($data[5] ?? '');
    $status = strtolower(trim($data[6] ?? 'aktif'));
    
    // Validasi
    $rowErrors = [];
    
    if (empty($nip)) $rowErrors[] = "NIP wajib diisi";
    if (empty($nama)) $rowErrors[] = "Nama Lengkap wajib diisi";
    if (empty($jenis_kelamin) || !in_array($jenis_kelamin, ['L', 'P'])) 
        $rowErrors[] = "Jenis Kelamin harus L atau P";
    
    // Format tanggal
    $tanggal_lahir = null;
    if (!empty($tanggal_lahir_raw)) {
        $tanggal = date_create($tanggal_lahir_raw);
        if ($tanggal) {
            $tanggal_lahir = $tanggal->format('Y-m-d');
        } else {
            $rowErrors[] = "Format Tanggal Lahir tidak valid (gunakan YYYY-MM-DD)";
        }
    }
    
    // Status
    if (!in_array($status, ['aktif', 'nonaktif'])) $status = 'aktif';
    
    if (!empty($rowErrors)) {
        $errors[] = "Baris " . ($rowNumber + 1) . ": " . implode(', ', $rowErrors);
        $errorCount++;
        return false;
    }
    
    // Mulai transaksi
    $pdo->beginTransaction();
    
    try {
        // Cek apakah guru sudah ada
        $existingGuru = getGuruByNip($nip);
        
        if ($existingGuru && !$updateIfExists) {
            $errors[] = "Baris " . ($rowNumber + 1) . ": NIP $nip sudah ada (skip)";
            $errorCount++;
            $pdo->rollBack();
            return false;
        }
        
        // Username dari NIP, jika sudah dipakai akun lain tambah suffix
        $username = $nip;
        $suffix = 1;
        while (isUsernameExists($username)) {
            $username = $nip . '_' . $suffix;
            $suffix++;
        }

        $now = date('Y-m-d H:i:s');
        
        if ($existingGuru) {
            // UPDATE GURU YANG SUDAH ADA
            
            // Update data guru
            updateGuru($existingGuru['id'], [
                'nama' => $nama,
                'jenis_kelamin' => $jenis_kelamin,
                'tempat_lahir' => $tempat_lahir,
                'tanggal_lahir' => $tanggal_lahir,
                'pendidikan_terakhir' => $pendidikan_terakhir,
                'status' => $status,
                'updated_at' => $now
            ]);
            
            // Cek user
            $existingUser = getUserByGuruId($existingGuru['id']);
            
            if ($existingUser) {
                // Update user yang ada — username & password TIDAK diubah
                updateUser($existingUser['id'], [
                    'username' => $existingUser['username'],
                    'nama_lengkap' => $nama,
                    'status' => $status,
                    'updated_at' => $now
                ]);
            } else {
                // Buat user baru dengan username & password dari NIP
                $userId = insertUser([
                    'username' => $username,
                    'password' => password_hash($nip, PASSWORD_DEFAULT),
                    'nama_lengkap' => $nama,
                    'role' => 'guru',
                    'status' => $status,
                    'created_at' => $now
                ]);
                
                // Update guru dengan user_id
                $sql = "UPDATE guru SET user_id = :user_id WHERE id = :id";
                $stmt = $pdo->prepare($sql);
                $stmt->execute(['user_id' => $userId, 'id' => $existingGuru['id']]);
            }
            
        } else {
            // INSERT GURU BARU
            
            // 1. Insert user dulu
            $userId = insertUser([
                'username' => $username,
                'password' => password_hash($nip, PASSWORD_DEFAULT),
                'nama_lengkap' => $nama,
                'role' => 'guru',
                'status' => $status,
                'created_at' => $now
            ]);
            
            // 2. Insert guru dengan user_id yang valid
            $guruId = insertGuru([
                'user_id' => $userId,
                'nip' => $nip,
                'nama' => $nama,
                'jenis_kelamin' => $jenis_kelamin,
                'tempat_lahir' => $tempat_lahir,
                'tanggal_lahir' => $tanggal_lahir,
                'pendidikan_terakhir' => $pendidikan_terakhir,
                'status' => $status,
                'created_at' => $now
            ]);
            
            // 3. Update users dengan guru_id
            updateUserGuruId($userId, $guruId);
        }
        
        $pdo->commit();
        $successCount++;
        return true;
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $errors[] = "Baris " . ($rowNumber + 1) . ": Error - " . $e->getMessage();
        $errorCount++;
        return false;
    }
}

// Proses file CSV
if (($handle = fopen($tmpFile, "r")) !== FALSE) {
    // Baca header (skip)
    $header = fgetcsv($handle);
    $rowNumber = 1;
    
    while (($data = fgetcsv($handle)) !== FALSE) {
        $rowNumber++;
        
        // Skip baris kosong atau komentar
        if (empty(array_filter($data)) || (isset($data[0]) && strpos(trim($data[0]), '#') === 0)) {
            continue;
        }
        
        processRow($data, $rowNumber, $updateIfExists);
    }
    fclose($handle);
} else {
    header('Location: list.php?error=Gagal membaca file CSV');
    exit;
}

// Hasil
$message = "Berhasil import $successCount data guru";
if ($errorCount > 0) {
    $message .= ", $errorCount data gagal";
}

if ($errorCount > 0) {
    $errorMessage = $message . ". " . implode('; ', array_slice($errors, 0, 5));
    if (count($errors) > 5) {
        $errorMessage .= " dan " . (count($errors) - 5) . " error lainnya";
    }
    header('Location: list.php?error=' . urlencode($errorMessage));
} else {
    header('Location: list.php?success=' . urlencode($message));
}
exit;
?>