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

// Cek login
checkLogin();

$current_user = getCurrentUser();

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

// Ambil data guru
$query = "SELECT g.*, u.username, u.role, u.is_active, u.id_user as user_id
          FROM bkcare_guru g
          LEFT JOIN bkcare_users u ON g.id_user = u.id_user
          WHERE g.id_guru = $id";
$result = mysqli_query($conn, $query);
$data = mysqli_fetch_assoc($result);

if (!$data) {
    $_SESSION['alert'] = [
        'type' => 'error',
        'title' => 'Error!',
        'message' => 'Data guru tidak ditemukan'
    ];
    header('Location: index.php');
    exit;
}

// Proses update 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;
    $reset_password = isset($_POST['reset_password']) ? true : false;
    $ubah_status_akun = isset($_POST['ubah_status_akun']) ? $_POST['ubah_status_akun'] : null;
    
    // Validasi
    $errors = [];
    
    if (empty($nama_guru)) {
        $errors[] = 'Nama guru harus diisi';
    }
    
    // Validasi NIP
    if (!empty($nip)) {
        if (!preg_match('/^\d{8,}$/', $nip)) {
            $errors[] = 'NIP harus berupa angka minimal 8 digit';
        }
        
        // Cek duplikat NIP kecuali data sendiri
        $check_nip = mysqli_query($conn, "SELECT * FROM bkcare_guru WHERE nip = '$nip' AND id_guru != $id");
        if (mysqli_num_rows($check_nip) > 0) {
            $errors[] = 'NIP sudah digunakan';
        }
        
        // Jika NIP berubah dan sudah punya akun, cek username di tabel users
        if ($data['id_user'] && $nip != $data['username']) {
            $check_username = mysqli_query($conn, "SELECT * FROM bkcare_users WHERE username = '$nip' AND id_user != {$data['id_user']}");
            if (mysqli_num_rows($check_username) > 0) {
                $errors[] = 'Username (NIP) sudah digunakan di tabel users';
            }
        }
        
        // Jika buat akun baru, cek username di tabel users
        if ($buat_akun && !$data['id_user']) {
            $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';
            }
        }
    } else {
        // Jika ingin buat akun tapi NIP kosong
        if ($buat_akun && !$data['id_user']) {
            $errors[] = 'NIP wajib diisi jika ingin membuat akun';
        }
    }
    
    // Jika tidak ada error
    if (empty($errors)) {
        // Mulai transaksi
        mysqli_begin_transaction($conn);
        
        try {
            // Buat akun jika dipilih dan belum punya akun
            if ($buat_akun && !$data['id_user'] && !empty($nip)) {
                // Hash password default "123"
                $hashed_password = password_hash('123', PASSWORD_DEFAULT);
                $role = 'guru'; // Default role untuk 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);
                
                // Update id_user di tabel guru
                $update_guru = "UPDATE bkcare_guru SET id_user = $id_user WHERE id_guru = $id";
                if (!mysqli_query($conn, $update_guru)) {
                    throw new Exception('Gagal menghubungkan akun ke guru: ' . mysqli_error($conn));
                }
                
                $success_message = 'Data guru berhasil diperbarui.<br>';
                $success_message .= 'Akun user berhasil dibuat dengan:<br>';
                $success_message .= '• Username: <strong>' . $nip . '</strong><br>';
                $success_message .= '• Password: <strong>123</strong> (default)<br>';
                $success_message .= '• Role: <strong>Guru</strong>';
                
            } else {
                // Update akun user jika sudah ada
                if ($data['id_user']) {
                    $update_user = "UPDATE bkcare_users SET nama = '$nama_guru'";
                    
                    // Update username jika NIP berubah
                    if (!empty($nip) && $nip != $data['username']) {
                        $update_user .= ", username = '$nip'";
                    }
                    
                    // Reset password jika diminta
                    if ($reset_password) {
                        $hashed_password = password_hash('123', PASSWORD_DEFAULT);
                        $update_user .= ", password = '$hashed_password'";
                    }
                    
                    // Ubah status aktif/nonaktif
                    if ($ubah_status_akun == 'aktif') {
                        $update_user .= ", is_active = 1";
                    } elseif ($ubah_status_akun == 'nonaktif') {
                        $update_user .= ", is_active = 0";
                    }
                    
                    $update_user .= " WHERE id_user = {$data['id_user']}";
                    
                    if (!mysqli_query($conn, $update_user)) {
                        throw new Exception('Gagal memperbarui akun user: ' . mysqli_error($conn));
                    }
                }
            }
            
            // Update tabel guru
            $query = "UPDATE bkcare_guru 
                      SET nip = " . ($nip ? "'$nip'" : "NULL") . ", 
                          nama_guru = '$nama_guru' 
                      WHERE id_guru = $id";
            
            if (!mysqli_query($conn, $query)) {
                throw new Exception('Gagal memperbarui data guru: ' . mysqli_error($conn));
            }
            
            mysqli_commit($conn);
            
            // Buat pesan sukses jika belum ada
            if (!isset($success_message)) {
                $success_message = 'Data guru <strong>' . $nama_guru . '</strong> berhasil diperbarui.';
                if ($reset_password) {
                    $success_message .= '<br>Password akun telah direset ke <strong>123</strong> (default).';
                }
                if ($ubah_status_akun) {
                    $success_message .= '<br>Status akun telah diubah menjadi <strong>' . $ubah_status_akun . '</strong>.';
                }
            }
            
            // Set session untuk alert
            $_SESSION['alert'] = [
                'type' => 'success',
                'title' => 'Berhasil!',
                'message' => $success_message
            ];
            
            // 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: edit.php?id=' . $id);
            exit;
        }
    } else {
        $_SESSION['alert'] = [
            'type' => 'warning',
            'title' => 'Validasi Gagal!',
            'message' => implode('<br>', $errors)
        ];
        
        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-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-edit text-purple-600 mr-3"></i>
                    Edit Guru
                </h1>
                <p class="text-gray-600 text-sm mt-1">Edit data guru</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; 
        ?>

        <!-- Info Akun -->
        <?php if ($data['id_user']): ?>
        <div class="bg-blue-50 border-l-4 border-blue-500 p-4 mb-6 rounded-lg">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-info-circle text-blue-500"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-blue-700">
                        <span class="font-medium">Informasi Akun:</span><br>
                        Username: <strong><?= $data['username'] ?></strong> 
                        (<?= ucfirst(str_replace('_', ' ', $data['role'])) ?>)<br>
                        Status: 
                        <?php if ($data['is_active']): ?>
                            <span class="bg-green-100 text-green-800 px-2 py-0.5 rounded-full text-xs font-medium inline-flex items-center ml-1">
                                <i class="fas fa-check-circle mr-1"></i>Aktif
                            </span>
                        <?php else: ?>
                            <span class="bg-yellow-100 text-yellow-800 px-2 py-0.5 rounded-full text-xs font-medium inline-flex items-center ml-1">
                                <i class="fas fa-times-circle mr-1"></i>Nonaktif
                            </span>
                        <?php endif; ?>
                    </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">
                <div class="flex-shrink-0">
                    <i class="fas fa-exclamation-triangle text-yellow-500"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-yellow-700">
                        <span class="font-medium">Belum memiliki akun user.</span>
                        Anda dapat membuatkan akun menggunakan opsi di bawah.
                    </p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Form -->
        <div class="card-stat p-8">
            <form action="" method="POST" id="editForm">
                <!-- 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="<?= htmlspecialchars($data['nip'] ?? '') ?>"
                           <?= !$data['id_user'] ? 'id="nip_field"' : '' ?>>
                    <p class="text-xs text-gray-500 mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        Minimal 8 digit angka.
                    </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="<?= htmlspecialchars($data['nama_guru']) ?>"
                           required>
                </div>

                <!-- Opsi Buat Akun (hanya jika belum punya akun) -->
                <?php if (!$data['id_user']): ?>
                <div class="mb-6 p-4 border border-gray-200 rounded-xl bg-purple-50">
                    <h3 class="text-sm font-medium text-gray-700 mb-3 flex items-center">
                        <i class="fas fa-user-plus text-purple-600 mr-2"></i>
                        Buat Akun User
                    </h3>
                    
                    <label class="flex items-center cursor-pointer">
                        <input type="checkbox" 
                               name="buat_akun" 
                               id="buat_akun"
                               class="w-4 h-4 text-purple-600 border-gray-300 rounded focus:ring-purple-500 mr-3">
                        <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>
                <?php endif; ?>

                <!-- Opsi untuk Akun (hanya jika sudah punya akun) -->
                <?php if ($data['id_user']): ?>
                <div class="mb-6 p-4 border border-gray-200 rounded-xl bg-gray-50">
                    <h3 class="text-sm font-medium text-gray-700 mb-3 flex items-center">
                        <i class="fas fa-cog text-purple-600 mr-2"></i>
                        Pengaturan Akun
                    </h3>
                    
                    <!-- Reset Password -->
                    <div class="mb-4">
                        <label class="flex items-center cursor-pointer">
                            <input type="checkbox" 
                                   name="reset_password" 
                                   class="w-4 h-4 text-purple-600 border-gray-300 rounded focus:ring-purple-500 mr-3">
                            <div>
                                <span class="text-sm font-medium text-gray-700">Reset Password ke Default</span>
                                <p class="text-xs text-gray-500">
                                    Password akan direset menjadi <strong>123</strong>
                                </p>
                            </div>
                        </label>
                    </div>
                    
                    <!-- Ubah Status Akun -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Ubah Status Akun
                        </label>
                        <div class="flex space-x-4">
                            <label class="flex items-center">
                                <input type="radio" 
                                       name="ubah_status_akun" 
                                       value="aktif" 
                                       class="mr-2 text-purple-600 focus:ring-purple-500"
                                       <?= $data['is_active'] ? 'checked' : '' ?>>
                                <span class="text-sm text-gray-700">
                                    <i class="fas fa-check-circle text-green-500 mr-1"></i>Aktif
                                </span>
                            </label>
                            <label class="flex items-center">
                                <input type="radio" 
                                       name="ubah_status_akun" 
                                       value="nonaktif" 
                                       class="mr-2 text-purple-600 focus:ring-purple-500"
                                       <?= !$data['is_active'] ? 'checked' : '' ?>>
                                <span class="text-sm text-gray-700">
                                    <i class="fas fa-times-circle text-red-500 mr-1"></i>Nonaktif
                                </span>
                            </label>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- 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>Update 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() {
    $('#editForm').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 jika diisi atau akan buat akun
        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
    $('#buat_akun').on('change', function() {
        if ($(this).is(':checked')) {
            $('#nip_field').attr('required', true);
        } else {
            $('#nip_field').removeAttr('required');
        }
    });
});
</script>

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