<?php
session_start();
require_once '../../config/database.php';
require_once '../../config/function.php';

// Cek login
checkLogin();

$current_user = getCurrentUser();
$tahun_ajaran = getTahunAjaranAktif();
$tahun_ajaran_id = $tahun_ajaran ? $tahun_ajaran['id_tahun_ajaran'] : 0;

// Ambil ID dari URL
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Ambil data siswa
$query = "SELECT s.*, 
          u.username, 
          u.is_active as user_active,
          sk.id_kelas as current_kelas_id
          FROM bkcare_siswa s
          LEFT JOIN bkcare_users u ON s.id_user = u.id_user
          LEFT JOIN bkcare_siswa_kelas sk ON s.id_siswa = sk.id_siswa AND sk.status = 'aktif'
          WHERE s.id_siswa = $id";
$result = mysqli_query($conn, $query);
$data = mysqli_fetch_assoc($result);

if (!$data) {
    $_SESSION['error_message'] = 'Data siswa tidak ditemukan';
    $_SESSION['error_title'] = 'Error!';
    header('Location: index.php');
    exit;
}

// Ambil data kelas untuk dropdown
$kelas_query = "SELECT * FROM bkcare_kelas WHERE id_tahun_ajaran = '$tahun_ajaran_id' ORDER BY nama_kelas";
$kelas_result = mysqli_query($conn, $kelas_query);

// Proses update data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nis = mysqli_real_escape_string($conn, $_POST['nis']);
    $nama = mysqli_real_escape_string($conn, $_POST['nama']);
    $jenis_kelamin = mysqli_real_escape_string($conn, $_POST['jenis_kelamin']);
    $id_kelas = !empty($_POST['id_kelas']) ? (int)$_POST['id_kelas'] : null;
    $alamat = mysqli_real_escape_string($conn, $_POST['alamat']);
    $no_hp = mysqli_real_escape_string($conn, $_POST['no_hp']);
    $nama_orangtua = mysqli_real_escape_string($conn, $_POST['nama_orangtua']);
    $no_hp_orangtua = mysqli_real_escape_string($conn, $_POST['no_hp_orangtua']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    
    // Validasi
    $errors = [];
    
    if (empty($nis)) {
        $errors[] = 'NIS harus diisi';
    } else {
        // Cek duplikat NIS kecuali data sendiri
        $check_nis = mysqli_query($conn, "SELECT * FROM bkcare_siswa WHERE nis = '$nis' AND id_siswa != $id");
        if (mysqli_num_rows($check_nis) > 0) {
            $errors[] = 'NIS sudah terdaftar';
        }
    }
    
    if (empty($nama)) {
        $errors[] = 'Nama siswa harus diisi';
    }
    
    if (empty($jenis_kelamin)) {
        $errors[] = 'Jenis kelamin harus dipilih';
    }
    
    if (empty($status)) {
        $errors[] = 'Status siswa harus dipilih';
    }
    
    // Jika tidak ada error
    if (empty($errors)) {
        // Mulai transaksi
        mysqli_begin_transaction($conn);
        
        try {
            // 1. Update data user jika ada
            if ($data['id_user']) {
                // Update username di tabel users jika NIS berubah
                $new_username = $nis;
                
                // Cek apakah username baru sudah digunakan user lain
                $check_username = mysqli_query($conn, "SELECT * FROM bkcare_users WHERE username = '$new_username' AND id_user != {$data['id_user']}");
                if (mysqli_num_rows($check_username) > 0) {
                    // Jika sudah ada, buat username unik
                    $i = 1;
                    while (mysqli_num_rows(mysqli_query($conn, "SELECT * FROM bkcare_users WHERE username = '$new_username' AND id_user != {$data['id_user']}"))) {
                        $new_username = $nis . $i;
                        $i++;
                    }
                }
                
                $query_user = "UPDATE bkcare_users 
                              SET nama = '$nama', username = '$new_username' 
                              WHERE id_user = {$data['id_user']}";
                
                if (!mysqli_query($conn, $query_user)) {
                    throw new Exception('Gagal memperbarui data user: ' . mysqli_error($conn));
                }
            } else {
                // Jika belum punya akun, buat akun baru
                $username = $nis;
                $password_default = password_hash('123', PASSWORD_DEFAULT);
                
                // Cek apakah username sudah ada
                $check_username = mysqli_query($conn, "SELECT * FROM bkcare_users WHERE username = '$username'");
                if (mysqli_num_rows($check_username) > 0) {
                    // Jika username sudah ada, buat username unik
                    $i = 1;
                    $new_username = $username;
                    while (mysqli_num_rows(mysqli_query($conn, "SELECT * FROM bkcare_users WHERE username = '$new_username'"))) {
                        $new_username = $username . $i;
                        $i++;
                    }
                    $username = $new_username;
                }
                
                $query_user = "INSERT INTO bkcare_users (nama, username, password, role, is_active) 
                              VALUES ('$nama', '$username', '$password_default', 'siswa', '1')";
                
                if (!mysqli_query($conn, $query_user)) {
                    throw new Exception('Gagal membuat akun user: ' . mysqli_error($conn));
                }
                
                $id_user = mysqli_insert_id($conn);
                
                // Update id_user di tabel siswa
                $update_siswa = "UPDATE bkcare_siswa SET id_user = $id_user WHERE id_siswa = $id";
                if (!mysqli_query($conn, $update_siswa)) {
                    throw new Exception('Gagal mengupdate id_user: ' . mysqli_error($conn));
                }
            }
            
            // 2. Update tabel siswa
            $query = "UPDATE bkcare_siswa 
                      SET nis = '$nis', 
                          nama = '$nama', 
                          jenis_kelamin = '$jenis_kelamin', 
                          alamat = '$alamat', 
                          no_hp = '$no_hp', 
                          nama_orangtua = '$nama_orangtua', 
                          no_hp_orangtua = '$no_hp_orangtua',
                          status = '$status'
                      WHERE id_siswa = $id";
            
            if (!mysqli_query($conn, $query)) {
                throw new Exception('Gagal memperbarui data siswa: ' . mysqli_error($conn));
            }
            
            // 3. Update kelas siswa
            // Hapus kelas lama yang aktif
            mysqli_query($conn, "DELETE FROM bkcare_siswa_kelas WHERE id_siswa = $id AND status = 'aktif'");
            
            // Insert kelas baru jika dipilih
            if ($id_kelas) {
                $query_kelas = "INSERT INTO bkcare_siswa_kelas (id_siswa, id_kelas, id_tahun_ajaran, status) 
                                VALUES ($id, $id_kelas, '$tahun_ajaran_id', 'aktif')";
                
                if (!mysqli_query($conn, $query_kelas)) {
                    throw new Exception('Gagal memperbarui data kelas siswa: ' . mysqli_error($conn));
                }
            }
            
            mysqli_commit($conn);
            
            $_SESSION['success_message'] = 'Data siswa <strong>' . $nama . '</strong> berhasil diperbarui';
            $_SESSION['success_title'] = 'Berhasil!';
            
            header('Location: index.php');
            exit;
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            
            $_SESSION['error_message'] = $e->getMessage();
            $_SESSION['error_title'] = 'Gagal!';
            
            header('Location: edit.php?id=' . $id);
            exit;
        }
    } else {
        $_SESSION['warning_message'] = implode('<br>', $errors);
        $_SESSION['warning_title'] = 'Validasi Gagal!';
        
        header('Location: edit.php?id=' . $id);
        exit;
    }
}

include '../../includes/header.php';
include '../../includes/navbar.php';
?>

<!-- Main Content -->
<main class="container mx-auto px-4 py-6">
    <div class="max-w-3xl mx-auto">
        <!-- Header -->
        <div class="flex items-center mb-6">
            <a href="index.php" class="text-gray-600 hover:text-purple-600 transition mr-4">
                <i class="fas fa-arrow-left text-xl"></i>
            </a>
            <div>
                <h1 class="text-2xl font-bold text-gray-800 flex items-center">
                    <i class="fas fa-edit text-purple-600 mr-3"></i>
                    Edit Data Siswa
                </h1>
                <p class="text-gray-600 text-sm mt-1">Edit data siswa: <span class="font-semibold"><?= htmlspecialchars($data['nama']) ?></span></p>
            </div>
        </div>

        <!-- Alert Notification -->
        <?php if (isset($_SESSION['warning_message'])): ?>
        <div id="alert-notification" class="mb-6 rounded-lg p-4 bg-yellow-50 border-l-4 border-yellow-500 shadow-md">
            <div class="flex items-start">
                <div class="flex-shrink-0">
                    <i class="fas fa-exclamation-triangle text-yellow-500 text-xl"></i>
                </div>
                <div class="ml-3 flex-1">
                    <h3 class="text-sm font-medium text-yellow-800"><?= $_SESSION['warning_title'] ?></h3>
                    <div class="mt-1 text-sm text-yellow-700"><?= $_SESSION['warning_message'] ?></div>
                </div>
                <div class="ml-auto pl-3">
                    <button onclick="this.parentElement.parentElement.parentElement.remove()" class="inline-flex text-yellow-500 hover:text-yellow-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
        <?php 
        unset($_SESSION['warning_message']);
        unset($_SESSION['warning_title']);
        endif; 
        ?>

        <?php if (isset($_SESSION['error_message'])): ?>
        <div id="alert-notification" class="mb-6 rounded-lg p-4 bg-red-50 border-l-4 border-red-500 shadow-md">
            <div class="flex items-start">
                <div class="flex-shrink-0">
                    <i class="fas fa-exclamation-circle text-red-500 text-xl"></i>
                </div>
                <div class="ml-3 flex-1">
                    <h3 class="text-sm font-medium text-red-800"><?= $_SESSION['error_title'] ?></h3>
                    <div class="mt-1 text-sm text-red-700"><?= $_SESSION['error_message'] ?></div>
                </div>
                <div class="ml-auto pl-3">
                    <button onclick="this.parentElement.parentElement.parentElement.remove()" class="inline-flex text-red-500 hover:text-red-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
        <?php 
        unset($_SESSION['error_message']);
        unset($_SESSION['error_title']);
        endif; 
        ?>

        <!-- Info Akun -->
        <?php if ($data['id_user']): ?>
        <div class="bg-green-50 border-l-4 border-green-500 p-4 mb-6 rounded-lg">
            <div class="flex items-center">
                <i class="fas fa-info-circle text-green-500 mr-3 text-xl"></i>
                <div>
                    <p class="text-green-700 font-medium">Informasi Akun:</p>
                    <p class="text-green-600 text-sm">
                        Username: <strong><?= $data['username'] ?></strong> | 
                        Status: <strong><?= $data['user_active'] == '1' ? 'Aktif' : 'Nonaktif' ?></strong>
                    </p>
                </div>
            </div>
        </div>
        <?php else: ?>
        <div class="bg-yellow-50 border-l-4 border-yellow-500 p-4 mb-6 rounded-lg">
            <div class="flex items-center">
                <i class="fas fa-exclamation-triangle text-yellow-500 mr-3 text-xl"></i>
                <div>
                    <p class="text-yellow-700 font-medium">Tidak Ada Akun!</p>
                    <p class="text-yellow-600 text-sm">Siswa ini tidak memiliki akun login. Akun akan dibuat otomatis saat menyimpan data.</p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Form -->
        <div class="card-stat p-8">
            <form action="" method="POST" id="editForm" class="space-y-6">
                <!-- NIS dan Nama -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-id-card text-purple-600 mr-2"></i>
                            NIS <span class="text-red-500">*</span>
                        </label>
                        <input type="text" 
                               name="nis" 
                               class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50"
                               placeholder="Masukkan NIS"
                               value="<?= htmlspecialchars($data['nis']) ?>"
                               required>
                        <p class="text-xs text-gray-500 mt-1">NIS akan digunakan sebagai username</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-user text-purple-600 mr-2"></i>
                            Nama Lengkap <span class="text-red-500">*</span>
                        </label>
                        <input type="text" 
                               name="nama" 
                               class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50"
                               placeholder="Masukkan nama lengkap"
                               value="<?= htmlspecialchars($data['nama']) ?>"
                               required>
                    </div>
                </div>

                <!-- Jenis Kelamin dan Kelas -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-venus-mars text-purple-600 mr-2"></i>
                            Jenis Kelamin <span class="text-red-500">*</span>
                        </label>
                        <div class="flex space-x-4">
                            <label class="flex items-center p-3 border border-gray-300 rounded-xl hover:bg-purple-50 transition cursor-pointer flex-1">
                                <input type="radio" 
                                       name="jenis_kelamin" 
                                       value="L" 
                                       class="mr-2 text-purple-600 focus:ring-purple-500"
                                       <?= $data['jenis_kelamin'] == 'L' ? 'checked' : '' ?>
                                       required>
                                <i class="fas fa-mars text-blue-500 mr-2"></i>
                                <span class="text-sm font-medium text-gray-700">Laki-laki</span>
                            </label>
                            <label class="flex items-center p-3 border border-gray-300 rounded-xl hover:bg-purple-50 transition cursor-pointer flex-1">
                                <input type="radio" 
                                       name="jenis_kelamin" 
                                       value="P" 
                                       class="mr-2 text-purple-600 focus:ring-purple-500"
                                       <?= $data['jenis_kelamin'] == 'P' ? 'checked' : '' ?>
                                       required>
                                <i class="fas fa-venus text-pink-500 mr-2"></i>
                                <span class="text-sm font-medium text-gray-700">Perempuan</span>
                            </label>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-school text-purple-600 mr-2"></i>
                            Kelas
                        </label>
                        <select name="id_kelas" class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50">
                            <option value="">-- Pilih Kelas --</option>
                            <?php while($kelas = mysqli_fetch_assoc($kelas_result)): ?>
                                <option value="<?= $kelas['id_kelas'] ?>" 
                                    <?= ($data['current_kelas_id'] ?? '') == $kelas['id_kelas'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($kelas['nama_kelas']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>

                <!-- Alamat -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-map-marker-alt text-purple-600 mr-2"></i>
                        Alamat
                    </label>
                    <textarea name="alamat" rows="3" 
                              class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50"
                              placeholder="Masukkan alamat lengkap"><?= htmlspecialchars($data['alamat']) ?></textarea>
                </div>

                <!-- Kontak Siswa -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fab fa-whatsapp text-purple-600 mr-2"></i>
                            No. HP Siswa
                        </label>
                        <input type="text" 
                               name="no_hp" 
                               class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50"
                               placeholder="Contoh: 08123456789"
                               value="<?= htmlspecialchars($data['no_hp']) ?>">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-user-tie text-purple-600 mr-2"></i>
                            Nama Orang Tua
                        </label>
                        <input type="text" 
                               name="nama_orangtua" 
                               class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50"
                               placeholder="Nama orang tua/wali"
                               value="<?= htmlspecialchars($data['nama_orangtua']) ?>">
                    </div>
                </div>

                <!-- Status Siswa dan No. HP Orang Tua (SEJAJAR) - Sesuai dengan tambah.php -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fab fa-whatsapp text-purple-600 mr-2"></i>
                            No. HP Orang Tua
                        </label>
                        <input type="text" 
                               name="no_hp_orangtua" 
                               class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50"
                               placeholder="Contoh: 08123456789"
                               value="<?= htmlspecialchars($data['no_hp_orangtua']) ?>">
                        <p class="text-xs text-gray-500 mt-1">Nomor HP orang tua/wali siswa</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-info-circle text-purple-600 mr-2"></i>
                            Status Siswa <span class="text-red-500">*</span>
                        </label>
                        <select name="status" class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50" required>
                            <option value="">-- Pilih Status --</option>
                            <option value="aktif" <?= $data['status'] == 'aktif' ? 'selected' : '' ?>>Aktif</option>
                            <option value="lulus" <?= $data['status'] == 'lulus' ? 'selected' : '' ?>>Lulus</option>
                            <option value="pindah" <?= $data['status'] == 'pindah' ? 'selected' : '' ?>>Pindah</option>
                        </select>
                        <p class="text-xs text-gray-500 mt-1">Status siswa (Aktif/Lulus/Pindah)</p>
                    </div>
                </div>

                <!-- Tombol -->
                <div class="flex justify-end space-x-3 pt-4 border-t border-gray-200">
                    <a href="index.php" class="btn-outline-primary text-sm px-6 py-3">
                        <i class="fas fa-times mr-2"></i>Batal
                    </a>
                    <button type="submit" class="btn-primary text-sm px-6 py-3">
                        <i class="fas fa-save mr-2"></i>Update Data
                    </button>
                </div>
            </form>
        </div>
    </div>
</main>

<script>
$(document).ready(function() {
    // Auto hide alert after 5 seconds
    if ($('#alert-notification').length) {
        setTimeout(function() {
            $('#alert-notification').fadeOut('slow');
        }, 5000);
    }

    // Validasi form
    $('#editForm').on('submit', function(e) {
        let nis = $('input[name="nis"]').val();
        let nama = $('input[name="nama"]').val();
        let jk = $('input[name="jenis_kelamin"]:checked').val();
        let status = $('select[name="status"]').val();
        let errors = [];
        
        if (!nis) {
            errors.push('NIS harus diisi');
            $('input[name="nis"]').addClass('border-red-500');
        }
        
        if (!nama) {
            errors.push('Nama harus diisi');
            $('input[name="nama"]').addClass('border-red-500');
        }
        
        if (!jk) {
            errors.push('Jenis kelamin harus dipilih');
        }
        
        if (!status) {
            errors.push('Status siswa harus dipilih');
        }
        
        if (errors.length > 0) {
            e.preventDefault();
            alert('Validasi Gagal:\n- ' + errors.join('\n- '));
        }
    });

    // Remove red border on input
    $('input').on('input', function() {
        $(this).removeClass('border-red-500');
    });
});
</script>

<?php include '../../includes/footer.php'; ?>