<?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;

if (!$tahun_ajaran) {
    $_SESSION['alert'] = [
        'type' => 'warning',
        'title' => 'Peringatan!',
        'message' => 'Belum ada tahun ajaran aktif. Silakan aktifkan tahun ajaran terlebih dahulu.'
    ];
    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 tambah 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
        $check_nis = mysqli_query($conn, "SELECT * FROM bkcare_siswa WHERE nis = '$nis'");
        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. Buat akun user untuk siswa
            $username = $nis; // Username = NIS
            $password_default = password_hash('123', PASSWORD_DEFAULT); // Password default: 123
            
            // 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 dengan tambahan angka
                $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);
            
            // 2. Insert ke tabel siswa
            $query = "INSERT INTO bkcare_siswa (nis, nama, jenis_kelamin, alamat, no_hp, 
                      nama_orangtua, no_hp_orangtua, id_user, status) 
                      VALUES ('$nis', '$nama', '$jenis_kelamin', '$alamat', '$no_hp', 
                      '$nama_orangtua', '$no_hp_orangtua', '$id_user', '$status')";
            
            if (!mysqli_query($conn, $query)) {
                throw new Exception('Gagal menambahkan data siswa: ' . mysqli_error($conn));
            }
            
            $id_siswa = mysqli_insert_id($conn);
            
            // 3. Jika kelas dipilih, insert ke tabel siswa_kelas
            if ($id_kelas) {
                $query_kelas = "INSERT INTO bkcare_siswa_kelas (id_siswa, id_kelas, id_tahun_ajaran, status) 
                                VALUES ($id_siswa, $id_kelas, '$tahun_ajaran_id', 'aktif')";
                
                if (!mysqli_query($conn, $query_kelas)) {
                    throw new Exception('Gagal menambahkan data kelas siswa: ' . mysqli_error($conn));
                }
            }
            
            mysqli_commit($conn);
            
            $_SESSION['success_message'] = 'Data siswa <strong>' . $nama . '</strong> berhasil ditambahkan.<br>';
            $_SESSION['success_message'] .= 'Akun login: <strong>Username: ' . $username . '</strong>, Password: <strong>123</strong>';
            $_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: tambah.php');
            exit;
        }
    } else {
        $_SESSION['warning_message'] = implode('<br>', $errors);
        $_SESSION['warning_title'] = 'Validasi Gagal!';
        
        header('Location: tambah.php');
        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-user-plus text-purple-600 mr-3"></i>
                    Tambah Siswa
                </h1>
                <p class="text-gray-600 text-sm mt-1">Tambahkan data siswa baru (akun akan dibuat otomatis)</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 -->
        <div class="bg-blue-50 border-l-4 border-blue-500 p-4 mb-6 rounded-lg">
            <div class="flex items-center">
                <i class="fas fa-info-circle text-blue-500 mr-3 text-xl"></i>
                <div>
                    <p class="text-blue-700 font-medium">Informasi Akun:</p>
                    <p class="text-blue-600 text-sm">Akun siswa akan dibuat otomatis dengan:
                        <br>• Username = NIS
                        <br>• Password default = <strong>123</strong>
                    </p>
                </div>
            </div>
        </div>

        <!-- Form -->
        <div class="card-stat p-8">
            <form action="" method="POST" id="tambahForm" 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="<?= isset($_POST['nis']) ? htmlspecialchars($_POST['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="<?= isset($_POST['nama']) ? htmlspecialchars($_POST['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"
                                       <?= (isset($_POST['jenis_kelamin']) && $_POST['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"
                                       <?= (isset($_POST['jenis_kelamin']) && $_POST['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'] ?>" 
                                    <?= (isset($_POST['id_kelas']) && $_POST['id_kelas'] == $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"><?= isset($_POST['alamat']) ? htmlspecialchars($_POST['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="<?= isset($_POST['no_hp']) ? htmlspecialchars($_POST['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="<?= isset($_POST['nama_orangtua']) ? htmlspecialchars($_POST['nama_orangtua']) : '' ?>">
                    </div>
                </div>

                <!-- Status Siswa dan No. HP Orang Tua (SEJAJAR) -->
                <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="<?= isset($_POST['no_hp_orangtua']) ? htmlspecialchars($_POST['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" <?= (isset($_POST['status']) && $_POST['status'] == 'aktif') ? 'selected' : '' ?>>Aktif</option>
                            <option value="lulus" <?= (isset($_POST['status']) && $_POST['status'] == 'lulus') ? 'selected' : '' ?>>Lulus</option>
                            <option value="pindah" <?= (isset($_POST['status']) && $_POST['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>Simpan 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
    $('#tambahForm').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'; ?>