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

// Cek login
checkLogin();

$current_user = getCurrentUser();

// Proses tambah data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nip = mysqli_real_escape_string($conn, $_POST['nip']);
    $nama_guru = mysqli_real_escape_string($conn, $_POST['nama_guru']);
    $buat_akun = isset($_POST['buat_akun']) ? true : false;
    
    // Validasi
    $errors = [];
    
    if (empty($nama_guru)) {
        $errors[] = 'Nama guru harus diisi';
    }
    
    // Validasi NIP (wajib jika ingin buat akun)
    if (empty($nip)) {
        if ($buat_akun) {
            $errors[] = 'NIP wajib diisi jika ingin membuat akun';
        }
    } else {
        // Cek format NIP (minimal 8 digit angka)
        if (!preg_match('/^\d{8,}$/', $nip)) {
            $errors[] = 'NIP harus berupa angka minimal 8 digit';
        }
        
        // Cek duplikat NIP di tabel guru
        $check_nip = mysqli_query($conn, "SELECT * FROM bkcare_guru WHERE nip = '$nip'");
        if (mysqli_num_rows($check_nip) > 0) {
            $errors[] = 'NIP sudah digunakan';
        }
        
        // Jika buat akun, cek juga apakah username (NIP) sudah digunakan di tabel users
        if ($buat_akun) {
            $check_username = mysqli_query($conn, "SELECT * FROM bkcare_users WHERE username = '$nip'");
            if (mysqli_num_rows($check_username) > 0) {
                $errors[] = 'Username (NIP) sudah digunakan di tabel users';
            }
        }
    }
    
    // Jika tidak ada error
    if (empty($errors)) {
        // Mulai transaksi
        mysqli_begin_transaction($conn);
        
        try {
            $id_user = 'NULL';
            
            // Buat akun user jika dipilih
            if ($buat_akun && !empty($nip)) {
                // Hash password default "123"
                $hashed_password = password_hash('123', PASSWORD_DEFAULT);
                // PERBAIKAN: Ubah default role dari 'guru_bk' menjadi 'guru'
                $role = 'guru'; 
                
                $query_user = "INSERT INTO bkcare_users (nama, username, password, role, is_active) 
                              VALUES ('$nama_guru', '$nip', '$hashed_password', '$role', 1)";
                
                if (!mysqli_query($conn, $query_user)) {
                    throw new Exception('Gagal membuat akun user: ' . mysqli_error($conn));
                }
                
                $id_user = mysqli_insert_id($conn);
            }
            
            // Insert ke tabel guru
            $query = "INSERT INTO bkcare_guru (id_user, nip, nama_guru) 
                      VALUES ($id_user, " . ($nip ? "'$nip'" : "NULL") . ", '$nama_guru')";
            
            if (!mysqli_query($conn, $query)) {
                throw new Exception('Gagal menambahkan data guru: ' . mysqli_error($conn));
            }
            
            mysqli_commit($conn);
            
            // Set session untuk alert
            $_SESSION['alert'] = [
                'type' => 'success',
                'title' => 'Berhasil!',
                'message' => 'Data guru <strong>' . $nama_guru . '</strong> berhasil ditambahkan.' . 
                             ($buat_akun ? '<br>Akun user dibuat dengan username: <strong>' . $nip . '</strong> dan password: <strong>123</strong>' : '')
            ];
            
            // Redirect ke index.php
            header('Location: index.php');
            exit;
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            
            $_SESSION['alert'] = [
                'type' => 'error',
                'title' => 'Gagal!',
                'message' => $e->getMessage()
            ];
            
            header('Location: tambah.php');
            exit;
        }
    } else {
        $_SESSION['alert'] = [
            'type' => 'warning',
            'title' => 'Validasi Gagal!',
            'message' => implode('<br>', $errors)
        ];
        
        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-2xl 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-plus-circle text-purple-600 mr-3"></i>
                    Tambah Guru
                </h1>
                <p class="text-gray-600 text-sm mt-1">Tambahkan data guru baru</p>
            </div>
        </div>

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

        <!-- Form -->
        <div class="card-stat p-8">
            <form action="" method="POST" id="tambahForm">
                <!-- NIP -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-id-card text-purple-600 mr-2"></i>
                        NIP
                    </label>
                    <input type="text" 
                           name="nip" 
                           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 NIP"
                           value="<?= isset($_POST['nip']) ? htmlspecialchars($_POST['nip']) : '' ?>">
                    <p class="text-xs text-gray-500 mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        Minimal 8 digit angka. Wajib diisi jika ingin membuat akun.
                    </p>
                </div>

                <!-- Nama Guru -->
                <div class="mb-6">
                    <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_guru" 
                           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 guru"
                           value="<?= isset($_POST['nama_guru']) ? htmlspecialchars($_POST['nama_guru']) : '' ?>"
                           required>
                </div>

                <!-- Opsi Buat Akun -->
                <div class="mb-8">
                    <label class="flex items-center p-4 bg-purple-50 rounded-xl cursor-pointer">
                        <input type="checkbox" 
                               name="buat_akun" 
                               id="buat_akun"
                               class="w-5 h-5 text-purple-600 border-gray-300 rounded focus:ring-purple-500 mr-3"
                               <?= isset($_POST['buat_akun']) ? 'checked' : '' ?>>
                        <div>
                            <span class="text-sm font-medium text-gray-700">Buatkan Akun User Otomatis</span>
                            <p class="text-xs text-gray-500 mt-1">
                                <i class="fas fa-info-circle mr-1"></i>
                                Akun akan dibuat dengan:
                            </p>
                            <ul class="text-xs text-gray-500 mt-1 list-disc list-inside">
                                <li>Username: <strong>NIP</strong></li>
                                <li>Password: <strong>123</strong> (default)</li>
                                <li>Role: <strong>Guru</strong></li>
                            </ul>
                        </div>
                    </label>
                </div>

                <!-- Tombol -->
                <div class="flex justify-end space-x-3">
                    <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>
// Auto hide alert after 5 seconds
$(document).ready(function() {
    if ($('#alert-notification').length) {
        setTimeout(function() {
            $('#alert-notification').fadeOut('slow');
        }, 5000);
    }
});

// Validasi form tambahan
$(document).ready(function() {
    $('#tambahForm').on('submit', function(e) {
        let nip = $('input[name="nip"]').val();
        let namaGuru = $('input[name="nama_guru"]').val();
        let buatAkun = $('#buat_akun').is(':checked');
        let errors = [];
        
        // Validasi NIP
        if (nip) {
            if (!/^\d{8,}$/.test(nip)) {
                errors.push('NIP harus berupa angka minimal 8 digit');
                $('input[name="nip"]').addClass('border-red-500 focus:ring-red-500');
            } else {
                $('input[name="nip"]').removeClass('border-red-500 focus:ring-red-500');
            }
        } else if (buatAkun) {
            errors.push('NIP wajib diisi jika ingin membuat akun');
            $('input[name="nip"]').addClass('border-red-500 focus:ring-red-500');
        } else {
            $('input[name="nip"]').removeClass('border-red-500 focus:ring-red-500');
        }
        
        // Validasi nama guru
        if (!namaGuru.trim()) {
            errors.push('Nama guru harus diisi');
            $('input[name="nama_guru"]').addClass('border-red-500 focus:ring-red-500');
        } else {
            $('input[name="nama_guru"]').removeClass('border-red-500 focus:ring-red-500');
        }
        
        if (errors.length > 0) {
            e.preventDefault();
            alert('Validasi Gagal:\n- ' + errors.join('\n- '));
        } else if (buatAkun) {
            // Konfirmasi jika membuat akun
            if (!confirm('Akun user akan dibuat dengan:\nUsername: ' + nip + '\nPassword: 123 (default)\nRole: Guru\n\nLanjutkan?')) {
                e.preventDefault();
            }
        }
    });
    
    // Toggle required pada NIP berdasarkan checkbox
    $('#buat_akun').on('change', function() {
        if ($(this).is(':checked')) {
            $('input[name="nip"]').attr('required', true);
        } else {
            $('input[name="nip"]').removeAttr('required');
        }
    });
});
</script>

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